chore: 初始化仓库,导入项目基线代码

Academy v0.8.3 完整代码基线:Go 后端(internal/cmd/cli/mcp-server/docreader)、
Vue 前端(frontend)、数据库迁移(migrations)、部署编排(docker/helm/deploy)与文档。
今日开发的培训推送管理改动随后单独提交。
This commit is contained in:
runny committed 2026-11-16 18:12:23 +08:00
commit 7ec21f35b0
5767 files changed
+1436788

No files matched your search

@@ -0,0 +1,85 @@
package sandbox
import (
"context"
"time"
"academy/internal/types/interfaces"
)
// MemoryActivityRegistry shares the binding store's background leases and lock,
// so single-process deployments also protect live work from rebuild and rewind.
type MemoryActivityRegistry struct {
store *MemorySessionSandboxBindingStore
}
var _ interfaces.ActivityRegistry = (*MemoryActivityRegistry)(nil)
// NewMemoryActivityRegistry returns the activity registry of store.
func NewMemoryActivityRegistry(store *MemorySessionSandboxBindingStore) *MemoryActivityRegistry {
return &MemoryActivityRegistry{store: store}
}
func memoryActivityKey(ctx context.Context, s interfaces.SessionRef) (SessionSandboxKey, error) {
key := SessionSandboxKey{TenantID: s.TenantID, SessionID: s.SessionID}
if err := key.Validate(); err != nil {
return key, err
}
return key, ctx.Err()
}
// Add implements interfaces.ActivityRegistry.
func (r *MemoryActivityRegistry) Add(
ctx context.Context, s interfaces.SessionRef, a interfaces.BackgroundActivity, lease time.Duration, kindCap int,
) error {
key, err := memoryActivityKey(ctx, s)
if err != nil {
return err
}
r.store.mu.Lock()
defer r.store.mu.Unlock()
if _, held := r.store.rewinds[key]; held {
return ErrSessionRewindLocked
}
return r.store.activity.Add(ctx, s, a, lease, kindCap)
}
// Renew implements interfaces.ActivityRegistry.
func (r *MemoryActivityRegistry) Renew(
ctx context.Context, s interfaces.SessionRef, id string, lease time.Duration,
) (bool, error) {
if _, err := memoryActivityKey(ctx, s); err != nil {
return false, err
}
r.store.mu.Lock()
defer r.store.mu.Unlock()
return r.store.activity.Renew(ctx, s, id, lease)
}
// Remove implements interfaces.ActivityRegistry.
func (r *MemoryActivityRegistry) Remove(ctx context.Context, s interfaces.SessionRef, id string) error {
if _, err := memoryActivityKey(ctx, s); err != nil {
return err
}
r.store.mu.Lock()
defer r.store.mu.Unlock()
return r.store.activity.Remove(ctx, s, id)
}
// List implements interfaces.ActivityRegistry.
func (r *MemoryActivityRegistry) List(
ctx context.Context, s interfaces.SessionRef,
) ([]interfaces.BackgroundActivity, error) {
if _, err := memoryActivityKey(ctx, s); err != nil {
return nil, err
}
r.store.mu.Lock()
defer r.store.mu.Unlock()
return r.store.activity.List(ctx, s)
}
// Caller holds s.mu, serializing the lease check with activity registration.
func (s *MemorySessionSandboxBindingStore) hasSessionActivityLocked(ctx context.Context, key SessionSandboxKey) bool {
items, err := s.activity.List(ctx, interfaces.SessionRef{TenantID: key.TenantID, SessionID: key.SessionID})
return err != nil || len(items) > 0
}
@@ -0,0 +1,100 @@
package sandbox
import (
"sync"
"testing"
"time"
"academy/internal/background"
"academy/internal/background/backgroundtest"
"academy/internal/types/interfaces"
"github.com/stretchr/testify/require"
)
type activityTestClock struct {
mu sync.Mutex
now time.Time
}
func (c *activityTestClock) Now() time.Time {
c.mu.Lock()
defer c.mu.Unlock()
return c.now
}
func (c *activityTestClock) advance(d time.Duration) {
c.mu.Lock()
defer c.mu.Unlock()
c.now = c.now.Add(d)
}
func TestBindingMemoryActivityRegistryContract(t *testing.T) {
backgroundtest.RunActivityRegistryContract(t,
func(_ *testing.T) (interfaces.ActivityRegistry, backgroundtest.Advance) {
store := NewMemorySessionSandboxBindingStore()
clock := &activityTestClock{now: time.Now()}
store.activity = background.NewMemoryActivityRegistry(clock)
return NewMemoryActivityRegistry(store), clock.advance
})
}
func TestMemoryActivityProtectsStaleSandboxAcrossTurns(t *testing.T) {
for _, release := range []string{"remove", "expire"} {
t.Run(release, func(t *testing.T) {
ctx := t.Context()
fx := newLifecycleFixture(t)
clock := &activityTestClock{now: time.Now()}
fx.bindings.activity = background.NewMemoryActivityRegistry(clock)
registry := NewMemoryActivityRegistry(fx.bindings)
ref := interfaces.SessionRef{TenantID: fx.key.TenantID, SessionID: fx.key.SessionID}
first, err := fx.lifecycle.Resolve(ctx, fx.key)
require.NoError(t, err)
require.NoError(t, registry.Add(ctx, ref, interfaces.BackgroundActivity{ID: "sj_1"}, time.Minute, 0))
_, err = fx.bindings.InvalidateByConfig(ctx, fx.key.TenantID, "cfg-1")
require.NoError(t, err)
active, rebuild, err := fx.bindings.TurnState(ctx, fx.key)
require.NoError(t, err)
require.True(t, active, "background work stays active after the submitting turn")
require.False(t, rebuild)
require.NoError(t, fx.bindings.BeginTurn(ctx, fx.key))
kept, err := fx.lifecycle.Resolve(ctx, fx.key)
require.NoError(t, err)
require.Equal(t, first.ID(), kept.ID())
require.Empty(t, fx.client.deleteIDs)
require.NoError(t, fx.bindings.EndTurn(ctx, fx.key))
if release == "remove" {
require.NoError(t, registry.Remove(ctx, ref, "sj_1"))
} else {
clock.advance(time.Minute)
}
require.NoError(t, fx.bindings.BeginTurn(ctx, fx.key))
replaced, err := fx.lifecycle.Resolve(ctx, fx.key)
require.NoError(t, err)
require.NotEqual(t, first.ID(), replaced.ID(), "completed or expired work must release the rebuild guard")
require.Equal(t, []string{first.ID()}, fx.client.deleteIDs)
require.NoError(t, fx.bindings.EndTurn(ctx, fx.key))
})
}
}
func TestMemoryActivityAndRewindAreExclusive(t *testing.T) {
ctx := t.Context()
store := NewMemorySessionSandboxBindingStore()
registry := NewMemoryActivityRegistry(store)
key := SessionSandboxKey{TenantID: 42, SessionID: "session-a"}
ref := interfaces.SessionRef{TenantID: key.TenantID, SessionID: key.SessionID}
item := interfaces.BackgroundActivity{ID: "sj_1"}
require.NoError(t, registry.Add(ctx, ref, item, time.Minute, 0))
_, err := store.TryLockRewind(ctx, key)
require.ErrorIs(t, err, ErrSessionWorkActive)
require.NoError(t, registry.Remove(ctx, ref, item.ID))
unlock, err := store.TryLockRewind(ctx, key)
require.NoError(t, err)
defer unlock()
require.ErrorIs(t, registry.Add(ctx, ref, item, time.Minute, 0), ErrSessionRewindLocked)
items, err := registry.List(ctx, ref)
require.NoError(t, err)
require.Empty(t, items)
}
+297
View File
@@ -0,0 +1,297 @@
package sandbox
import (
"context"
"encoding/json"
"fmt"
"strings"
"time"
"academy/internal/types/interfaces"
"github.com/redis/go-redis/v9"
)
// activityKeyGrace keeps the activity hash around briefly after its last
// deadline so a read racing the expiry still sees a well-formed key.
const activityKeyGrace = 60 * time.Second
// activityLiveCountLua defines now_ms() and live_count(key, now_ms): the
// latter deletes expired fields of the activity hash and returns how many
// remain. The turn-lease scripts in session_binding_redis.go prepend it so
// they can refuse a rebuild or a rewind while items are live.
const activityLiveCountLua = `
local function now_ms()
local t = redis.call('TIME')
return tonumber(t[1]) * 1000 + math.floor(tonumber(t[2]) / 1000)
end
local function live_count(key, now)
local raw = redis.call('HGETALL', key)
local live = 0
for i = 1, #raw, 2 do
local v = cjson.decode(raw[i + 1])
if tonumber(v['deadline_ms']) <= now then
redis.call('HDEL', key, raw[i])
else
live = live + 1
end
end
return live
end
`
// Every write refreshes the hash until its latest member expires. A shared
// machine mirrors each session's leases in a machine hash, in the same script
// and Redis slot, so sibling sessions cannot rebuild underneath them.
const activityWriteLua = `
local function save_activity(key, id, value, now, grace)
redis.call('HSET', key, id, cjson.encode(value))
local raw = redis.call('HGETALL', key)
local maxd = now
for i = 1, #raw, 2 do
local d = tonumber(cjson.decode(raw[i + 1])['deadline_ms'])
if d > maxd then maxd = d end
end
redis.call('PEXPIRE', key, maxd - now + grace)
end
`
// KEYS: session activity, machine activity, rewind, machine close, session close.
// ARGV[1] id, ARGV[2] kind, ARGV[3] title,
// ARGV[4] started_at_ms, ARGV[5] lease_ms, ARGV[6] kind cap (<=0 unlimited),
// ARGV[7] key grace ms, ARGV[8] machine member. Returns 1 on success, 0 at the cap.
var addActivityScript = redis.NewScript(activityLiveCountLua + activityWriteLua + `
local now = now_ms()
live_count(KEYS[1], now)
local deadline = now + tonumber(ARGV[5])
local existing = redis.call('HGET', KEYS[1], ARGV[1])
local v
if existing then
v = cjson.decode(existing)
v['deadline_ms'] = deadline
else
if redis.call('EXISTS', KEYS[3]) == 1 then
return redis.error_reply('ERR_SESSION_REWIND_LOCKED')
end
if redis.call('EXISTS', KEYS[4]) == 1 or redis.call('EXISTS', KEYS[5]) == 1 then
return redis.error_reply('ERR_SCOPE_CLOSED')
end
local cap = tonumber(ARGV[6])
if cap > 0 then
local raw = redis.call('HGETALL', KEYS[1])
local same = 0
for i = 1, #raw, 2 do
if cjson.decode(raw[i + 1])['kind'] == ARGV[2] then
same = same + 1
end
end
if same >= cap then
return 0
end
end
v = {
kind = ARGV[2], title = ARGV[3],
started_at_ms = tonumber(ARGV[4]), deadline_ms = deadline,
}
end
save_activity(KEYS[1], ARGV[1], v, now, tonumber(ARGV[7]))
if KEYS[2] ~= KEYS[1] then
live_count(KEYS[2], now)
save_activity(KEYS[2], ARGV[8], v, now, tonumber(ARGV[7]))
end
return 1
`)
// KEYS: session activity, machine activity.
// ARGV: id, lease_ms, key grace ms, machine member.
// Returns 1 when renewed, 0 when the item is missing or expired.
var renewActivityScript = redis.NewScript(activityLiveCountLua + activityWriteLua + `
local now = now_ms()
live_count(KEYS[1], now)
local existing = redis.call('HGET', KEYS[1], ARGV[1])
if not existing then
if KEYS[2] ~= KEYS[1] then redis.call('HDEL', KEYS[2], ARGV[4]) end
return 0
end
local v = cjson.decode(existing)
v['deadline_ms'] = now + tonumber(ARGV[2])
save_activity(KEYS[1], ARGV[1], v, now, tonumber(ARGV[3]))
if KEYS[2] ~= KEYS[1] then
live_count(KEYS[2], now)
save_activity(KEYS[2], ARGV[4], v, now, tonumber(ARGV[3]))
end
return 1
`)
var removeActivityScript = redis.NewScript(`
redis.call('HDEL', KEYS[1], ARGV[1])
if KEYS[2] ~= KEYS[1] then redis.call('HDEL', KEYS[2], ARGV[2]) end
return 1
`)
var countActivityScript = redis.NewScript(activityLiveCountLua + `
return live_count(KEYS[1], now_ms())
`)
// KEYS[1] activity hash. Returns the live fields as a flat [id, json, ...] list.
var listActivityScript = redis.NewScript(activityLiveCountLua + `
live_count(KEYS[1], now_ms())
return redis.call('HGETALL', KEYS[1])
`)
type redisActivityValue struct {
Kind string `json:"kind"`
Title string `json:"title"`
StartedAtMS int64 `json:"started_at_ms"`
DeadlineMS int64 `json:"deadline_ms"`
}
// RedisActivityRegistry is the multi-replica ActivityRegistry. It shares the
// binding store's client and hash tag so the turn-lease scripts can read it.
type RedisActivityRegistry struct {
store *RedisSessionSandboxBindingStore
allocations AllocationDirectory
}
var _ interfaces.ActivityRegistry = (*RedisActivityRegistry)(nil)
// NewRedisActivityRegistry returns a registry backed by store's Redis client.
func NewRedisActivityRegistry(store *RedisSessionSandboxBindingStore) *RedisActivityRegistry {
return &RedisActivityRegistry{store: store}
}
// WithAllocations uses each session's recorded placement to address shared
// machine leases. Configure it before using the registry.
func (r *RedisActivityRegistry) WithAllocations(allocations AllocationDirectory) *RedisActivityRegistry {
r.allocations = allocations
return r
}
func (s *RedisSessionSandboxBindingStore) activityKey(key SessionSandboxKey) string {
if key.IsUserScoped() && key.SessionID != "" {
return s.keyBase(key) + ":session:" + key.SessionID + ":activity"
}
return s.keyBase(key) + ":activity"
}
func (r *RedisActivityRegistry) key(ctx context.Context, s interfaces.SessionRef) (SessionSandboxKey, error) {
k := SessionSandboxKey{TenantID: s.TenantID, SessionID: s.SessionID}
if err := k.Validate(); err != nil {
return k, err
}
if r.allocations != nil {
a, found, err := r.allocations.SessionAllocation(ctx, s.SessionID)
if err != nil {
return k, fmt.Errorf("read background work allocation: %w", err)
}
if found && a.IsUser() {
k.User = a.Machine
}
}
return k, k.Validate()
}
func (r *RedisActivityRegistry) keys(key SessionSandboxKey) []string {
return []string{r.store.activityKey(key), r.store.activityKey(key.Machine())}
}
func activityMachineMember(key SessionSandboxKey, id string) string {
return key.SessionID + ":" + id
}
// hasBackgroundActivity includes every sibling session on a shared machine.
func (s *RedisSessionSandboxBindingStore) hasBackgroundActivity(
ctx context.Context, key SessionSandboxKey,
) (bool, error) {
n, err := countActivityScript.Run(ctx, s.client, []string{s.activityKey(key.Machine())}).Int64()
return n > 0, err
}
// Add implements interfaces.ActivityRegistry.
func (r *RedisActivityRegistry) Add(
ctx context.Context, s interfaces.SessionRef, a interfaces.BackgroundActivity, lease time.Duration, kindCap int,
) error {
key, err := r.key(ctx, s)
if err != nil {
return err
}
keys := append(r.keys(key), r.store.rewindKey(key))
if key.IsUserScoped() {
base := r.store.keyBase(key)
keys = append(keys, base+":machine:closed", base+":session:"+key.SessionID+":closed")
} else {
keys = append(keys, r.store.rewindKey(key), r.store.rewindKey(key))
}
ok, err := addActivityScript.Run(ctx, r.store.client, keys,
a.ID, a.Kind, a.Title, a.StartedAt.UnixMilli(), lease.Milliseconds(), kindCap,
activityKeyGrace.Milliseconds(), activityMachineMember(key, a.ID),
).Int64()
if err != nil {
if isRewindLockedRedisErr(err) {
return ErrSessionRewindLocked
}
if strings.Contains(err.Error(), "ERR_SCOPE_CLOSED") {
return ErrSessionWorkspaceBusy
}
return fmt.Errorf("add background activity: %w", err)
}
if ok == 0 {
return interfaces.ErrActivityLimit
}
return nil
}
// Renew implements interfaces.ActivityRegistry.
func (r *RedisActivityRegistry) Renew(
ctx context.Context, s interfaces.SessionRef, id string, lease time.Duration,
) (bool, error) {
key, err := r.key(ctx, s)
if err != nil {
return false, err
}
ok, err := renewActivityScript.Run(ctx, r.store.client, r.keys(key),
id, lease.Milliseconds(), activityKeyGrace.Milliseconds(), activityMachineMember(key, id),
).Int64()
if err != nil {
return false, fmt.Errorf("renew background activity: %w", err)
}
return ok == 1, nil
}
// Remove implements interfaces.ActivityRegistry.
func (r *RedisActivityRegistry) Remove(ctx context.Context, s interfaces.SessionRef, id string) error {
key, err := r.key(ctx, s)
if err != nil {
return err
}
err = removeActivityScript.Run(ctx, r.store.client, r.keys(key), id, activityMachineMember(key, id)).Err()
if err != nil {
return fmt.Errorf("remove background activity: %w", err)
}
return nil
}
// List implements interfaces.ActivityRegistry.
func (r *RedisActivityRegistry) List(
ctx context.Context, s interfaces.SessionRef,
) ([]interfaces.BackgroundActivity, error) {
key, err := r.key(ctx, s)
if err != nil {
return nil, err
}
flat, err := listActivityScript.Run(ctx, r.store.client, []string{r.store.activityKey(key)}).StringSlice()
if err != nil {
return nil, fmt.Errorf("list background activity: %w", err)
}
out := make([]interfaces.BackgroundActivity, 0, len(flat)/2)
for i := 0; i+1 < len(flat); i += 2 {
var v redisActivityValue
if err := json.Unmarshal([]byte(flat[i+1]), &v); err != nil {
return nil, fmt.Errorf("decode background activity %s: %w", flat[i], err)
}
out = append(out, interfaces.BackgroundActivity{
ID: flat[i], Kind: v.Kind, Title: v.Title,
StartedAt: time.UnixMilli(v.StartedAtMS).UTC(),
})
}
return out, nil
}
@@ -0,0 +1,215 @@
package sandbox
import (
"context"
"testing"
"time"
"academy/internal/background/backgroundtest"
"academy/internal/sandbox/admission"
"academy/internal/sandbox/allocation"
"academy/internal/types/interfaces"
"github.com/alicebob/miniredis/v2"
"github.com/stretchr/testify/require"
)
func TestRedisActivityRegistryContract(t *testing.T) {
backgroundtest.RunActivityRegistryContract(t,
func(t *testing.T) (interfaces.ActivityRegistry, backgroundtest.Advance) {
store, _, mini := newRedisBindingTestStore(t)
now := time.Date(2026, 10, 14, 10, 0, 0, 0, time.UTC)
mini.SetTime(now)
advance := func(d time.Duration) {
now = now.Add(d)
mini.SetTime(now)
mini.FastForward(d) // also expires key TTLs
}
return NewRedisActivityRegistry(store), advance
})
}
func TestRedisActivityRegistryUsesBindingHashTag(t *testing.T) {
store, _, _ := newRedisBindingTestStore(t)
key := SessionSandboxKey{TenantID: 7, SessionID: "s1"}
require.Equal(t, "academy:sandbox:session:{test:7:s1}:activity", store.activityKey(key))
require.Equal(t, "academy:sandbox:session:{test:7:s1}:turn", store.turnKey(key))
}
func TestRedisActivityRegistryRejectsInvalidSession(t *testing.T) {
store, _, _ := newRedisBindingTestStore(t)
r := NewRedisActivityRegistry(store)
err := r.Add(t.Context(), interfaces.SessionRef{}, interfaces.BackgroundActivity{ID: "x"}, time.Minute, 0)
require.Error(t, err)
}
// These managers use separate stores on the same Redis, as two replicas do.
func newSharedActivityManagers(
t *testing.T,
) (*userHarness, *userHarness, *RedisActivityRegistry, *miniredis.Miniredis) {
t.Helper()
store, client, mini := newRedisBindingTestStore(t)
other, err := NewRedisSessionSandboxBindingStore(client, store.namespace)
require.NoError(t, err)
allocs := newFakeAllocations(userAssignmentFor(userSessionA), userAssignmentFor(userSessionB))
remote := newFakeRemoteClient(SandboxTypeCube)
h1 := newUserManagerHarnessWithDirectory(t, remote, store,
admission.NewRedis(client, "academy:sandbox:user:"), allocs, store.namespace)
h2 := newUserManagerHarnessWithDirectory(t, remote, other,
admission.NewRedis(client, "academy:sandbox:user:"), allocs, store.namespace)
return h1, h2, NewRedisActivityRegistry(store).WithAllocations(allocs), mini
}
func useActivityTestSandbox(t *testing.T, mgr *SessionBoundManager, sessionID string) string {
t.Helper()
ctx, end, err := mgr.BeginSessionTurn(ownerCtx(), sessionID)
require.NoError(t, err)
defer end()
_, err = mgr.ExecShellCommand(ctx, sessionID, "true", "", time.Second, nil)
require.NoError(t, err)
id, bound := mgr.BoundSandboxID(ctx, sessionID)
require.True(t, bound)
return id
}
func TestRedisActivityProtectsSharedMachineFromSiblingRebuild(t *testing.T) {
for _, release := range []string{"remove", "expire"} {
t.Run(release, func(t *testing.T) {
h1, h2, registry, mini := newSharedActivityManagers(t)
now := time.Now()
mini.SetTime(now)
ctx := ownerCtx()
first := useActivityTestSandbox(t, h1.mgr, userSessionA)
ref := interfaces.SessionRef{TenantID: 42, SessionID: userSessionA}
require.NoError(t, registry.Add(ctx, ref, interfaces.BackgroundActivity{ID: "sj_1"}, time.Minute, 0))
n, err := h1.mgr.InvalidateConfigSandboxesForMachines(ctx, "cfg-1",
[]allocation.UserMachine{userAssignmentFor(userSessionA).Machine})
require.NoError(t, err)
require.Equal(t, 1, n)
require.Equal(t, first, useActivityTestSandbox(t, h2.mgr, userSessionB),
"another replica's sibling turn must not destroy the background job's machine")
require.Equal(t, first, useActivityTestSandbox(t, h2.mgr, userSessionA),
"the submitting session's next turn must also keep its machine")
require.Empty(t, h1.client.deleteIDs)
if release == "remove" {
require.NoError(t, registry.Remove(ctx, ref, "sj_1"))
} else {
mini.SetTime(now.Add(time.Minute))
mini.FastForward(time.Minute)
}
require.NotEqual(t, first, useActivityTestSandbox(t, h2.mgr, userSessionB))
require.Equal(t, []string{first}, h1.client.deleteIDs)
})
}
}
type activityBeforeCloseRegistry struct {
admission.Registry
beforeClose func()
}
func (r *activityBeforeCloseRegistry) Close(
ctx context.Context, scope admission.Scope, ttl time.Duration,
) (admission.Barrier, error) {
if r.beforeClose != nil {
f := r.beforeClose
r.beforeClose = nil
f()
}
return r.Registry.Close(ctx, scope, ttl)
}
func TestSharedRebuildRechecksActivityAfterClosingAdmission(t *testing.T) {
h1, h2, registry, _ := newSharedActivityManagers(t)
ctx := ownerCtx()
first := useActivityTestSandbox(t, h1.mgr, userSessionA)
_, err := h1.mgr.InvalidateConfigSandboxesForMachines(ctx, "cfg-1",
[]allocation.UserMachine{userAssignmentFor(userSessionA).Machine})
require.NoError(t, err)
ref := interfaces.SessionRef{TenantID: 42, SessionID: userSessionA}
raced := false
h2.mgr.lifecycle.admission = &activityBeforeCloseRegistry{
Registry: h2.mgr.admission,
beforeClose: func() {
raced = true
require.NoError(t, registry.Add(ctx, ref, interfaces.BackgroundActivity{ID: "sj_1"}, time.Minute, 0))
},
}
require.Equal(t, first, useActivityTestSandbox(t, h2.mgr, userSessionB))
require.True(t, raced, "register between the optimistic check and the machine barrier")
require.Empty(t, h1.client.deleteIDs)
}
func TestRedisActivityCannotRegisterThroughClosedAdmission(t *testing.T) {
for _, scopeKind := range []string{"machine", "session", "rewind"} {
t.Run(scopeKind, func(t *testing.T) {
h, _, registry, _ := newSharedActivityManagers(t)
ctx := ownerCtx()
ref := interfaces.SessionRef{TenantID: 42, SessionID: userSessionA}
key, err := registry.key(ctx, ref)
require.NoError(t, err)
want := ErrSessionWorkspaceBusy
if scopeKind == "rewind" {
unlock, err := registry.store.TryLockRewind(ctx, key)
require.NoError(t, err)
defer unlock()
want = ErrSessionRewindLocked
} else {
digest := key.User.Digest(registry.store.namespace)
scope := admission.MachineScope(digest)
if scopeKind == "session" {
scope = admission.SessionScope(digest, ref.SessionID)
}
barrier, err := h.mgr.admission.Close(ctx, scope, time.Minute)
require.NoError(t, err)
defer barrier.Release()
}
require.ErrorIs(t, registry.Add(ctx, ref, interfaces.BackgroundActivity{ID: "sj_1"}, time.Minute, 0), want)
items, err := registry.List(ctx, ref)
require.NoError(t, err)
require.Empty(t, items)
active, err := registry.store.hasBackgroundActivity(ctx, key)
require.NoError(t, err)
require.False(t, active)
})
}
}
func TestRedisSharedActivityLeasesRemainSessionScoped(t *testing.T) {
_, _, registry, mini := newSharedActivityManagers(t)
ctx := ownerCtx()
now := time.Now()
mini.SetTime(now)
a := interfaces.SessionRef{TenantID: 42, SessionID: userSessionA}
b := interfaces.SessionRef{TenantID: 42, SessionID: userSessionB}
key, err := registry.key(ctx, a)
require.NoError(t, err)
item := interfaces.BackgroundActivity{ID: "sj_1", Kind: "shell_job"}
require.NoError(t, registry.Add(ctx, a, item, 10*time.Second, 1))
items, err := registry.List(ctx, b)
require.NoError(t, err)
require.Empty(t, items)
// Caps and IDs are session scoped even on the same machine.
require.NoError(t, registry.Add(ctx, b, item, 10*time.Second, 1))
_, err = registry.store.TryLockRewind(ctx, key)
require.ErrorIs(t, err, ErrSessionWorkActive)
require.NoError(t, registry.Remove(ctx, a, item.ID))
unlock, err := registry.store.TryLockRewind(ctx, key)
require.NoError(t, err, "a sibling's work must not block this session's rewind")
unlock()
mini.SetTime(now.Add(8 * time.Second))
mini.FastForward(8 * time.Second)
found, err := registry.Renew(ctx, b, item.ID, time.Minute)
require.NoError(t, err)
require.True(t, found)
mini.SetTime(now.Add(20 * time.Second))
mini.FastForward(12 * time.Second)
active, err := registry.store.hasBackgroundActivity(ctx, key)
require.NoError(t, err)
require.True(t, active, "renew must extend the shared machine guard too")
require.NoError(t, registry.Remove(ctx, b, item.ID))
active, err = registry.store.hasBackgroundActivity(ctx, key)
require.NoError(t, err)
require.False(t, active)
}
+295
View File
@@ -0,0 +1,295 @@
// Package admission tracks operations in flight on a shared machine and on
// each session of it, so a rebuild, a reclaim, a rewind or a workspace delete
// can stop new work and wait for running work instead of cutting it off.
//
// Every user-mode operation holds a member in the machine scope and then in
// its session scope. A destructive path closes the scope it destroys, then
// requires ActiveExcept to report zero, and calls Barrier.Check before every
// destructive step. A lease that can no longer be confirmed reports Lost; the
// caller cancels the work it guards.
package admission
import (
"context"
"errors"
"strconv"
"sync"
"time"
)
var (
// ErrClosed reports that the scope is being rebuilt, reclaimed, or held
// exclusively.
ErrClosed = errors.New("sandbox: not admitting new operations")
// ErrLeaseLost reports a lease or barrier whose ownership can no longer
// be confirmed.
ErrLeaseLost = errors.New("sandbox: operation lease lost")
)
// DefaultHoldTTL bounds a holder that died without releasing.
const DefaultHoldTTL = 2 * time.Minute
// Scope names one admission domain. Tag is the machine digest, so every
// scope of a machine shares one Redis hash tag.
type Scope struct {
Tag string
Name string
}
// MachineScope covers every operation on a shared machine.
func MachineScope(digest string) Scope { return Scope{Tag: digest, Name: "machine"} }
// SessionScope covers one session's operations on its machine.
func SessionScope(digest, sessionID string) Scope {
return Scope{Tag: digest, Name: "session:" + sessionID}
}
// ConfigCreateScope registers provider creates of one sandbox config, so a
// config deletion can stop new creates and wait for running ones before it
// takes inventory.
func ConfigCreateScope(configTenantID uint64, configID string) Scope {
return Scope{Tag: "config:" + strconv.FormatUint(configTenantID, 10) + ":" + configID, Name: "create"}
}
// SessionMember names one operation of sessionID: kind is "turn", "shell",
// "file", "exec", "pty", "desktop", "fork" or "cleanup". token is unique per
// hold — including turns, which may nest — so releasing one hold never
// removes another.
func SessionMember(sessionID, kind, token string) string {
return "s:" + sessionID + ":" + kind + ":" + token
}
// Signal is the loss side of a lease or a barrier.
type Signal interface {
// Lost is closed once ownership can no longer be confirmed: the member
// is gone, or the local deadline passed without a confirmation.
Lost() <-chan struct{}
// Check returns ErrLeaseLost once Lost is closed or the deadline passed.
// Call it before every destructive step.
Check() error
}
// Lease is one registered operation.
type Lease interface {
Signal
Member() string
// Release removes the member. Idempotent.
Release()
}
// Barrier is an exclusive close of a scope.
type Barrier interface {
Signal
// Release reopens the scope. Idempotent, and exclusive with Seal:
// whichever runs first wins.
Release()
// Seal stops renewal and leaves the scope closed. It does not remove
// the closed flag, so new creates of this scope stay refused. Idempotent,
// and exclusive with Release.
Seal()
}
// Bind returns a context cancelled with ErrLeaseLost as soon as any of
// signals is lost, and a function that ends the watch and cancels the
// context. Pass the context to every provider call the signals protect, so a
// lost lease also stops the call in flight.
func Bind(ctx context.Context, signals ...Signal) (context.Context, func()) {
bound, cancel := context.WithCancelCause(ctx)
done := make(chan struct{})
for _, sig := range signals {
if sig == nil {
continue
}
if sig.Check() != nil {
cancel(ErrLeaseLost)
continue
}
lost := sig.Lost()
go func() {
select {
case <-lost:
cancel(ErrLeaseLost)
case <-done:
case <-bound.Done():
}
}()
}
var once sync.Once
return bound, func() {
once.Do(func() {
close(done)
cancel(nil)
})
}
}
// Registry is the admission contract. Implementations are safe for
// concurrent use.
type Registry interface {
Hold(ctx context.Context, scope Scope, member string, ttl time.Duration) (Lease, error)
ActiveExcept(ctx context.Context, scope Scope, except ...string) (int, error)
Close(ctx context.Context, scope Scope, ttl time.Duration) (Barrier, error)
}
// signal is the shared Lost/deadline/Release bookkeeping of leases and
// barriers. A zero deadline (the memory registry) never expires on its own.
type signal struct {
lost chan struct{}
lostOnce sync.Once
finishOnce sync.Once
release func()
// seal stops renewal without reopening. Nil on a memory barrier: the
// scope stays in the barrier map.
seal func()
mu sync.Mutex
deadline time.Time
timer *time.Timer
// stopped is set by Release. extend and the timer callback both refuse
// to arm another timer once it is set, so a confirmation that arrives
// as Release runs cannot resurrect the deadline.
stopped bool
}
func newSignal() *signal { return &signal{lost: make(chan struct{})} }
func (s *signal) markLost() {
s.mu.Lock()
s.closeLostLocked()
s.mu.Unlock()
}
func (s *signal) closeLostLocked() {
s.lostOnce.Do(func() { close(s.lost) })
}
func (s *signal) Lost() <-chan struct{} { return s.lost }
// extend moves the local deadline to sentAt+ttl-margin. sentAt is when the
// confirming request was sent: Redis may have applied it any time after, so
// counting from the reply would overstate how long the lease is still ours.
// A lost or released signal is never extended.
func (s *signal) extend(sentAt time.Time, ttl time.Duration) {
d := sentAt.Add(ttl - renewMargin(ttl))
s.mu.Lock()
defer s.mu.Unlock()
if s.stopped || s.lostClosed() {
return
}
if !s.deadline.IsZero() && !time.Now().Before(s.deadline) {
s.closeLostLocked()
return
}
if !d.After(s.deadline) {
return
}
s.deadline = d
s.armLocked(time.Until(d))
}
// armLocked schedules markLost at the deadline. A callback that wakes early,
// or one already in flight when the deadline moves, waits again instead of
// closing Lost. Go's AfterFunc Reset can run an already-started callback
// alongside the rescheduled one; the callback re-reads the deadline under
// s.mu so a stale wake cannot drop a lease that was just confirmed.
func (s *signal) armLocked(delay time.Duration) {
if s.timer != nil {
s.timer.Stop()
}
if delay <= 0 {
s.closeLostLocked()
return
}
s.timer = time.AfterFunc(delay, s.onDeadline)
}
func (s *signal) onDeadline() {
s.mu.Lock()
defer s.mu.Unlock()
if s.stopped || s.lostClosed() || s.deadline.IsZero() {
return
}
if delay := time.Until(s.deadline); delay > 0 {
// This wake is from an earlier deadline. Drop it and any timer it
// would race with, and wait out the deadline we hold now.
if s.timer != nil {
s.timer.Stop()
}
s.timer = time.AfterFunc(delay, s.onDeadline)
return
}
s.closeLostLocked()
}
func (s *signal) lostClosed() bool {
select {
case <-s.lost:
return true
default:
return false
}
}
func (s *signal) currentDeadline() time.Time {
s.mu.Lock()
defer s.mu.Unlock()
return s.deadline
}
func (s *signal) Release() { s.finish(true) }
// Seal stops the local deadline timer the same way Release does, so it
// cannot mark the barrier lost, and runs the non-reopening callback.
func (b *barrier) Seal() { b.finish(false) }
func (s *signal) finish(reopen bool) {
s.finishOnce.Do(func() {
s.mu.Lock()
s.stopped = true
if s.timer != nil {
s.timer.Stop()
s.timer = nil
}
s.mu.Unlock()
if reopen {
if s.release != nil {
s.release()
}
return
}
if s.seal != nil {
s.seal()
}
})
}
func (s *signal) Check() error {
s.mu.Lock()
defer s.mu.Unlock()
if s.lostClosed() {
return ErrLeaseLost
}
// Release and Seal both stop the deadline. A stopped signal is not a
// loss, even if the old deadline has since passed.
if s.stopped {
return nil
}
if d := s.deadline; !d.IsZero() && !time.Now().Before(d) {
s.closeLostLocked()
return ErrLeaseLost
}
return nil
}
type lease struct {
*signal
member string
}
func (l *lease) Member() string { return l.member }
type barrier struct{ *signal }
// renewMargin is how long before expiry an unconfirmed lease is declared
// lost: the holder must stop before another replica can see it as gone.
func renewMargin(ttl time.Duration) time.Duration { return ttl / 6 }
@@ -0,0 +1,396 @@
package admission
import (
"context"
"strconv"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/alicebob/miniredis/v2"
"github.com/redis/go-redis/v9"
"github.com/stretchr/testify/require"
)
const prefix = "academy:sandbox:user:"
func newRedis(t *testing.T) (*RedisRegistry, *miniredis.Miniredis) {
t.Helper()
mini := miniredis.RunT(t)
client := redis.NewClient(&redis.Options{Addr: mini.Addr()})
t.Cleanup(func() { _ = client.Close() })
return NewRedis(client, prefix), mini
}
func registries(t *testing.T) map[string]Registry {
r, _ := newRedis(t)
return map[string]Registry{"redis": r, "memory": NewMemory()}
}
func waitClosed(t *testing.T, ch <-chan struct{}) {
t.Helper()
select {
case <-ch:
case <-time.After(2 * time.Second):
t.Fatal("expected the lease to be reported lost")
}
}
func TestRegistryContract(t *testing.T) {
for name, reg := range registries(t) {
t.Run(name, func(t *testing.T) {
ctx := context.Background()
machine := MachineScope("d-1")
a := SessionMember("s1", "turn", "t1")
b := SessionMember("s1", "pty", "p1")
c := SessionMember("s2", "shell", "x1")
la, err := reg.Hold(ctx, machine, a, time.Minute)
require.NoError(t, err)
lb, err := reg.Hold(ctx, machine, b, time.Minute)
require.NoError(t, err)
lc, err := reg.Hold(ctx, machine, c, time.Minute)
require.NoError(t, err)
n, err := reg.ActiveExcept(ctx, machine)
require.NoError(t, err)
require.Equal(t, 3, n)
n, err = reg.ActiveExcept(ctx, machine, a)
require.NoError(t, err)
require.Equal(t, 2, n, "only the exact members passed are exempt; the same session's PTY still counts")
n, err = reg.ActiveExcept(ctx, SessionScope("d-1", "s1"))
require.NoError(t, err)
require.Zero(t, n, "scopes are independent")
barrier, err := reg.Close(ctx, machine, time.Minute)
require.NoError(t, err)
require.NoError(t, barrier.Check())
_, err = reg.Hold(ctx, machine, SessionMember("s3", "file", "f"), time.Minute)
require.ErrorIs(t, err, ErrClosed)
_, err = reg.Close(ctx, machine, time.Minute)
require.ErrorIs(t, err, ErrClosed, "a second closer backs off")
la.Release()
lb.Release()
lc.Release()
la.Release() // idempotent
n, err = reg.ActiveExcept(ctx, machine)
require.NoError(t, err)
require.Zero(t, n)
barrier.Release()
l, err := reg.Hold(ctx, machine, SessionMember("s3", "file", "f2"), time.Minute)
require.NoError(t, err)
require.Equal(t, SessionMember("s3", "file", "f2"), l.Member())
l.Release()
})
}
}
func TestRedisRenewNeverResurrectsAnExpiredMember(t *testing.T) {
reg, mini := newRedis(t)
ctx := context.Background()
scope := MachineScope("d-1")
lease, err := reg.Hold(ctx, scope, SessionMember("s", "shell", "1"), 300*time.Millisecond)
require.NoError(t, err)
defer lease.Release()
// Redis TIME jumps past the lease: the member has expired server-side.
mini.SetTime(time.Now().Add(time.Hour))
waitClosed(t, lease.Lost())
// The renew loop ticks every ttl/3. Wait past one more tick so a loop
// that re-added the member after declaring it lost cannot hide.
time.Sleep(200 * time.Millisecond)
n, err := reg.ActiveExcept(ctx, scope)
require.NoError(t, err)
require.Zero(t, n, "an expired member must not be re-registered by its renew loop")
}
func TestRedisLeaseIsLostWhenRedisIsUnreachable(t *testing.T) {
reg, mini := newRedis(t)
lease, err := reg.Hold(
context.Background(), MachineScope("d-1"), SessionMember("s", "shell", "1"), 300*time.Millisecond,
)
require.NoError(t, err)
defer lease.Release()
mini.Close()
waitClosed(t, lease.Lost())
}
// stallHook makes every command hang until its context ends, the way a
// Redis behind a partition does.
type stallHook struct{ stall *atomic.Bool }
func (h stallHook) DialHook(next redis.DialHook) redis.DialHook { return next }
func (h stallHook) ProcessHook(next redis.ProcessHook) redis.ProcessHook {
return func(ctx context.Context, cmd redis.Cmder) error {
if h.stall.Load() {
<-ctx.Done()
return ctx.Err()
}
return next(ctx, cmd)
}
}
func (h stallHook) ProcessPipelineHook(next redis.ProcessPipelineHook) redis.ProcessPipelineHook {
return next
}
func newStallingRedis(t *testing.T) (*RedisRegistry, *atomic.Bool) {
t.Helper()
mini := miniredis.RunT(t)
client := redis.NewClient(&redis.Options{Addr: mini.Addr()})
t.Cleanup(func() { _ = client.Close() })
stall := &atomic.Bool{}
client.AddHook(stallHook{stall: stall})
return NewRedis(client, prefix), stall
}
func TestRedisLeaseIsLostAtItsLocalDeadlineWhileRenewStalls(t *testing.T) {
reg, stall := newStallingRedis(t)
ttl := 600 * time.Millisecond
lease, err := reg.Hold(context.Background(), MachineScope("d-1"), SessionMember("s", "shell", "1"), ttl)
require.NoError(t, err)
defer lease.Release()
stall.Store(true)
stalledAt := time.Now()
waitClosed(t, lease.Lost())
// The last confirmed request was sent before stalledAt, so the deadline
// is at most ttl-ttl/6 after it. Losing it only at Redis expiry (ttl) or
// after the hung call returns would let another replica act first.
require.Less(t, time.Since(stalledAt), ttl)
require.ErrorIs(t, lease.Check(), ErrLeaseLost)
}
func TestRedisBarrierIsLostAtItsLocalDeadlineWhileRenewStalls(t *testing.T) {
reg, stall := newStallingRedis(t)
ttl := 600 * time.Millisecond
barrier, err := reg.Close(context.Background(), MachineScope("d-1"), ttl)
require.NoError(t, err)
defer barrier.Release()
stall.Store(true)
stalledAt := time.Now()
waitClosed(t, barrier.Lost())
require.Less(t, time.Since(stalledAt), ttl)
require.ErrorIs(t, barrier.Check(), ErrLeaseLost)
}
func TestBindCancelsWhenAnySignalIsLost(t *testing.T) {
reg := NewMemory()
ctx := context.Background()
lease, err := reg.Hold(ctx, MachineScope("d"), SessionMember("s", "shell", "1"), time.Minute)
require.NoError(t, err)
barrier, err := reg.Close(ctx, SessionScope("d", "s"), time.Minute)
require.NoError(t, err)
bound, stop := Bind(ctx, lease, barrier)
defer stop()
require.NoError(t, bound.Err())
reg.LoseBarrier(SessionScope("d", "s"))
waitClosed(t, bound.Done())
require.ErrorIs(t, context.Cause(bound), ErrLeaseLost)
again, stopAgain := Bind(ctx, lease)
stopAgain()
require.ErrorIs(t, again.Err(), context.Canceled, "stop ends the watch and the context")
require.NotErrorIs(t, context.Cause(again), ErrLeaseLost, "stop is not a loss")
}
func TestBindOnAnAlreadyLostSignalIsCancelledAtOnce(t *testing.T) {
reg := NewMemory()
scope := MachineScope("d")
member := SessionMember("s", "shell", "1")
lease, err := reg.Hold(context.Background(), scope, member, time.Minute)
require.NoError(t, err)
reg.ExpireMember(scope, member)
bound, stop := Bind(context.Background(), lease)
defer stop()
require.ErrorIs(t, context.Cause(bound), ErrLeaseLost)
}
func TestRedisBarrierRenewsAndReportsLoss(t *testing.T) {
reg, mini := newRedis(t)
ctx := context.Background()
scope := MachineScope("d-1")
barrier, err := reg.Close(ctx, scope, 300*time.Millisecond)
require.NoError(t, err)
defer barrier.Release()
// miniredis ages key TTLs only when FastForward is called, not during a
// wall-clock sleep. Leave a short remainder of the initial TTL, wait for
// a renew to PEXPIRE the key back to a full TTL, then jump farther than
// that remainder. Without a renew the key is gone.
mini.FastForward(250 * time.Millisecond)
time.Sleep(250 * time.Millisecond) // renew interval is ttl/3 = 100ms
mini.FastForward(100 * time.Millisecond)
require.True(t, mini.Exists(prefix+"{d-1}:machine:closed"), "the barrier outlives its initial TTL while held")
require.NoError(t, barrier.Check())
mini.Del(prefix + "{d-1}:machine:closed")
waitClosed(t, barrier.Lost())
require.ErrorIs(t, barrier.Check(), ErrLeaseLost)
}
func TestRedisKeysShareTheMachineHashTag(t *testing.T) {
reg, mini := newRedis(t)
l, err := reg.Hold(context.Background(), SessionScope("abc", "s1"), SessionMember("s1", "x", "1"), time.Minute)
require.NoError(t, err)
defer l.Release()
require.True(t, mini.Exists(prefix+"{abc}:session:s1:ops"))
}
func TestMemoryHooksSimulateLoss(t *testing.T) {
reg := NewMemory()
ctx := context.Background()
scope := MachineScope("d")
member := SessionMember("s", "shell", "1")
lease, err := reg.Hold(ctx, scope, member, time.Minute)
require.NoError(t, err)
reg.ExpireMember(scope, member)
waitClosed(t, lease.Lost())
n, _ := reg.ActiveExcept(ctx, scope)
require.Zero(t, n)
barrier, err := reg.Close(ctx, scope, time.Minute)
require.NoError(t, err)
reg.LoseBarrier(scope)
waitClosed(t, barrier.Lost())
require.ErrorIs(t, barrier.Check(), ErrLeaseLost)
}
func TestReleaseIsIdempotentAndIsNotLoss(t *testing.T) {
for name, reg := range registries(t) {
t.Run(name, func(t *testing.T) {
ctx := context.Background()
scope := MachineScope("d")
lease, err := reg.Hold(ctx, scope, SessionMember("s", "shell", "1"), time.Minute)
require.NoError(t, err)
lease.Release()
lease.Release()
select {
case <-lease.Lost():
t.Fatal("release must not report the lease lost")
default:
}
require.NoError(t, lease.Check())
n, err := reg.ActiveExcept(ctx, scope)
require.NoError(t, err)
require.Zero(t, n)
barrier, err := reg.Close(ctx, scope, time.Minute)
require.NoError(t, err)
barrier.Release()
barrier.Release()
select {
case <-barrier.Lost():
t.Fatal("release must not report the barrier lost")
default:
}
require.NoError(t, barrier.Check())
again, err := reg.Hold(ctx, scope, SessionMember("s", "shell", "2"), time.Minute)
require.NoError(t, err)
again.Release()
})
}
}
func TestConcurrentHoldAndRelease(t *testing.T) {
for name, reg := range registries(t) {
t.Run(name, func(t *testing.T) {
ctx := context.Background()
scope := MachineScope("d-conc")
var wg sync.WaitGroup
for i := 0; i < 8; i++ {
wg.Add(1)
go func(i int) {
defer wg.Done()
member := SessionMember("s", "shell", strconv.Itoa(i))
for n := 0; n < 15; n++ {
lease, err := reg.Hold(ctx, scope, member, time.Minute)
if err != nil {
t.Errorf("hold: %v", err)
return
}
if _, err := reg.ActiveExcept(ctx, scope, member); err != nil {
t.Errorf("count: %v", err)
}
lease.Release()
lease.Release()
}
}(i)
}
wg.Wait()
n, err := reg.ActiveExcept(ctx, scope)
require.NoError(t, err)
require.Zero(t, n)
})
}
}
// A short hold must not cut the key's lifetime below a longer member's
// deadline: once the key expires, ActiveExcept would see an idle machine while
// the long operation is still running.
func TestRedisShortHoldNeverShortensALongerLease(t *testing.T) {
reg, mini := newRedis(t)
ctx := context.Background()
scope := MachineScope("d-ttl")
long, err := reg.Hold(ctx, scope, SessionMember("a", "turn", "1"), 30*time.Minute)
require.NoError(t, err)
defer long.Release()
short, err := reg.Hold(ctx, scope, SessionMember("b", "shell", "1"), 2*time.Minute)
require.NoError(t, err)
short.Release()
ops := reg.key(scope, "ops")
require.GreaterOrEqual(t, mini.TTL(ops), 30*time.Minute, "the key outlives its longest member")
mini.FastForward(5 * time.Minute)
n, err := reg.ActiveExcept(ctx, scope)
require.NoError(t, err)
require.Equal(t, 1, n, "the long lease is still registered")
}
func TestSealKeepsTheScopeClosedWithoutReportingLoss(t *testing.T) {
ctx := context.Background()
scope := ConfigCreateScope(7, "cfg-a")
t.Run("memory", func(t *testing.T) {
reg := NewMemory()
barrier, err := reg.Close(ctx, scope, time.Minute)
require.NoError(t, err)
barrier.Seal()
barrier.Seal()
_, err = reg.Hold(ctx, scope, "create:again", time.Minute)
require.ErrorIs(t, err, ErrClosed)
_, err = reg.Close(ctx, scope, time.Minute)
require.ErrorIs(t, err, ErrClosed)
select {
case <-barrier.Lost():
t.Fatal("seal must not report the barrier lost")
default:
}
require.NoError(t, barrier.Check())
})
t.Run("redis", func(t *testing.T) {
reg, mini := newRedis(t)
barrier, err := reg.Close(ctx, scope, 300*time.Millisecond)
require.NoError(t, err)
barrier.Seal()
time.Sleep(400 * time.Millisecond)
mini.FastForward(time.Second)
key := prefix + "{config:7:cfg-a}:create:closed"
require.True(t, mini.Exists(key), "seal persists the closed flag past its TTL")
require.Equal(t, time.Duration(0), mini.TTL(key))
_, err = reg.Hold(ctx, scope, "create:again", time.Minute)
require.ErrorIs(t, err, ErrClosed)
select {
case <-barrier.Lost():
t.Fatal("seal must not report the barrier lost")
default:
}
require.NoError(t, barrier.Check())
})
}
+122
View File
@@ -0,0 +1,122 @@
package admission
import (
"context"
"sync"
"time"
)
// MemoryRegistry is a process-local Registry for tests and single-process
// deployments. User mode is never enabled without Redis, so multi-replica
// production never uses it. Leases never expire on their own; tests force
// loss with ExpireMember and LoseBarrier.
type MemoryRegistry struct {
mu sync.Mutex
members map[Scope]map[string]*lease
barriers map[Scope]*barrier
}
// NewMemory builds an empty registry.
func NewMemory() *MemoryRegistry {
return &MemoryRegistry{members: map[Scope]map[string]*lease{}, barriers: map[Scope]*barrier{}}
}
// Hold registers member until Release. The memory registry does not expire on its own.
func (r *MemoryRegistry) Hold(_ context.Context, scope Scope, member string, _ time.Duration) (Lease, error) {
r.mu.Lock()
defer r.mu.Unlock()
if _, closed := r.barriers[scope]; closed {
return nil, ErrClosed
}
set := r.members[scope]
if set == nil {
set = map[string]*lease{}
r.members[scope] = set
}
l := &lease{signal: newSignal(), member: member}
l.release = func() {
r.mu.Lock()
defer r.mu.Unlock()
if r.members[scope][member] == l {
delete(r.members[scope], member)
}
}
set[member] = l
return l, nil
}
// ActiveExcept counts members of scope other than except.
func (r *MemoryRegistry) ActiveExcept(_ context.Context, scope Scope, except ...string) (int, error) {
r.mu.Lock()
defer r.mu.Unlock()
skip := make(map[string]struct{}, len(except))
for _, m := range except {
skip[m] = struct{}{}
}
n := 0
for m := range r.members[scope] {
if _, ok := skip[m]; !ok {
n++
}
}
return n, nil
}
// Close stops new holds on scope until the barrier is released.
func (r *MemoryRegistry) Close(_ context.Context, scope Scope, _ time.Duration) (Barrier, error) {
r.mu.Lock()
defer r.mu.Unlock()
if _, closed := r.barriers[scope]; closed {
return nil, ErrClosed
}
b := &barrier{signal: newSignal()}
b.release = func() {
r.mu.Lock()
defer r.mu.Unlock()
if r.barriers[scope] == b {
delete(r.barriers, scope)
}
}
r.barriers[scope] = b
return b, nil
}
// ExpireScope marks every member of scope lost. Tests use it when the
// member token is chosen inside the call under test.
func (r *MemoryRegistry) ExpireScope(scope Scope) {
r.mu.Lock()
set := r.members[scope]
delete(r.members, scope)
lost := make([]*lease, 0, len(set))
for _, l := range set {
lost = append(lost, l)
}
r.mu.Unlock()
for _, l := range lost {
l.markLost()
}
}
// ExpireMember simulates a lease that expired server-side.
func (r *MemoryRegistry) ExpireMember(scope Scope, member string) {
r.mu.Lock()
l := r.members[scope][member]
delete(r.members[scope], member)
r.mu.Unlock()
if l != nil {
l.markLost()
}
}
// LoseBarrier simulates a barrier whose ownership could not be renewed.
func (r *MemoryRegistry) LoseBarrier(scope Scope) {
r.mu.Lock()
b := r.barriers[scope]
delete(r.barriers, scope)
r.mu.Unlock()
if b != nil {
b.markLost()
}
}
var _ Registry = (*MemoryRegistry)(nil)
+214
View File
@@ -0,0 +1,214 @@
package admission
import (
"context"
"fmt"
"strings"
"time"
"academy/internal/common/redislock"
"github.com/redis/go-redis/v9"
)
const redisNowLua = "local t = redis.call('TIME'); " +
"local now = tonumber(t[1]) * 1000 + math.floor(tonumber(t[2]) / 1000)"
// KEYS[1] ops zset, KEYS[2] closed flag. ARGV[1] member, ARGV[2] ttl ms.
var holdScript = redis.NewScript(redisNowLua + `
if redis.call('EXISTS', KEYS[2]) == 1 then return redis.error_reply('ERR_SCOPE_CLOSED') end
redis.call('ZREMRANGEBYSCORE', KEYS[1], '-inf', now)
redis.call('ZADD', KEYS[1], now + tonumber(ARGV[2]), ARGV[1])
-- The zset holds every member's lease; only ever extend its lifetime, or a
-- short hold would expire the key under a longer, still-live member.
local keep = tonumber(ARGV[2]) * 2
if redis.call('PTTL', KEYS[1]) < keep then redis.call('PEXPIRE', KEYS[1], keep) end
return 1
`)
// Renewal only extends a member that is still live. An expired member is
// removed and reported lost: another replica may already have acted on its
// absence, so it must never come back. Renewing while the scope is closed is
// allowed — it protects work the closer is waiting for.
var renewScript = redis.NewScript(redisNowLua + `
local score = redis.call('ZSCORE', KEYS[1], ARGV[1])
if (not score) or tonumber(score) <= now then
redis.call('ZREM', KEYS[1], ARGV[1])
return 0
end
redis.call('ZADD', KEYS[1], 'XX', now + tonumber(ARGV[2]), ARGV[1])
-- The zset holds every member's lease; only ever extend its lifetime, or a
-- short hold would expire the key under a longer, still-live member.
local keep = tonumber(ARGV[2]) * 2
if redis.call('PTTL', KEYS[1]) < keep then redis.call('PEXPIRE', KEYS[1], keep) end
return 1
`)
// ARGV: exempt members.
var activeExceptScript = redis.NewScript(redisNowLua + `
redis.call('ZREMRANGEBYSCORE', KEYS[1], '-inf', now)
local members = redis.call('ZRANGEBYSCORE', KEYS[1], now, '+inf')
local skip = {}
for i = 1, #ARGV do skip[ARGV[i]] = true end
local n = 0
for _, m in ipairs(members) do
if not skip[m] then n = n + 1 end
end
return n
`)
// RedisRegistry is the distributed admission registry.
type RedisRegistry struct {
client redis.UniversalClient
prefix string
}
// NewRedis builds a registry whose keys start with keyPrefix, e.g.
// "academy:sandbox:user:", matching the user binding keys.
func NewRedis(client redis.UniversalClient, keyPrefix string) *RedisRegistry {
return &RedisRegistry{client: client, prefix: keyPrefix}
}
func (r *RedisRegistry) key(scope Scope, suffix string) string {
return r.prefix + "{" + scope.Tag + "}:" + scope.Name + ":" + suffix
}
// Hold registers member until Release or until the lease can no longer be renewed.
func (r *RedisRegistry) Hold(ctx context.Context, scope Scope, member string, ttl time.Duration) (Lease, error) {
if ttl <= 0 {
ttl = DefaultHoldTTL
}
ops, closed := r.key(scope, "ops"), r.key(scope, "closed")
sent := time.Now()
if err := holdScript.Run(ctx, r.client, []string{ops, closed}, member, ttl.Milliseconds()).Err(); err != nil {
if strings.Contains(err.Error(), "ERR_SCOPE_CLOSED") {
return nil, ErrClosed
}
return nil, fmt.Errorf("admission: hold %s: %w", member, err)
}
l := &lease{signal: newSignal(), member: member}
l.extend(sent, ttl)
renewCtx, stop := context.WithCancel(context.WithoutCancel(ctx))
l.release = func() {
stop()
relCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
_ = r.client.ZRem(relCtx, ops, member).Err()
}
go r.renewLease(renewCtx, l, ops, ttl)
return l, nil
}
// renewLease confirms the lease every ttl/3. Each request is bounded by the
// local deadline; a failed or hung renewal leaves the deadline where it was,
// and the deadline timer reports the loss on time.
func (r *RedisRegistry) renewLease(ctx context.Context, l *lease, ops string, ttl time.Duration) {
ticker := time.NewTicker(renewInterval(ttl))
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return
case <-l.Lost():
return
case <-ticker.C:
sent := time.Now()
callCtx, cancel := context.WithDeadline(ctx, l.currentDeadline())
n, err := renewScript.Run(callCtx, r.client, []string{ops}, l.member, ttl.Milliseconds()).Int()
cancel()
switch {
case err == nil && n == 1:
l.extend(sent, ttl)
case err == nil:
l.markLost()
return
}
}
}
}
// ActiveExcept counts members of scope other than except.
func (r *RedisRegistry) ActiveExcept(ctx context.Context, scope Scope, except ...string) (int, error) {
args := make([]any, len(except))
for i, m := range except {
args[i] = m
}
n, err := activeExceptScript.Run(ctx, r.client, []string{r.key(scope, "ops")}, args...).Int()
if err != nil {
return 0, fmt.Errorf("admission: count %s/%s: %w", scope.Tag, scope.Name, err)
}
return n, nil
}
// Close stops new holds on scope until the barrier is released.
func (r *RedisRegistry) Close(ctx context.Context, scope Scope, ttl time.Duration) (Barrier, error) {
token, err := redislock.NewToken()
if err != nil {
return nil, err
}
key := r.key(scope, "closed")
sent := time.Now()
ok, err := redislock.TryAcquire(ctx, r.client, key, token, ttl)
if err != nil {
return nil, fmt.Errorf("admission: close %s/%s: %w", scope.Tag, scope.Name, err)
}
if !ok {
return nil, ErrClosed
}
b := &barrier{signal: newSignal()}
b.extend(sent, ttl)
renewCtx, stop := context.WithCancel(context.WithoutCancel(ctx))
renewDone := make(chan struct{})
go func() {
defer close(renewDone)
ticker := time.NewTicker(renewInterval(ttl))
defer ticker.Stop()
for {
select {
case <-renewCtx.Done():
return
case <-b.Lost():
return
case <-ticker.C:
sent := time.Now()
callCtx, cancel := context.WithDeadline(renewCtx, b.currentDeadline())
renewed, err := redislock.Renew(callCtx, r.client, key, token, ttl)
cancel()
switch {
case err == nil && renewed:
b.extend(sent, ttl)
case err == nil:
b.markLost()
return
}
}
}
}()
// Wait for the renewal goroutine to leave before touching the key, so a
// PEXPIRE cannot land after PERSIST and put the TTL back.
finishKey := func(persist bool) {
stop()
<-renewDone
relCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if persist {
_ = r.client.Persist(relCtx, key).Err()
return
}
_, _ = redislock.Release(relCtx, r.client, key, token)
}
b.release = func() { finishKey(false) }
b.seal = func() { finishKey(true) }
return b, nil
}
// renewInterval is how often a holder reconfirms. It stays inside the
// deadline (ttl - ttl/6) so one hung renewal still loses the lease on time.
func renewInterval(ttl time.Duration) time.Duration {
every := ttl / 3
if every <= 0 {
return time.Millisecond
}
return every
}
var _ Registry = (*RedisRegistry)(nil)
@@ -0,0 +1,139 @@
package admission_test
import (
"os"
"strings"
"testing"
"time"
"github.com/google/uuid"
"github.com/redis/go-redis/v9"
"github.com/stretchr/testify/require"
"academy/internal/sandbox/admission"
)
// integrationEnv returns an integration dependency's address. Missing, the
// test is skipped — unless ACADEMY_REQUIRE_INTEGRATION=1, which turns the
// skip into a failure so an enablement run cannot pass by skipping.
func integrationEnv(t *testing.T, name string) string {
t.Helper()
v := strings.TrimSpace(os.Getenv(name))
if v != "" {
return v
}
if os.Getenv("ACADEMY_REQUIRE_INTEGRATION") == "1" {
t.Fatalf("%s is required when ACADEMY_REQUIRE_INTEGRATION=1", name)
}
t.Skipf("set %s to run against a real dependency", name)
return ""
}
// realRedisPair dials ACADEMY_TEST_REDIS_ADDR twice. prefix isolates this run.
func realRedisPair(t *testing.T) (c1, c2 *admission.RedisRegistry, raw *redis.Client, prefix string) {
t.Helper()
addr := integrationEnv(t, "ACADEMY_TEST_REDIS_ADDR")
prefix = "it-" + uuid.NewString() + ":"
open := func() *redis.Client {
rc := redis.NewClient(&redis.Options{Addr: addr})
t.Cleanup(func() { _ = rc.Close() })
return rc
}
left, right := open(), open()
raw = open()
return admission.NewRedis(left, prefix), admission.NewRedis(right, prefix), raw, prefix
}
// redisKey is RedisRegistry's key layout. The method is unexported; the
// integration test builds the same string so it can inject faults.
func redisKey(prefix string, scope admission.Scope, suffix string) string {
return prefix + "{" + scope.Tag + "}:" + scope.Name + ":" + suffix
}
func TestRedisRealTwoClientsShareAdmission(t *testing.T) {
c1, c2, _, _ := realRedisPair(t)
ctx := t.Context()
scope := admission.MachineScope("d-" + uuid.NewString())
member := "s:a:pty:1"
lease, err := c1.Hold(ctx, scope, member, time.Minute)
require.NoError(t, err)
defer lease.Release()
barrier, err := c2.Close(ctx, scope, time.Minute)
require.NoError(t, err)
defer barrier.Release()
n, err := c2.ActiveExcept(ctx, scope)
require.NoError(t, err)
require.Equal(t, 1, n)
lease.Release()
n, err = c2.ActiveExcept(ctx, scope)
require.NoError(t, err)
require.Zero(t, n)
_, err = c1.Hold(ctx, scope, "s:a:pty:2", time.Minute)
require.ErrorIs(t, err, admission.ErrClosed)
barrier.Release()
again, err := c1.Hold(ctx, scope, "s:a:pty:3", time.Minute)
require.NoError(t, err)
again.Release()
}
func TestRedisRealBarrierIsRenewedAndLossIsReported(t *testing.T) {
c1, c2, raw, prefix := realRedisPair(t)
ctx := t.Context()
scope := admission.MachineScope("d-" + uuid.NewString())
ttl := 2 * time.Second
barrier, err := c2.Close(ctx, scope, ttl)
require.NoError(t, err)
defer barrier.Release()
time.Sleep(3 * time.Second)
require.NoError(t, barrier.Check(), "a held barrier is renewed past its initial TTL")
closedKey := redisKey(prefix, scope, "closed")
require.NoError(t, raw.Del(ctx, closedKey).Err())
select {
case <-barrier.Lost():
require.ErrorIs(t, barrier.Check(), admission.ErrLeaseLost)
case <-time.After(ttl):
t.Fatal("the barrier kept reporting ownership after its key was deleted")
}
again, err := c1.Close(ctx, scope, time.Minute)
require.NoError(t, err, "a lost barrier does not keep the scope closed")
again.Release()
}
func TestRedisRealLostMemberIsNotResurrected(t *testing.T) {
c1, _, raw, prefix := realRedisPair(t)
ctx := t.Context()
scope := admission.MachineScope("d-" + uuid.NewString())
member := admission.SessionMember("s", "shell", "1")
ttl := 2 * time.Second
lease, err := c1.Hold(ctx, scope, member, ttl)
require.NoError(t, err)
defer lease.Release()
opsKey := redisKey(prefix, scope, "ops")
require.NoError(t, raw.ZRem(ctx, opsKey, member).Err())
// Renewal ticks every ttl/3. Wait past one tick, and past the ttl/6
// margin, so a loop that put the member back would be visible.
select {
case <-lease.Lost():
case <-time.After(ttl):
t.Fatal("a removed member was not reported lost")
}
time.Sleep(ttl/3 + 100*time.Millisecond)
_, err = raw.ZScore(ctx, opsKey, member).Result()
require.ErrorIs(t, err, redis.Nil, "renewal must not resurrect a removed member")
require.ErrorIs(t, lease.Check(), admission.ErrLeaseLost)
}
@@ -0,0 +1,168 @@
package allocation
import (
"strings"
"testing"
"github.com/stretchr/testify/require"
)
const sid = "0f8fad5b-d9cb-469f-a165-70867728950e"
func TestParseMode(t *testing.T) {
for in, want := range map[string]Mode{"": ModeSession, "session": ModeSession, " user ": ModeUser} {
got, err := ParseMode(in)
require.NoError(t, err)
require.Equal(t, want, got)
}
_, err := ParseMode("machine")
require.Error(t, err)
}
func TestDecideMatrix(t *testing.T) {
web := Owner{TenantID: 7, ID: "u-1", Kind: KindWebUser, Source: SourceWeb}
ext := Owner{TenantID: 7, ID: "api_external_user:7:alice", Kind: KindAPIExternalUser, Source: SourceAPISignedToken}
base := DecideInput{ConfigMode: ModeUser, Purpose: PurposeChat, SessionID: sid, UserModeAvailable: true}
cases := []struct {
name string
mutate func(*DecideInput)
mode Mode
reason FallbackReason
}{
{"web user shares", func(in *DecideInput) { in.Owner = web }, ModeUser, ReasonNone},
{"signed external user shares", func(in *DecideInput) { in.Owner = ext }, ModeUser, ReasonNone},
{"direct external user shares", func(in *DecideInput) {
in.Owner = ext
in.Owner.Source = SourceAPIDirectHeader
}, ModeUser, ReasonNone},
{"session config never shares", func(in *DecideInput) {
in.Owner = web
in.ConfigMode = ModeSession
}, ModeSession, ReasonNone},
{"maintenance first", func(in *DecideInput) {
in.Owner = web
in.Purpose = PurposeMaintenance
}, ModeSession, ReasonMaintenanceDedicated},
{"gate off", func(in *DecideInput) {
in.Owner = web
in.UserModeAvailable = false
}, ModeSession, ReasonUserModeUnavailable},
{"tenant api key", func(in *DecideInput) {
in.Owner = Owner{TenantID: 7, ID: "api_tenant_key:7:3", Kind: KindAPITenantKey, Source: SourceAPITenantKey}
}, ModeSession, ReasonSharedAPIKey},
{"platform api key", func(in *DecideInput) {
in.Owner = Owner{TenantID: 7, ID: "api_platform:3", Kind: KindAPIPlatformKey, Source: SourceAPIPlatformKey}
}, ModeSession, ReasonSharedAPIKey},
{"mcp endpoint", func(in *DecideInput) {
in.Owner = Owner{TenantID: 7, ID: "mcp_endpoint:7:e", Kind: KindMCPEndpoint, Source: SourceMCPEndpoint}
}, ModeSession, ReasonSharedMCPEndpoint},
{"embed", func(in *DecideInput) {
in.Owner = Owner{TenantID: 7, ID: "embed_session:7:c:s", Kind: KindEmbed}
}, ModeSession, ReasonChannelIdentity},
{"im", func(in *DecideInput) {
in.Owner = Owner{TenantID: 7, ID: "x", Kind: KindIM}
}, ModeSession, ReasonChannelIdentity},
{"empty owner", func(in *DecideInput) {
in.Owner = Owner{TenantID: 7}
}, ModeSession, ReasonOwnerIdentityUnverified},
{"web without web source", func(in *DecideInput) {
in.Owner = web
in.Owner.Source = SourceInternal
}, ModeSession, ReasonOwnerIdentityUnverified},
{"external with unknown source", func(in *DecideInput) {
in.Owner = ext
in.Owner.Source = SourceUnknown
}, ModeSession, ReasonOwnerIdentityUnverified},
{"unknown kind", func(in *DecideInput) {
in.Owner = Owner{TenantID: 7, ID: "u", Source: SourceWeb}
}, ModeSession, ReasonOwnerIdentityUnverified},
{"owner with braces", func(in *DecideInput) {
in.Owner = web
in.Owner.ID = "u{1}"
}, ModeSession, ReasonOwnerIdentityInvalid},
{"owner too long", func(in *DecideInput) {
in.Owner = web
in.Owner.ID = strings.Repeat("a", 513)
}, ModeSession, ReasonOwnerIdentityInvalid},
{"session id not uuid", func(in *DecideInput) {
in.Owner = web
in.SessionID = "abc"
}, ModeSession, ReasonSessionIDNotUUID},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
in := base
tc.mutate(&in)
got := Decide(in)
require.Equal(t, tc.mode, got.Mode)
require.Equal(t, tc.reason, got.Reason)
})
}
}
func TestEligibleForUser(t *testing.T) {
require.True(t, EligibleForUser(KindWebUser, SourceWeb))
require.True(t, EligibleForUser(KindAPIExternalUser, SourceAPISignedToken))
require.True(t, EligibleForUser(KindAPIExternalUser, SourceAPIDirectHeader))
require.False(t, EligibleForUser(KindWebUser, SourceInternal))
require.False(t, EligibleForUser(KindAPITenantKey, SourceAPITenantKey))
require.False(t, EligibleForUser(KindUnknown, SourceWeb))
}
func TestUserMachineDigestIsStableAndUnambiguous(t *testing.T) {
m := UserMachine{OwnerTenantID: 7, OwnerID: "u-1", ConfigTenantID: 9, ConfigID: "cfg"}
require.NoError(t, m.Validate())
d := m.Digest("academy")
require.Len(t, d, 64)
require.Equal(t, d, m.Digest("academy"))
require.NotEqual(t, d, m.Digest("other"))
// Length-prefixing keeps field boundaries: these two must not collide.
a := UserMachine{OwnerTenantID: 7, OwnerID: "ab", ConfigTenantID: 9, ConfigID: "c"}
b := UserMachine{OwnerTenantID: 7, OwnerID: "a", ConfigTenantID: 9, ConfigID: "bc"}
require.NotEqual(t, a.Digest("n"), b.Digest("n"))
require.Error(t, UserMachine{OwnerID: "u", ConfigTenantID: 9, ConfigID: "c"}.Validate())
require.Error(t, UserMachine{OwnerTenantID: 7, ConfigTenantID: 9, ConfigID: "c"}.Validate())
require.Error(t, UserMachine{OwnerTenantID: 7, OwnerID: "u", ConfigID: "c"}.Validate())
require.Error(t, UserMachine{OwnerTenantID: 7, OwnerID: "u", ConfigTenantID: 9}.Validate())
}
func TestAssignmentLayout(t *testing.T) {
s := Assignment{SessionID: sid, ConfigTenantID: 9, ConfigID: "cfg"}
require.Equal(t, ModeSession, s.Mode())
l, err := s.Layout()
require.NoError(t, err)
require.Equal(t, "/workspace", l.Root)
_, ok := s.UserMachine()
require.False(t, ok)
want := UserMachine{OwnerTenantID: 7, OwnerID: "u-1", ConfigTenantID: 9, ConfigID: "cfg"}
u := Assignment{SessionID: sid, ConfigTenantID: 9, ConfigID: "cfg", Machine: want}
require.Equal(t, ModeUser, u.Mode())
l, err = u.Layout()
require.NoError(t, err)
require.Equal(t, "/workspace/sessions/c812e1edb644", l.Root)
m, ok := u.UserMachine()
require.True(t, ok)
require.Equal(t, want, m)
}
func TestRetention(t *testing.T) {
require.Equal(t, 7, EffectiveRetentionDays(0))
require.Equal(t, 30, EffectiveRetentionDays(30))
require.NoError(t, ValidateRetentionDays(0))
require.NoError(t, ValidateRetentionDays(90))
require.Error(t, ValidateRetentionDays(-1))
require.Error(t, ValidateRetentionDays(91))
}
func TestGate(t *testing.T) {
t.Cleanup(func() { SetUserModeAvailable(false) })
require.False(t, UserModeAvailable())
SetUserModeAvailable(true)
require.True(t, UserModeAvailable())
t.Setenv(UserModeEnvVar, "enabled")
require.True(t, UserModeRequestedByEnv())
t.Setenv(UserModeEnvVar, "nope")
require.False(t, UserModeRequestedByEnv())
}
+49
View File
@@ -0,0 +1,49 @@
package allocation
import (
"time"
"academy/internal/sandbox/workspace"
)
// Assignment is the persisted placement of one session. Only the config
// address, the shared machine (if any) and the release time are stored; the
// mode and the workspace layout follow from whether there is a machine, and
// the session keeps both for life whatever the config switch says later.
type Assignment struct {
SessionID string
ConfigTenantID uint64
ConfigID string
// Machine is the shared machine of a user-mode session; zero for a
// session with a machine of its own.
Machine UserMachine
ReleasedAt *time.Time
}
// Released reports a session whose workspace has been given back.
func (a Assignment) Released() bool { return a.ReleasedAt != nil }
// Mode is ModeUser for a session on a shared machine, ModeSession otherwise.
func (a Assignment) Mode() Mode {
if a.Machine != (UserMachine{}) {
return ModeUser
}
return ModeSession
}
// IsUser reports a session on a shared machine.
func (a Assignment) IsUser() bool { return a.Mode() == ModeUser }
// UserMachine returns the shared machine a user-mode session lives on.
func (a Assignment) UserMachine() (UserMachine, bool) {
return a.Machine, a.IsUser()
}
// Layout is the workspace the session was assigned, independent of the
// config's current switch.
func (a Assignment) Layout() (workspace.Layout, error) {
if a.IsUser() {
return workspace.UserSession(a.SessionID)
}
return workspace.Remote(), nil
}
+30
View File
@@ -0,0 +1,30 @@
package allocation
import (
"os"
"strings"
"sync/atomic"
)
// UserModeEnvVar opts a deployment into user-mode allocation. It must be set
// on every replica before any config is switched to "user".
const UserModeEnvVar = "ACADEMY_SANDBOX_USER_ALLOCATION"
var userModeAvailable atomic.Bool
// UserModeRequestedByEnv reports whether the operator asked for user mode.
func UserModeRequestedByEnv() bool {
switch strings.ToLower(strings.TrimSpace(os.Getenv(UserModeEnvVar))) {
case "1", "true", "on", "enabled":
return true
default:
return false
}
}
// SetUserModeAvailable is called once by the container after it knows whether
// the deployment can coordinate shared machines (env opt-in and Redis).
func SetUserModeAvailable(available bool) { userModeAvailable.Store(available) }
// UserModeAvailable reports the deployment gate.
func UserModeAvailable() bool { return userModeAvailable.Load() }
+58
View File
@@ -0,0 +1,58 @@
package allocation
import (
"crypto/sha256"
"encoding/binary"
"encoding/hex"
"errors"
"strconv"
"strings"
)
// UserMachine is the logical identity of one shared machine: one owner, one
// sandbox config. It is comparable so it can key maps. ConfigID must already
// be normalized (sandbox.NormalizeConfigID) and ConfigTenantID resolved.
type UserMachine struct {
OwnerTenantID uint64
OwnerID string
ConfigTenantID uint64
ConfigID string
}
// Validate rejects identities that cannot address a machine.
func (m UserMachine) Validate() error {
if m.OwnerTenantID == 0 {
return errors.New("allocation: user machine requires an owner tenant")
}
if err := ValidateOwnerID(m.OwnerID); err != nil {
return err
}
if m.ConfigTenantID == 0 {
return errors.New("allocation: user machine requires a resolved config tenant")
}
if strings.TrimSpace(m.ConfigID) == "" {
return errors.New("allocation: user machine requires a config id")
}
return nil
}
// Digest is the hex SHA-256 of a length-prefixed canonical encoding, so no
// two identities share a digest by field-boundary ambiguity. The namespace is
// part of it: two deployments sharing one Redis never address each other's
// machines. It is the Redis hash tag, the DB key and the provider metadata.
func (m UserMachine) Digest(namespace string) string {
h := sha256.New()
write := func(s string) {
var n [8]byte
binary.BigEndian.PutUint64(n[:], uint64(len(s)))
h.Write(n[:])
h.Write([]byte(s))
}
write("academy-user-sandbox/v1")
write(namespace)
write(strconv.FormatUint(m.OwnerTenantID, 10))
write(m.OwnerID)
write(strconv.FormatUint(m.ConfigTenantID, 10))
write(m.ConfigID)
return hex.EncodeToString(h.Sum(nil))
}
+59
View File
@@ -0,0 +1,59 @@
// Package allocation is the domain model for placing a session on a remote
// sandbox: which mode it uses, whether its owner may share a machine, and the
// identity of a shared machine. It performs no I/O.
package allocation
import (
"fmt"
"strings"
)
// Mode is how a session is placed on remote machines.
type Mode string
const (
// ModeSession gives the session a machine of its own (historical behaviour).
ModeSession Mode = "session"
// ModeUser places the session in a directory on its owner's shared machine.
ModeUser Mode = "user"
)
// ParseMode accepts the stored config value. Empty means session.
func ParseMode(raw string) (Mode, error) {
switch strings.TrimSpace(raw) {
case "", string(ModeSession):
return ModeSession, nil
case string(ModeUser):
return ModeUser, nil
default:
return "", fmt.Errorf("allocation: unknown mode %q", raw)
}
}
// Purpose is why a session uses a sandbox.
type Purpose string
// Placement purposes. PurposeChat is an ordinary session.
// PurposeMaintenance is a skill-install session and stays on its own machine.
const (
PurposeChat Purpose = "chat"
PurposeMaintenance Purpose = "maintenance"
)
// FallbackReason explains why a session did not get the config's mode. The
// values are stable, non-sensitive tokens safe to show an admin.
type FallbackReason string
// Reasons a placement stayed on a per-session machine.
const (
ReasonNone FallbackReason = ""
ReasonMaintenanceDedicated FallbackReason = "MAINTENANCE_DEDICATED"
ReasonUserModeUnavailable FallbackReason = "USER_MODE_UNAVAILABLE"
ReasonOwnerIdentityInvalid FallbackReason = "OWNER_IDENTITY_INVALID"
ReasonSharedAPIKey FallbackReason = "SHARED_API_KEY"
ReasonSharedMCPEndpoint FallbackReason = "SHARED_MCP_ENDPOINT"
ReasonChannelIdentity FallbackReason = "CHANNEL_IDENTITY_NOT_SUPPORTED"
ReasonOwnerIdentityUnverified FallbackReason = "OWNER_IDENTITY_UNVERIFIED"
ReasonSessionIDNotUUID FallbackReason = "SESSION_ID_NOT_UUID"
ReasonLegacySessionSandbox FallbackReason = "LEGACY_SESSION_SANDBOX"
)
+142
View File
@@ -0,0 +1,142 @@
package allocation
import (
"errors"
"strings"
"unicode"
"academy/internal/sandbox/workspace"
)
// OwnerKind classifies who sessions.user_id names.
type OwnerKind string
// Kinds derived from owner_auth_source and the shape of user_id.
const (
KindUnknown OwnerKind = ""
KindWebUser OwnerKind = "web_user"
KindAPIExternalUser OwnerKind = "api_external_user"
KindAPITenantKey OwnerKind = "api_tenant_key"
KindAPIPlatformKey OwnerKind = "api_platform_key"
KindMCPEndpoint OwnerKind = "mcp_endpoint"
KindEmbed OwnerKind = "embed"
KindIM OwnerKind = "im"
)
// AuthSource is how the server authenticated the owner when the session was
// created or its owner was first bound. It is recorded server-side only.
type AuthSource string
// Sources stamped by the server. SourceUnknown is an empty or legacy row.
const (
SourceUnknown AuthSource = "unknown"
SourceWeb AuthSource = "web"
SourceAPIDirectHeader AuthSource = "api_direct_header"
SourceAPISignedToken AuthSource = "api_signed_token"
SourceAPITenantKey AuthSource = "api_tenant_key"
SourceAPIPlatformKey AuthSource = "api_platform_key"
SourceMCPEndpoint AuthSource = "mcp_endpoint"
SourceEmbed AuthSource = "embed"
SourceIM AuthSource = "im"
SourceInternal AuthSource = "internal"
)
// MaxOwnerIDLength matches sessions.user_id.
const MaxOwnerIDLength = 512
// Owner is the persisted owner of a session as the allocator sees it.
type Owner struct {
TenantID uint64
ID string
Kind OwnerKind
Source AuthSource
}
// ValidateOwnerID rejects ids that cannot be part of a machine identity.
func ValidateOwnerID(id string) error {
if strings.TrimSpace(id) == "" {
return errors.New("allocation: owner id is empty")
}
if len(id) > MaxOwnerIDLength {
return errors.New("allocation: owner id is too long")
}
if strings.ContainsAny(id, "{}") {
return errors.New("allocation: owner id must not contain braces")
}
for _, r := range id {
if unicode.IsControl(r) {
return errors.New("allocation: owner id must not contain control characters")
}
}
return nil
}
// DecideInput is everything Decide needs; callers load it, Decide is pure.
type DecideInput struct {
ConfigMode Mode
Purpose Purpose
Owner Owner
SessionID string
UserModeAvailable bool
}
// Decision is the mode a session gets and why it differs from the config.
type Decision struct {
Mode Mode
Reason FallbackReason
}
// Decide applies the user-mode admission whitelist. Only a server-verified web
// account or API external user may share a machine; every other owner keeps a
// machine per session. Checks run in a fixed order so the recorded reason is
// deterministic: maintenance, deployment gate, invalid owner, shared entry or
// channel, unverified identity, session id shape.
func Decide(in DecideInput) Decision {
session := func(reason FallbackReason) Decision { return Decision{Mode: ModeSession, Reason: reason} }
if in.Purpose == PurposeMaintenance {
return session(ReasonMaintenanceDedicated)
}
if in.ConfigMode != ModeUser {
return session(ReasonNone)
}
if !in.UserModeAvailable {
return session(ReasonUserModeUnavailable)
}
if strings.TrimSpace(in.Owner.ID) == "" {
return session(ReasonOwnerIdentityUnverified)
}
if ValidateOwnerID(in.Owner.ID) != nil {
return session(ReasonOwnerIdentityInvalid)
}
if EligibleForUser(in.Owner.Kind, in.Owner.Source) {
if !workspace.IsCanonicalUUID(in.SessionID) {
return session(ReasonSessionIDNotUUID)
}
return Decision{Mode: ModeUser}
}
switch in.Owner.Kind {
case KindAPITenantKey, KindAPIPlatformKey:
return session(ReasonSharedAPIKey)
case KindMCPEndpoint:
return session(ReasonSharedMCPEndpoint)
case KindEmbed, KindIM:
return session(ReasonChannelIdentity)
default:
return session(ReasonOwnerIdentityUnverified)
}
}
// EligibleForUser is the whitelist itself: a server-verified web account, or
// an API external user whose subject came from the direct header or a signed
// token. Decide applies it at first use; the manager re-applies it to stored
// assignments so a row whose identity is no longer acceptable stops running.
func EligibleForUser(kind OwnerKind, source AuthSource) bool {
switch kind {
case KindWebUser:
return source == SourceWeb
case KindAPIExternalUser:
return source == SourceAPIDirectHeader || source == SourceAPISignedToken
default:
return false
}
}
+28
View File
@@ -0,0 +1,28 @@
package allocation
import "fmt"
const (
// DefaultEmptyRetentionDays is how long a user machine with no live
// session is kept when the config leaves the value unset.
DefaultEmptyRetentionDays = 7
// MaxEmptyRetentionDays bounds the setting; there is no "keep forever".
MaxEmptyRetentionDays = 90
)
// EffectiveRetentionDays maps the stored value (0 = unset) onto days.
func EffectiveRetentionDays(stored int) int {
if stored <= 0 {
return DefaultEmptyRetentionDays
}
return stored
}
// ValidateRetentionDays accepts 0 (use the default) through 90.
func ValidateRetentionDays(stored int) error {
if stored < 0 || stored > MaxEmptyRetentionDays {
return fmt.Errorf("user_sandbox_empty_retention_days must be between 1 and %d, or 0 for the default of %d",
MaxEmptyRetentionDays, DefaultEmptyRetentionDays)
}
return nil
}
+220
View File
@@ -0,0 +1,220 @@
// Package sandbox: session-scoped capability interfaces.
//
// The Sandbox / Manager pair intentionally hides provider identity (Cube,
// E2B, Docker) from the application layer. Higher layers should never
// branch on Manager.GetType() to decide whether a feature is supported —
// that couples them to a specific backend.
//
// Instead, session-scoped features (shell execution, per-session file
// inspection, attachment staging) are advertised via the capability
// interfaces below. A manager may satisfy the underlying methods yet still
// return nil from the accessors on SessionCapabilityProvider when the
// current runtime configuration cannot honour that capability.
package sandbox
import (
"context"
"errors"
"time"
"github.com/gorilla/websocket"
)
var (
// ErrSharedSandbox is returned when the session lives on its owner's shared
// machine, so destroying its sandbox would destroy every sibling session's
// workspace. Delete the session workspace instead.
ErrSharedSandbox = errors.New("sandbox: session shares its owner's machine")
// ErrSessionWorkspaceBusy is returned when the session's workspace is held
// exclusively, or has operations that an exclusive request must not cut off.
ErrSessionWorkspaceBusy = errors.New("sandbox: session workspace is busy")
// ErrUserAllocationRejected is returned when a stored user-mode assignment's
// owner identity is not, or is no longer, eligible to share a machine.
ErrUserAllocationRejected = errors.New("sandbox: user-mode allocation rejected for this owner")
)
// SessionShellExecutor executes ad-hoc shell commands inside a session-
// scoped remote sandbox. SessionBoundManager surfaces it while Cube, E2B,
// or Docker is active.
type SessionShellExecutor interface {
ExecShellCommand(
ctx context.Context,
sessionID string,
command string,
workDir string,
timeout time.Duration,
env map[string]string,
) (*ExecuteResult, error)
}
// SessionFileStore is the effective per-session filesystem view a manager
// offers callers that need to inspect, stage, or clean up files inside the
// session's remote sandbox. It is intentionally provider-neutral: entries
// use RemoteDirEntry / RemoteStatEntry, so E2B and Cube can implement it
// without touching the caller.
type SessionFileStore interface {
// EnsureSessionDir creates dir in the session's live sandbox. Silent
// no-op when no sandbox is bound yet; the next Execute call will
// materialise the directory during script upload.
EnsureSessionDir(ctx context.Context, sessionID, dir string) error
// ListSessionFiles walks dir recursively and returns file entries.
// Returns nil (no error) when the session has no live sandbox so
// callers can treat "no sandbox" and "empty output" uniformly.
ListSessionFiles(ctx context.Context, sessionID, dir string) ([]RemoteDirEntry, error)
// StatSessionFile returns metadata for a single file. Errors when the
// session has no bound sandbox — callers of this method already hold a
// path from a prior ListSessionFiles call.
StatSessionFile(ctx context.Context, sessionID, path string) (*RemoteStatEntry, error)
// ReadSessionFile downloads a file's contents. Same "no sandbox
// bound" contract as StatSessionFile.
ReadSessionFile(ctx context.Context, sessionID, path string) ([]byte, error)
// WriteSessionInputFile writes a durable attachment path into the
// session's remote sandbox, provisioning the sandbox on first call.
WriteSessionInputFile(ctx context.Context, sessionID, filePath string, content []byte) error
// WriteSessionWorkspaceFile writes a model-authored file inside the
// current session sandbox. Relative paths resolve from /workspace;
// /workspace/input stays read-only (attachments).
WriteSessionWorkspaceFile(ctx context.Context, sessionID, filePath string, content []byte) error
// WriteSessionWorkspaceFiles writes many workspace files after preparing
// the session layout once. Host-skill staging must use this instead of
// looping WriteSessionWorkspaceFile.
WriteSessionWorkspaceFiles(ctx context.Context, sessionID string, files []SessionWorkspaceFile) error
// RemoveSessionInputPath deletes a staged attachment. No-op when the
// session has no live sandbox.
RemoveSessionInputPath(ctx context.Context, sessionID, targetPath string) error
}
// SessionWorkspaceFile is one path/content pair for WriteSessionWorkspaceFiles.
type SessionWorkspaceFile struct {
Path string
Content []byte
}
// SessionCapabilityProvider is implemented by managers that MAY offer
// session-scoped capabilities. Accessors return nil when the current
// runtime configuration cannot support that capability. Application code
// should gate feature registration on non-nil accessor returns.
type SessionCapabilityProvider interface {
SessionShellExecutor() SessionShellExecutor
SessionFileStore() SessionFileStore
}
// SessionWorkspaceLayoutProvider is implemented by managers that can describe
// their session workspace. Tools resolve it once per Execute from the
// session sandbox, not from a tool-instance field.
type SessionWorkspaceLayoutProvider interface {
SessionWorkspaceLayout(ctx context.Context, sessionID string) (WorkspaceLayout, error)
}
// SessionInstallShellExecutor runs install/maintenance shell commands with
// their own bootstrap and working-directory scope. Ordinary shell execution
// stays inside its session sandbox: anywhere in a remote container, and the
// layout's writable roots on a host workspace.
type SessionInstallShellExecutor interface {
ExecShellCommandWithOptions(
ctx context.Context,
sessionID string,
command string,
opts ShellExecOptions,
) (*ExecuteResult, error)
}
// SessionFileReader reads one file out of a session's sandbox. It is the
// single-method slice of SessionFileStore that callers which only ever read
// need, so a manager offering just this much is enough for them.
type SessionFileReader interface {
ReadSessionFile(ctx context.Context, sessionID, path string) ([]byte, error)
}
// SessionDestroyer releases the remote sandbox bound to a session, leaving the
// session record itself alone. Like RemoteSnapshotManager it is an optional
// capability: stateless backends have nothing to release.
type SessionDestroyer interface {
DestroySession(ctx context.Context, sessionID string) error
}
// SessionInstallCapabilityProvider is implemented by managers that can run
// install-mode shell commands. Like the other accessors it returns nil when
// the current runtime cannot honour the capability.
type SessionInstallCapabilityProvider interface {
SessionInstallShellExecutor() SessionInstallShellExecutor
}
// SessionTerminalManager opens interactive PTYs on the sandbox bound to a
// session. Like the file store it is provider-neutral: the WebSocket
// handler bridges browser terminal frames to it without knowing whether
// E2B or Cube serves the session.
type SessionTerminalManager interface {
// OpenSessionTerminal connects to the session's currently bound sandbox
// and opens a PTY. It is lookup-only: when no live sandbox is bound it
// returns ErrNoLiveSessionSandbox instead of provisioning one, because
// the terminal entry point lacks the agent's config-pin context and
// must not create microVMs as a side effect. A bound sandbox that is
// not confirmed running returns ErrSandboxPaused unless opts.AllowResume
// is set, so a panel open cannot silently resume (and re-bill) a paused
// instance. A backend that cannot stream PTYs returns
// ErrTerminalUnsupported, not "no sandbox".
OpenSessionTerminal(ctx context.Context, sessionID string, opts RemoteTerminalOptions) (RemoteTerminalSession, error)
}
// SessionTerminalProvider is implemented by managers that MAY offer
// interactive terminals. The accessor returns nil when the current runtime
// cannot honour the capability.
type SessionTerminalProvider interface {
SessionTerminalManager() SessionTerminalManager
}
// SessionDesktopConn is one dialled desktop leg.
//
// SandboxID is the sandbox this connection actually reached. It is returned
// rather than looked up afterwards because a skill install landing between
// the dial and the lookup would report the new sandbox for a connection held
// on the old one, and the handler's rebuild check would silently miss.
type SessionDesktopConn struct {
Conn *websocket.Conn
SandboxID string
// StartTTLRefresh extends the provider idle timeout for as long as ctx
// is live. The WebSocket handler must pass the relay ctx (WithoutCancel),
// not the HTTP request ctx used to dial. Nil when the backend has no
// timeout to refresh (Docker).
StartTTLRefresh func(ctx context.Context)
}
// SessionDesktopManager relays a WebSocket to the graphical desktop of the
// sandbox bound to a session. Like the terminal it is provider-neutral: the
// WebSocket handler bridges browser RFB frames to it without knowing whether
// E2B or Cube serves the session.
type SessionDesktopManager interface {
// OpenSessionDesktop dials the desktop port of the session's currently
// bound sandbox. It is lookup-only by design: the caller (the desktop
// service) has already provisioned and started the desktop through the
// normal execution path, so a missing binding here means the sandbox
// disappeared between the two steps, not "please create one".
// ErrNoLiveSessionSandbox says exactly that; a backend that cannot relay
// desktops returns ErrDesktopUnsupported.
OpenSessionDesktop(ctx context.Context, sessionID string, opts RemoteDesktopOptions) (*SessionDesktopConn, error)
}
// SessionDesktopProvider is implemented by managers that MAY offer a
// graphical desktop. The accessor returns nil when the current runtime cannot
// honour the capability.
type SessionDesktopProvider interface {
SessionDesktopManager() SessionDesktopManager
}
// SessionTurnHolder marks one chat turn on a session's sandbox.
type SessionTurnHolder interface {
// BeginSessionTurn opens one turn hold. Run the turn with the returned
// context: on a shared machine it carries this hold's admission member,
// so the turn's own tool calls do not wait for it, and it ends if the
// registration is lost. end closes exactly this hold; call it once.
BeginSessionTurn(ctx context.Context, sessionID string) (turnCtx context.Context, end func(), err error)
}
@@ -0,0 +1,61 @@
package sandbox
import (
"context"
"strings"
"testing"
"github.com/stretchr/testify/require"
)
// The connectivity probe dials endpoints an admin typed into an unsaved form,
// so it is the one client whose target is fully attacker-influenced within a
// workspace. Save-time validation cannot cover it: a hostname can resolve to a
// public address while the form is validated and to the cloud metadata service
// by the time the probe connects. Both providers must therefore refuse
// link-local at dial time, and they must do so even under the private-endpoint
// opt-in that self-hosted Cube deployments need.
func TestNewRemoteClientForCheckRefusesLinkLocalAtDial(t *testing.T) {
const metadata = "http://169.254.169.254"
for _, tc := range []struct {
name string
cfg *Config
}{
{
name: "cube",
cfg: &Config{
AllowPrivateEndpoints: true,
Type: SandboxTypeCube,
CubeAPIURL: metadata,
CubeProxyURL: metadata,
CubeSandboxDomain: "cube.app",
CubeTemplate: "tpl-test",
},
},
{
name: "e2b",
cfg: &Config{
AllowPrivateEndpoints: true,
Type: SandboxTypeE2B,
E2BAPIKey: "key-test",
E2BAPIURL: metadata,
E2BTemplate: "base",
},
},
} {
t.Run(tc.name, func(t *testing.T) {
client, err := NewRemoteClientForCheck(tc.cfg)
require.NoError(t, err)
err = client.Health(context.Background())
require.Error(t, err, "probing the metadata service must fail")
// The guard rejects before any packet leaves, so the refusal - not
// a connection timeout - is what has to surface.
require.True(t,
strings.Contains(err.Error(), ErrUnsafeOutboundURL.Error()) ||
strings.Contains(err.Error(), "never routable"),
"expected the outbound guard to refuse the dial, got: %v", err)
})
}
}
+19
View File
@@ -0,0 +1,19 @@
package sandbox
import "context"
type commandOutputKey struct{}
// WithCommandOutput observes the command executed with this context. It does
// not grant installer privileges or change the final command result.
func WithCommandOutput(ctx context.Context, callback func(string, []byte)) context.Context {
return context.WithValue(ctx, commandOutputKey{}, callback)
}
func commandOutputCallback(ctx context.Context, explicit func(string, []byte)) func(string, []byte) {
if explicit != nil {
return explicit
}
callback, _ := ctx.Value(commandOutputKey{}).(func(string, []byte))
return callback
}
+85
View File
@@ -0,0 +1,85 @@
// Package sandbox: what makes an existing sandbox operable.
//
// Two groups of configuration fields decide whether the sandboxes a config has
// already created can still be acted on. This file names them in one place
// because the answer depends on which SDK carries which value:
//
// - Control plane (API URL, API key): every lifecycle call - list, delete,
// pause, resume, refresh timeout - is issued against it. Lose it and the
// sandboxes can no longer be reclaimed at all.
// - Data plane (sandbox domain, and for Cube the proxy endpoint): envd traffic
// is routed through it. Lose it and the sandboxes are still deletable but no
// longer usable, so every live session on the config fails at once.
//
// The split is a property of the clients in use, not a universal truth:
// github.com/matiasinsaurralde/go-e2b resolves the API base URL and the sandbox
// domain independently, whereas E2B's own JS/Python SDKs derive the API base from
// the domain (https://api.${domain}). Swapping that dependency would move the
// domain into the control-plane group.
package sandbox
import (
"academy/internal/types"
)
// SandboxIdentity is the comparable projection of a config: two configs with
// equal identities can operate each other's sandboxes.
type SandboxIdentity struct {
Provider string
AllowPrivateEndpoints bool
// Control plane - whether an existing sandbox can still be reclaimed.
APIURL string
APIKey string
// Data plane - whether an existing sandbox can still be used.
SandboxDomain string
ProxyURL string
}
// IdentityOf projects a stored config onto its identity. Only the active
// provider's fields are read: a sub-struct left behind by an earlier provider
// switch says nothing about where today's sandboxes live.
//
// Because named configs inherit nothing, the stored row is the whole picture and
// no deployment baseline is consulted. Unknown type strings are compared verbatim
// rather than rejected: a typo yields an identity that matches nothing, which
// errs toward refusing the edit, and ParseSandboxType reports it on save.
//
// This runs no SSRF guard and returns no error on purpose. It answers "would this
// edit strand anything", a question that must stay answerable when the OLD
// endpoint no longer resolves — precisely the situation in which an admin needs
// to re-point the config. Validating the incoming URLs is the save path's job.
func IdentityOf(tenantCfg *types.TenantSandboxConfig) SandboxIdentity {
if tenantCfg == nil {
return SandboxIdentity{}
}
identity := SandboxIdentity{
Provider: tenantCfg.SandboxType,
AllowPrivateEndpoints: tenantCfg.AllowPrivateEndpoints,
}
switch SandboxType(tenantCfg.SandboxType) {
case SandboxTypeCube:
if cube := tenantCfg.Cube; cube != nil {
identity.APIURL, identity.APIKey = cube.APIURL, cube.APIKey
identity.SandboxDomain = cube.SandboxDomain
identity.ProxyURL = cube.ProxyURL
}
case SandboxTypeE2B:
if e2bCfg := tenantCfg.E2B; e2bCfg != nil {
identity.APIURL, identity.APIKey = e2bCfg.APIURL, e2bCfg.APIKey
identity.SandboxDomain = e2bCfg.SandboxDomain
identity.ProxyURL = e2bCfg.ProxyURL
}
case SandboxTypeDocker:
// The daemon endpoint is both planes at once: containers are created,
// exec'd and deleted over the same socket, so re-pointing it strands
// every sandbox this config owns. The image is not part of the
// identity — changing it only affects sandboxes created afterwards.
if docker := tenantCfg.Docker; docker != nil {
identity.APIURL = docker.Host
identity.APIKey = docker.TLSCertPath
}
}
return identity
}
+75
View File
@@ -0,0 +1,75 @@
package sandbox
import (
"testing"
"github.com/stretchr/testify/require"
"academy/internal/types"
)
// Identity comes from the stored row alone. Nothing about the deployment can
// change it, which is what makes "did this edit strand a sandbox" answerable
// without reaching for process-level sandbox configuration.
func TestIdentityOfReadsStoredFieldsOnly(t *testing.T) {
identity := IdentityOf(&types.TenantSandboxConfig{
SandboxType: "e2b",
E2B: &types.E2BSandboxConfig{
APIURL: "https://api.e2b.app", SandboxDomain: "e2b.app", APIKey: "key-a",
},
})
require.Equal(t, SandboxIdentity{
Provider: "e2b",
APIURL: "https://api.e2b.app",
APIKey: "key-a",
SandboxDomain: "e2b.app",
}, identity)
}
// A blank field is blank, not "whatever the deployment runs". Two configs that
// differ only in what they spell out are therefore different identities.
func TestIdentityOfDoesNotInherit(t *testing.T) {
blank := IdentityOf(&types.TenantSandboxConfig{SandboxType: "cube"})
spelledOut := IdentityOf(&types.TenantSandboxConfig{
SandboxType: "cube",
Cube: &types.CubeSandboxConfig{
APIURL: DefaultCubeAPIURL, ProxyURL: DefaultCubeProxyURL,
SandboxDomain: DefaultCubeSandboxDomain,
},
})
require.Equal(t, SandboxIdentity{Provider: "cube"}, blank)
require.NotEqual(t, blank, spelledOut)
require.Equal(t, DefaultCubeProxyURL, spelledOut.ProxyURL)
}
// Only the active provider describes where the sandboxes are; the other
// sub-struct is leftover state from an earlier switch.
func TestIdentityOfReadsOnlyActiveProvider(t *testing.T) {
cfg := &types.TenantSandboxConfig{
SandboxType: "e2b",
E2B: &types.E2BSandboxConfig{APIKey: "e2b-key"},
Cube: &types.CubeSandboxConfig{APIKey: "stale-cube-key"},
}
identity := IdentityOf(cfg)
require.Equal(t, "e2b-key", identity.APIKey)
require.Empty(t, identity.ProxyURL, "Cube's data plane is irrelevant while E2B is active")
}
// Backends that hold no remote resources carry no credentials, but switching
// between them still has to register as a change.
func TestIdentityOfDockerWithoutHostCarriesProviderOnly(t *testing.T) {
docker := IdentityOf(&types.TenantSandboxConfig{SandboxType: "docker"})
cube := IdentityOf(&types.TenantSandboxConfig{SandboxType: "cube"})
require.Equal(t, SandboxIdentity{Provider: "docker"}, docker)
require.NotEqual(t, docker, cube)
}
// A nil config must not panic: Update compares against it when creating.
func TestIdentityOfToleratesNilConfig(t *testing.T) {
require.Equal(t, SandboxIdentity{}, IdentityOf(nil))
}
+78
View File
@@ -0,0 +1,78 @@
// Package sandbox: what a named backend config must carry on its own.
//
// A named config is self-contained. Every value the provider client cannot
// synthesize has to be present in the workspace config itself, so this file
// names those values once and both save and resolve paths check against it.
//
// Two classes are deliberately NOT required:
//
// - Credentials a self-hosted deployment does not use. The common single-node
// Cube setup runs unauthenticated, so CubeAPIKey stays optional.
// - Values the SDK resolves by itself. go-e2b defaults both the API base URL
// and the sandbox domain when they are left empty, so demanding them would
// force operators to spell out constants they cannot verify.
//
// Everything else is required precisely because its absence fails late and
// obscurely: a missing Cube proxy URL or sandbox domain still creates a sandbox
// and only breaks when envd traffic is routed, which reads as a provider outage
// rather than a typo in the form.
package sandbox
import (
"errors"
"fmt"
"strings"
)
// ErrSandboxConfigIncomplete marks a named config that cannot build a working
// client because required fields are empty. Callers map it onto 400.
var ErrSandboxConfigIncomplete = errors.New("sandbox: config is missing required fields")
// MissingRequiredFields lists the fields cfg fails to supply for its own
// provider, named after the JSON keys the API and the settings form use so the
// message can be surfaced without translation. Disabled holds no
// backend-specific values; Docker must explicitly name its image.
func MissingRequiredFields(cfg *Config) []string {
if cfg == nil {
return nil
}
var missing []string
require := func(field, value string) {
if strings.TrimSpace(value) == "" {
missing = append(missing, field)
}
}
// host and disabled have no provider fields to require: host runs locally
// with no endpoint or credential, so they fall through and return empty.
switch cfg.Type {
case SandboxTypeCube:
require("api_url", cfg.CubeAPIURL)
require("proxy_url", cfg.CubeProxyURL)
require("sandbox_domain", cfg.CubeSandboxDomain)
require("template_id", cfg.CubeTemplate)
case SandboxTypeE2B:
require("api_key", cfg.E2BAPIKey)
require("template_id", cfg.E2BTemplate)
case SandboxTypeDocker:
require("image", cfg.DockerImage)
}
return missing
}
// RequireCompleteConfig is the error form of MissingRequiredFields, shared by
// the save path and the resolve path so both reject the same configs with the
// same wording.
func RequireCompleteConfig(cfg *Config) error {
missing := MissingRequiredFields(cfg)
if len(missing) == 0 {
return nil
}
provider := ""
if cfg != nil {
provider = string(cfg.Type)
}
return fmt.Errorf(
"%w: %s backend requires %s",
ErrSandboxConfigIncomplete, provider, strings.Join(missing, ", "),
)
}
+120
View File
@@ -0,0 +1,120 @@
// Package sandbox: per-config sandbox inventory.
//
// Identity changes (provider / endpoint / API key) and config deletion both
// need one question answered authoritatively: does this config still own live
// sandboxes on the provider?
//
// The binding store cannot answer it. Bindings go missing exactly when leaks
// happen - a CAS rebind overwrites the old sandbox ID, Redis evicts, a process
// restarts - so trusting them under-reports in the one direction that costs
// money. The provider's own listing is the source of truth.
package sandbox
import (
"context"
"errors"
"fmt"
"strconv"
"strings"
"academy/internal/types"
)
// ConfigSandboxLister is the read half of the provider client.
type ConfigSandboxLister interface {
List(ctx context.Context, filter RemoteListFilter) ([]RemoteSandboxSummary, error)
}
// ConfigSandboxClient adds deletion, needed to release an inventory.
type ConfigSandboxClient interface {
ConfigSandboxLister
Delete(ctx context.Context, sandboxID string) error
}
// NormalizeConfigID maps the empty config ID onto the sentinel used in
// metadata, so "the deployment default config" is addressable like any other.
func NormalizeConfigID(configID string) string {
if strings.TrimSpace(configID) == "" {
return types.SandboxConfigIDGlobalDefault
}
return configID
}
// MetadataSessionIDKey returns the provider metadata key used for session IDs.
func MetadataSessionIDKey() string {
return remoteMetadataSessionID
}
// MetadataAllocationUser marks a shared user machine in provider metadata.
const MetadataAllocationUser = "user"
// MetadataAllocationKey returns the provider metadata key for the allocation mode.
func MetadataAllocationKey() string { return remoteMetadataAllocation }
// configSandboxFilter narrows a listing to one workspace's one config.
func configSandboxFilter(tenantID uint64, configID string) RemoteListFilter {
return RemoteListFilter{
Metadata: map[string]string{
remoteMetadataTenantID: strconv.FormatUint(tenantID, 10),
remoteMetadataConfigID: NormalizeConfigID(configID),
},
// Paused sandboxes are not idle leftovers: they bill, and a session
// expects to resume them. Omitting them would report "nothing here"
// right before the credentials that could delete them are replaced.
States: []RemoteSandboxState{RemoteStateRunning, RemoteStatePaused},
}
}
// ListConfigSandboxes returns the sandboxes a config currently owns.
func ListConfigSandboxes(
ctx context.Context,
client ConfigSandboxLister,
tenantID uint64,
configID string,
) ([]RemoteSandboxSummary, error) {
if client == nil {
return nil, fmt.Errorf("sandbox: listing requires a client")
}
summaries, err := client.List(ctx, configSandboxFilter(tenantID, configID))
if err != nil {
return nil, fmt.Errorf(
"sandbox: list workspace %d config %q sandboxes: %w",
tenantID, NormalizeConfigID(configID), err)
}
return summaries, nil
}
// ReleaseConfigSandboxes deletes every sandbox the config owns and reports how
// many went away.
//
// This is deliberately NOT exposed as an admin action. Its one caller is the
// sweep that runs immediately after a config's credentials are overwritten,
// using the outgoing credentials still held in memory — the only remaining
// moment those sandboxes can be reached at all. An admin blocked from editing a
// config is instead told to end the owning sessions or create a second config.
//
// One undeletable sandbox does not abort the sweep - partial progress is
// strictly better than none - but the failures ARE returned. Swallowing them
// would leave a paused instance billing on credentials that no longer exist
// anywhere, with no record of which sandbox it was.
func ReleaseConfigSandboxes(
ctx context.Context,
client ConfigSandboxClient,
tenantID uint64,
configID string,
) (int, error) {
summaries, err := ListConfigSandboxes(ctx, client, tenantID, configID)
if err != nil {
return 0, err
}
deleted := 0
var failures []error
for _, summary := range summaries {
if err := client.Delete(ctx, summary.ID); err != nil {
failures = append(failures, fmt.Errorf("delete sandbox %s: %w", summary.ID, err))
continue
}
deleted++
}
return deleted, errors.Join(failures...)
}
+126
View File
@@ -0,0 +1,126 @@
package sandbox
import (
"context"
"errors"
"testing"
"github.com/stretchr/testify/require"
"academy/internal/types"
)
// fakeConfigSandboxClient records the filters it was asked for and serves a
// fixed inventory, so the test can assert both the query and the deletions.
type fakeConfigSandboxClient struct {
inventory []RemoteSandboxSummary
filters []RemoteListFilter
deleted []string
deleteFailures map[string]error
}
func (f *fakeConfigSandboxClient) List(
_ context.Context, filter RemoteListFilter,
) ([]RemoteSandboxSummary, error) {
f.filters = append(f.filters, filter)
var out []RemoteSandboxSummary
for _, s := range f.inventory {
match := true
for k, v := range filter.Metadata {
if s.Metadata[k] != v {
match = false
break
}
}
if match {
out = append(out, s)
}
}
return out, nil
}
func (f *fakeConfigSandboxClient) Delete(_ context.Context, sandboxID string) error {
if err := f.deleteFailures[sandboxID]; err != nil {
return err
}
f.deleted = append(f.deleted, sandboxID)
return nil
}
func summary(id, tenant, config string) RemoteSandboxSummary {
return RemoteSandboxSummary{
ID: id,
Metadata: map[string]string{
remoteMetadataTenantID: tenant,
remoteMetadataConfigID: config,
},
}
}
func TestListConfigSandboxesIncludesPausedAndScopesToConfig(t *testing.T) {
client := &fakeConfigSandboxClient{inventory: []RemoteSandboxSummary{
summary("sb-1", "7", "cfg-a"),
summary("sb-2", "7", "cfg-b"),
summary("sb-3", "8", "cfg-a"),
}}
got, err := ListConfigSandboxes(context.Background(), client, 7, "cfg-a")
require.NoError(t, err)
require.Len(t, got, 1)
require.Equal(t, "sb-1", got[0].ID)
require.Len(t, client.filters, 1)
require.Equal(t, "cfg-a", client.filters[0].Metadata[remoteMetadataConfigID])
require.Equal(t, "7", client.filters[0].Metadata[remoteMetadataTenantID])
require.ElementsMatch(t,
[]RemoteSandboxState{RemoteStateRunning, RemoteStatePaused},
client.filters[0].States,
"paused sandboxes still bill and are what a session expects to resume")
}
func TestListConfigSandboxesUsesSentinelForGlobalDefault(t *testing.T) {
client := &fakeConfigSandboxClient{inventory: []RemoteSandboxSummary{
summary("sb-1", "7", types.SandboxConfigIDGlobalDefault),
}}
got, err := ListConfigSandboxes(context.Background(), client, 7, "")
require.NoError(t, err)
require.Len(t, got, 1)
}
func TestMetadataSessionIDKeyReturnsSessionMetadataKey(t *testing.T) {
require.Equal(t, remoteMetadataSessionID, MetadataSessionIDKey())
}
// Releasing one config must not touch a sibling config that happens to use the
// same provider account.
func TestReleaseConfigSandboxesLeavesSiblingConfigAlone(t *testing.T) {
client := &fakeConfigSandboxClient{inventory: []RemoteSandboxSummary{
summary("sb-1", "7", "cfg-a"),
summary("sb-2", "7", "cfg-b"),
}}
deleted, err := ReleaseConfigSandboxes(context.Background(), client, 7, "cfg-a")
require.NoError(t, err)
require.Equal(t, 1, deleted)
require.Equal(t, []string{"sb-1"}, client.deleted)
}
func TestReleaseConfigSandboxesContinuesAndReturnsDeleteFailures(t *testing.T) {
client := &fakeConfigSandboxClient{
inventory: []RemoteSandboxSummary{
summary("sb-1", "7", "cfg-a"),
summary("sb-2", "7", "cfg-a"),
summary("sb-3", "7", "cfg-a"),
},
deleteFailures: map[string]error{
"sb-2": errors.New("provider delete failed"),
},
}
deleted, err := ReleaseConfigSandboxes(context.Background(), client, 7, "cfg-a")
require.Error(t, err)
require.ErrorContains(t, err, "sb-2")
require.Equal(t, 2, deleted)
require.Equal(t, []string{"sb-1", "sb-3"}, client.deleted)
}
+38
View File
@@ -0,0 +1,38 @@
package sandbox
import (
"fmt"
"net"
"strings"
)
// NormalizeCubeDNSServers trims, drops empties, rejects non-IP values, and
// de-duplicates. Cube's template `dns` field is a list of nameserver IPs —
// hostnames are not accepted. An empty result means "leave Cubelet's default".
func NormalizeCubeDNSServers(raw []string) ([]string, error) {
if len(raw) == 0 {
return nil, nil
}
out := make([]string, 0, len(raw))
seen := make(map[string]struct{}, len(raw))
for _, item := range raw {
ip := strings.TrimSpace(item)
if ip == "" {
continue
}
parsed := net.ParseIP(ip)
if parsed == nil {
return nil, fmt.Errorf("sandbox: invalid cube DNS server %q (need an IP address)", item)
}
canonical := parsed.String()
if _, dup := seen[canonical]; dup {
continue
}
seen[canonical] = struct{}{}
out = append(out, canonical)
}
if len(out) == 0 {
return nil, nil
}
return out, nil
}
+27
View File
@@ -0,0 +1,27 @@
package sandbox
import (
"testing"
"github.com/stretchr/testify/require"
)
func TestNormalizeCubeDNSServers(t *testing.T) {
got, err := NormalizeCubeDNSServers(nil)
require.NoError(t, err)
require.Nil(t, got)
got, err = NormalizeCubeDNSServers([]string{"", " "})
require.NoError(t, err)
require.Nil(t, got)
got, err = NormalizeCubeDNSServers([]string{
" 8.8.8.8 ", "8.8.8.8", "1.1.1.1",
})
require.NoError(t, err)
require.Equal(t, []string{"8.8.8.8", "1.1.1.1"}, got)
_, err = NormalizeCubeDNSServers([]string{"dns.google"})
require.Error(t, err)
require.Contains(t, err.Error(), "dns.google")
}
@@ -0,0 +1,60 @@
//go:build integration
package sandbox
import (
"context"
"strings"
"testing"
"time"
)
// TestIntegrationCubeClient_PublicEgress is the same check the settings
// wizard runs as "出网可用". It needs cube-egress listening on the cube-dev
// gateway and FORWARD/MASQUERADE for sandbox DNS.
func TestIntegrationCubeClient_PublicEgress(t *testing.T) {
cfg := integrationConfig(t)
client, err := NewCubeRemoteClient(cfg)
if err != nil {
t.Fatalf("NewCubeRemoteClient: %v", err)
}
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Minute)
defer cancel()
handle, err := client.Create(ctx, RemoteCreateRequest{
TemplateID: cfg.CubeTemplate,
Timeout: RemoteTimeoutPolicy{
Mode: RemoteTimeoutExplicit,
Value: integrationSandboxTTL,
Action: RemoteOnTimeoutKill,
},
})
if err != nil {
t.Fatalf("Create: %v", err)
}
t.Cleanup(func() {
cleanupCtx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
if err := client.Delete(cleanupCtx, handle.ID()); err != nil {
t.Logf("cleanup delete sandbox %s: %v", handle.ID(), err)
}
})
result, err := client.Exec(ctx, handle, RemoteExecRequest{
Command: `if curl -fsS -o /dev/null -m 8 -I 'https://www.baidu.com'; then echo 'cn:baidu'; exit 0; fi; echo "all probes failed" >&2; exit 1`,
Shell: true,
User: DefaultSandboxExecUser,
Timeout: 20 * time.Second,
})
if err != nil {
t.Fatalf("egress Exec: %v", err)
}
if result.ExitCode != 0 {
t.Fatalf("sandbox egress failed exit=%d stdout=%q stderr=%q",
result.ExitCode, result.Stdout, result.Stderr)
}
if !strings.Contains(result.Stdout, "cn:baidu") {
t.Fatalf("egress stdout missing marker: %q", result.Stdout)
}
}
+581
View File
@@ -0,0 +1,581 @@
//go:build integration
// Package sandbox integration tests against a locally-running CubeSandbox
// deployment. These tests DO NOT use any mock — they connect straight to a
// live CubeAPI + CubeProxy pair. Enable them with the `integration` build tag:
//
// CUBE_API_URL=http://127.0.0.1:33000 \
// CUBE_PROXY_URL=http://127.0.0.1:12088 \
// go test -tags=integration -run Integration -count=1 ./internal/sandbox/...
//
// If the environment variables are unset the tests fall back to the local
// dev defaults (127.0.0.1:33000 for the CubeAPI, 127.0.0.1:80 for the
// CubeProxy). A ready template is auto-discovered from /templates unless
// CUBE_TEMPLATE_ID is supplied.
//
// Every test hands its sandboxes back through Cleanup / Delete, so a
// clean run should leave no live MicroVMs behind.
package sandbox
import (
"bytes"
"context"
"encoding/json"
"net/http"
"os"
"strings"
"testing"
"time"
"academy/internal/types"
)
const (
// integrationDefaultAPIURL / integrationDefaultProxyURL match the user's
// local Cube deployment: CubeAPI on 33000, CubeProxy (openresty inside
// the cube-proxy docker container) on the host's port 80. The Dashboard
// (cube-webui) is exposed on 12088 and MUST NOT be used as a data-plane
// endpoint — POST requests against it return 405 because Dashboard is a
// static SPA server, not a routing proxy.
integrationDefaultAPIURL = "http://127.0.0.1:33000"
integrationDefaultProxyURL = "http://127.0.0.1:80"
integrationSandboxTTL = 5 * time.Minute
integrationHTTPTimeout = 30 * time.Second
integrationDefaultExecTimeout = 60 * time.Second
)
// integrationConfig builds a Config suitable for talking to the on-host Cube
// deployment. It probes /templates so tests survive template ID rotations,
// and applies short timeouts so a broken environment fails loudly instead of
// hanging.
func integrationConfig(t *testing.T) *Config {
t.Helper()
cfg := DefaultConfig()
cfg.Type = SandboxTypeCube
if v := strings.TrimSpace(os.Getenv("CUBE_API_URL")); v != "" {
cfg.CubeAPIURL = v
} else {
cfg.CubeAPIURL = integrationDefaultAPIURL
}
if v := strings.TrimSpace(os.Getenv("CUBE_PROXY_URL")); v != "" {
cfg.CubeProxyURL = v
} else {
cfg.CubeProxyURL = integrationDefaultProxyURL
}
cfg.CubeSandboxDomain = DefaultCubeSandboxDomain
cfg.CubeHTTPTimeout = integrationHTTPTimeout
cfg.CubeSandboxTTL = integrationSandboxTTL
cfg.DefaultTimeout = integrationDefaultExecTimeout
if v := strings.TrimSpace(os.Getenv("CUBE_TEMPLATE_ID")); v != "" {
cfg.CubeTemplate = v
} else {
cfg.CubeTemplate = discoverReadyTemplate(t, cfg.CubeAPIURL, cfg.CubeAPIKey)
}
t.Logf("Cube integration target api=%s proxy=%s template=%s domain=%s",
cfg.CubeAPIURL, cfg.CubeProxyURL, cfg.CubeTemplate, cfg.CubeSandboxDomain)
return cfg
}
// discoverReadyTemplate mirrors what the SDK's own integration suite does:
// pick the first READY template from the CubeAPI /templates listing so
// developers don't have to hard-code a template ID for local runs.
func discoverReadyTemplate(t *testing.T, apiURL, apiKey string) string {
t.Helper()
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cancel()
req, err := http.NewRequestWithContext(ctx, http.MethodGet, strings.TrimRight(apiURL, "/")+"/templates", nil)
if err != nil {
t.Fatalf("build templates request: %v", err)
}
if apiKey != "" {
req.Header.Set("Authorization", "Bearer "+apiKey)
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
t.Fatalf("list templates from %s: %v", apiURL, err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
t.Fatalf("list templates HTTP %d from %s", resp.StatusCode, apiURL)
}
var templates []struct {
TemplateID string `json:"templateID"`
Status string `json:"status"`
}
if err := json.NewDecoder(resp.Body).Decode(&templates); err != nil {
t.Fatalf("decode templates: %v", err)
}
for _, tpl := range templates {
if tpl.TemplateID != "" && strings.EqualFold(tpl.Status, "READY") {
return tpl.TemplateID
}
}
if len(templates) > 0 && templates[0].TemplateID != "" {
return templates[0].TemplateID
}
t.Fatalf("no templates found at %s; set CUBE_TEMPLATE_ID", apiURL)
return ""
}
// writeIntegrationScript drops a small Python script in a t.TempDir() so
// tests have a real filesystem path for ExecuteConfig.Script (the security
// validator still needs to read the file even though the sandbox executes
// the uploaded copy).
func writeIntegrationScript(t *testing.T, name, body string) string {
t.Helper()
dir := t.TempDir()
p := dir + "/" + name
if err := os.WriteFile(p, []byte(body), 0o644); err != nil {
t.Fatalf("write %s: %v", p, err)
}
return p
}
// -----------------------------------------------------------------------------
// Client-level tests (CubeRemoteClient directly)
// -----------------------------------------------------------------------------
// TestIntegrationCubeClient_HealthAndList sanity-checks that the /health
// endpoint responds and ListSandboxes deserialises. Failure here almost
// always means CubeAPI isn't running on the expected port.
func TestIntegrationCubeClient_HealthAndList(t *testing.T) {
cfg := integrationConfig(t)
client, err := NewCubeRemoteClient(cfg)
if err != nil {
t.Fatalf("NewCubeRemoteClient: %v", err)
}
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cancel()
if err := client.Health(ctx); err != nil {
t.Fatalf("Health: %v", err)
}
summaries, err := client.List(ctx, RemoteListFilter{})
if err != nil {
t.Fatalf("List: %v", err)
}
t.Logf("current live sandboxes: %d", len(summaries))
}
// TestIntegrationCubeClient_CreateConnectRoundTrip validates that Create +
// Connect + Get form a consistent lifecycle round-trip through the real
// CubeAPI. It replaces the old ConnectRoundTripRequiresTimeout test which
// verified the SDK connect body patch — that patch is now handled internally
// by CubeRemoteClient.
func TestIntegrationCubeClient_CreateConnectRoundTrip(t *testing.T) {
cfg := integrationConfig(t)
client, err := NewCubeRemoteClient(cfg)
if err != nil {
t.Fatalf("NewCubeRemoteClient: %v", err)
}
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Minute)
defer cancel()
handle, err := client.Create(ctx, RemoteCreateRequest{
TemplateID: cfg.CubeTemplate,
Timeout: RemoteTimeoutPolicy{
Mode: RemoteTimeoutExplicit,
Value: integrationSandboxTTL,
Action: RemoteOnTimeoutKill,
},
})
if err != nil {
t.Fatalf("Create: %v", err)
}
sandboxID := handle.ID()
t.Logf("created sandbox %s", sandboxID)
t.Cleanup(func() {
cleanupCtx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
if err := client.Delete(cleanupCtx, sandboxID); err != nil {
t.Logf("cleanup delete sandbox %s: %v", sandboxID, err)
}
})
// Verify the sandbox is immediately visible via Get.
summary, err := client.Get(ctx, sandboxID)
if err != nil {
t.Fatalf("Get after create: %v", err)
}
if summary == nil || summary.ID != sandboxID {
t.Fatalf("Get returned unexpected summary: %#v", summary)
}
// Reconnect to the same sandbox — this is the critical path that
// exercises CubeAPI's /sandboxes/{id}/connect endpoint.
reattached, err := client.Connect(ctx, RemoteConnectRequest{SandboxID: sandboxID})
if err != nil {
t.Fatalf("Connect existing sandbox via real CubeAPI: %v", err)
}
if reattached == nil || reattached.ID() != sandboxID {
t.Fatalf("reattached sandbox ID = %s, want %s", reattached.ID(), sandboxID)
}
// Verify the reattached handle can also be looked up.
summary2, err := client.Get(ctx, sandboxID)
if err != nil {
t.Fatalf("Get after reconnect: %v", err)
}
if summary2 == nil || summary2.ID != sandboxID {
t.Fatalf("Get after reconnect returned unexpected summary: %#v", summary2)
}
}
// TestIntegrationCubeClient_LifecycleRoundTrip exercises the full lifecycle
// against a real sandbox: Create → WriteFile → ReadFile → Exec → Delete.
func TestIntegrationCubeClient_LifecycleRoundTrip(t *testing.T) {
cfg := integrationConfig(t)
client, err := NewCubeRemoteClient(cfg)
if err != nil {
t.Fatalf("NewCubeRemoteClient: %v", err)
}
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Minute)
defer cancel()
handle, err := client.Create(ctx, RemoteCreateRequest{
TemplateID: cfg.CubeTemplate,
Timeout: RemoteTimeoutPolicy{
Mode: RemoteTimeoutExplicit,
Value: integrationSandboxTTL,
Action: RemoteOnTimeoutKill,
},
})
if err != nil {
t.Fatalf("Create: %v", err)
}
sandboxID := handle.ID()
t.Logf("created sandbox %s", sandboxID)
t.Cleanup(func() {
cleanupCtx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
if err := client.Delete(cleanupCtx, sandboxID); err != nil {
t.Logf("cleanup delete sandbox %s: %v", sandboxID, err)
}
})
// Write a file inside the sandbox.
path := "/tmp/academy-integration.txt"
payload := []byte("hello from academy integration\n")
if err := client.WriteFile(ctx, handle, path, payload); err != nil {
t.Fatalf("WriteFile: %v", err)
}
// Read the file back.
got, err := client.ReadFile(ctx, handle, path)
if err != nil {
t.Fatalf("ReadFile: %v", err)
}
if !bytes.Equal(got, payload) {
t.Fatalf("read back mismatch: got=%q want=%q", string(got), string(payload))
}
// Run a shell command that echoes the file to stdout.
result, err := client.Exec(ctx, handle, RemoteExecRequest{
Command: "cat",
Args: []string{path},
WorkDir: "/tmp",
Timeout: integrationDefaultExecTimeout,
})
if err != nil {
t.Fatalf("Exec: %v", err)
}
if result.ExitCode != 0 {
t.Fatalf("Exec exit code: %d stderr=%q", result.ExitCode, result.Stderr)
}
if !strings.Contains(result.Stdout, "hello from academy integration") {
t.Fatalf("stdout missing marker: %q", result.Stdout)
}
// Explicitly delete and verify it's gone.
if err := client.Delete(ctx, sandboxID); err != nil {
t.Fatalf("Delete: %v", err)
}
summary, err := client.Get(ctx, sandboxID)
if err != nil {
if IsRemoteNotFound(err) {
t.Logf("sandbox %s confirmed deleted (not-found)", sandboxID)
return
}
t.Fatalf("Get after delete: %v", err)
}
if summary != nil {
t.Logf("sandbox still visible right after delete (state=%s) — acceptable eventual-consistency window", summary.State)
}
}
// TestIntegrationCubeClient_FilesystemOps covers the filesystem RPCs:
// MakeDir, WriteFile, ListDir, Stat, and Remove. It's kept separate from
// the lifecycle test so failures point at the right subsystem.
func TestIntegrationCubeClient_FilesystemOps(t *testing.T) {
cfg := integrationConfig(t)
client, err := NewCubeRemoteClient(cfg)
if err != nil {
t.Fatalf("NewCubeRemoteClient: %v", err)
}
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Minute)
defer cancel()
handle, err := client.Create(ctx, RemoteCreateRequest{
TemplateID: cfg.CubeTemplate,
Timeout: RemoteTimeoutPolicy{
Mode: RemoteTimeoutExplicit,
Value: integrationSandboxTTL,
Action: RemoteOnTimeoutKill,
},
})
if err != nil {
t.Fatalf("Create: %v", err)
}
t.Cleanup(func() {
cleanupCtx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
_ = client.Delete(cleanupCtx, handle.ID())
})
base := "/tmp/academy-fs"
if err := client.MakeDir(ctx, handle, base); err != nil {
t.Fatalf("MakeDir %s: %v", base, err)
}
// Write two files to verify listing.
src := base + "/one.txt"
another := base + "/another.txt"
if err := client.WriteFile(ctx, handle, src, []byte("aaa")); err != nil {
t.Fatalf("WriteFile: %v", err)
}
if err := client.WriteFile(ctx, handle, another, []byte("bbb")); err != nil {
t.Fatalf("WriteFile: %v", err)
}
entries, err := client.ListDir(ctx, handle, base)
if err != nil {
t.Fatalf("ListDir %s: %v", base, err)
}
foundOne := false
foundAnother := false
for _, e := range entries {
if e.Name == "one.txt" {
foundOne = true
}
if e.Name == "another.txt" {
foundAnother = true
}
}
if !foundOne || !foundAnother {
t.Fatalf("ListDir did not surface expected files: %#v", entries)
}
stat, err := client.Stat(ctx, handle, src)
if err != nil {
t.Fatalf("Stat %s: %v", src, err)
}
if stat == nil {
t.Fatalf("Stat returned nil for existing path %s", src)
}
if stat.Type != RemoteEntryFile {
t.Fatalf("Stat type=%q, want file", stat.Type)
}
missing, err := client.Stat(ctx, handle, base+"/does-not-exist")
if err != nil {
t.Fatalf("Stat missing: unexpected error %v", err)
}
if missing != nil {
t.Fatalf("Stat missing returned entry: %#v", missing)
}
if err := client.Remove(ctx, handle, src); err != nil {
t.Fatalf("Remove %s: %v", src, err)
}
remaining, err := client.ListDir(ctx, handle, base)
if err != nil {
t.Fatalf("ListDir after remove: %v", err)
}
for _, e := range remaining {
if e.Name == "one.txt" {
t.Fatalf("'one.txt' still present after Remove")
}
}
if err := client.Remove(ctx, handle, base); err != nil {
t.Fatalf("Remove %s: %v", base, err)
}
}
// -----------------------------------------------------------------------------
// End-to-end tests through SessionBoundManager
// -----------------------------------------------------------------------------
// TestIntegrationRemoteSandbox_EphemeralExecute exercises the empty-SessionID
// path through SessionBoundManager: the manager allocates a fresh MicroVM,
// runs the script, and tears it down — same wire behaviour Docker
// sandboxes present per Execute.
func TestIntegrationRemoteSandbox_EphemeralExecute(t *testing.T) {
mgr := newIntegrationManager(t)
script := writeIntegrationScript(t, "hello.py", "print('academy-integration-hi')\n")
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Minute)
defer cancel()
result, err := mgr.Execute(ctx, &ExecuteConfig{
Script: script,
SkipValidation: true,
})
if err != nil {
t.Fatalf("Execute: %v", err)
}
if result.ExitCode != 0 {
t.Fatalf("exit code %d stderr=%q err=%q", result.ExitCode, result.Stderr, result.Error)
}
if !strings.Contains(result.Stdout, "academy-integration-hi") {
t.Fatalf("stdout missing expected marker: %q", result.Stdout)
}
}
// TestIntegrationSessionBoundManager_StatePersistsAcrossExecutes verifies
// the flagship feature of the Cube backend: two Execute calls that share the
// same SessionID must hit the same MicroVM, so packages installed / files
// created by the first call are visible to the second.
func TestIntegrationSessionBoundManager_StatePersistsAcrossExecutes(t *testing.T) {
mgr := newIntegrationManager(t)
baseCtx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
defer cancel()
ctx := integrationTenantContext(baseCtx)
first := writeIntegrationScript(t, "write.py", strings.Join([]string{
"with open('/tmp/academy-session-marker', 'w') as f:",
" f.write('session-state-ok')",
"print('wrote marker')",
"",
}, "\n"))
second := writeIntegrationScript(t, "read.py", strings.Join([]string{
"with open('/tmp/academy-session-marker') as f:",
" print('marker=' + f.read())",
"",
}, "\n"))
sess := "integration-sess-alpha"
if r, err := mgr.Execute(ctx, &ExecuteConfig{
Script: first, SessionID: sess, SkipValidation: true,
}); err != nil || r.ExitCode != 0 {
t.Fatalf("first Execute: err=%v exit=%d stderr=%q", err, safeExit(r), safeStderr(r))
}
r2, err := mgr.Execute(ctx, &ExecuteConfig{
Script: second, SessionID: sess, SkipValidation: true,
})
if err != nil {
t.Fatalf("second Execute: %v", err)
}
if r2.ExitCode != 0 {
t.Fatalf("second Execute exit=%d stderr=%q", r2.ExitCode, r2.Stderr)
}
if !strings.Contains(r2.Stdout, "marker=session-state-ok") {
t.Fatalf("session state didn't persist across executes; stdout=%q", r2.Stdout)
}
// Third leg: a *different* SessionID must NOT see the marker. This is
// the negative half of the isolation contract; skipping it would let a
// regression that collapses all sessions onto the same VM slip by.
miss := writeIntegrationScript(t, "miss.py", strings.Join([]string{
"import os",
"print('exists=' + str(os.path.exists('/tmp/academy-session-marker')))",
"",
}, "\n"))
r3, err := mgr.Execute(ctx, &ExecuteConfig{
Script: miss, SessionID: "integration-sess-beta", SkipValidation: true,
})
if err != nil {
t.Fatalf("third Execute: %v", err)
}
if r3.ExitCode != 0 {
t.Fatalf("third Execute exit=%d stderr=%q", r3.ExitCode, r3.Stderr)
}
if !strings.Contains(r3.Stdout, "exists=False") {
t.Fatalf("session isolation broken; stdout=%q", r3.Stdout)
}
}
// TestIntegrationSessionBoundManager_DestroySession asserts that
// DestroySession actually reaches CubeAPI and cleans the MicroVM up.
func TestIntegrationSessionBoundManager_DestroySession(t *testing.T) {
mgr := newIntegrationManager(t)
baseCtx, cancel := context.WithTimeout(context.Background(), 3*time.Minute)
defer cancel()
ctx := integrationTenantContext(baseCtx)
script := writeIntegrationScript(t, "touch.py", "print('destroy-me')\n")
if _, err := mgr.Execute(ctx, &ExecuteConfig{
Script: script,
SessionID: "integration-destroy",
SkipValidation: true,
}); err != nil {
t.Fatalf("prime Execute: %v", err)
}
if err := mgr.DestroySession(ctx, "integration-destroy"); err != nil {
t.Fatalf("DestroySession: %v", err)
}
// Second destroy is a no-op.
if err := mgr.DestroySession(ctx, "integration-destroy"); err != nil {
t.Fatalf("second DestroySession: %v", err)
}
}
// safeExit / safeStderr shield the assertion helpers above from nil results
// so a transport error doesn't crash the test before we've had a chance to
// report the real cause.
func safeExit(r *ExecuteResult) int {
if r == nil {
return -1
}
return r.ExitCode
}
func safeStderr(r *ExecuteResult) string {
if r == nil {
return ""
}
return r.Stderr
}
// newIntegrationManager wires a SessionBoundManager against the live Cube
// deployment described by integrationConfig. Every integration test uses this
// helper so provider adapter, binding store, and existence checker stay in
// one place.
func newIntegrationManager(t *testing.T) *SessionBoundManager {
t.Helper()
cfg := integrationConfig(t)
client, err := NewCubeRemoteClient(cfg)
if err != nil {
t.Fatalf("NewCubeRemoteClient: %v", err)
}
mgr, err := NewSessionBoundManager(SessionBoundManagerConfig{
Config: cfg,
Client: client,
Store: NewMemorySessionSandboxBindingStore(),
Checker: PermissiveSessionExistenceChecker{},
})
if err != nil {
t.Fatalf("NewSessionBoundManager: %v", err)
}
t.Cleanup(func() { _ = mgr.Cleanup(context.Background()) })
return mgr
}
// integrationTenantContext supplies the tenant ID SessionBoundManager needs
// when resolving session-scoped operations.
func integrationTenantContext(parent context.Context) context.Context {
return context.WithValue(parent, types.TenantIDContextKey, uint64(1))
}
+692
View File
@@ -0,0 +1,692 @@
package sandbox
import (
"bytes"
"encoding/base64"
"encoding/binary"
"encoding/json"
"fmt"
"io"
"net"
"net/http"
"net/http/httptest"
"strconv"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
)
// cubeMockServer emulates the Cube control-plane API and envd data-plane
// endpoints that the Cube SDK speaks to. CubeRemoteClient tests exercise the
// adapter through its public surface without requiring a real Cube deployment.
type cubeMockServer struct {
server *httptest.Server
mu sync.Mutex
createBody map[string]any
connectCount atomic.Int32
infoCount atomic.Int32
createCount atomic.Int32
killCount atomic.Int32
nextID atomic.Int64
sandboxes map[string]map[string]any // sandboxID → sandbox state record
snapshots []cubeMockSnapshot
snapshotSeq int64
snapshotPageSize int
snapshotStuckPagination bool // always return the same non-empty next token
snapshotDeleteFailWith int // when set, DELETE /templates/:id returns this status
snapshotCreateBody map[string]any
trafficAccessToken string
connectTrafficToken string
executor func(sandboxID, cmd string, args []string) (stdout, stderr string, exitCode int)
files map[string]map[string][]byte // sandboxID → path → content
cmdHistory []commandRecord
// ptyHoldAfterStart, when set, keeps the envd PTY stream open and
// delays the first output chunk so tests can observe HTTP-client
// timeouts that fire while the stream is still alive.
ptyHoldAfterStart time.Duration
ptyLatePayload string
ptyPID int
ptyStartCount atomic.Int32
ptyConnectCount atomic.Int32
timeoutPOSTs atomic.Int32
}
type cubeMockSnapshot struct {
id string
sandboxID string
names []string
}
type commandRecord struct {
sandboxID string
cmd string
args []string
}
func newCubeMockServer(t *testing.T) *cubeMockServer {
t.Helper()
m := &cubeMockServer{
sandboxes: map[string]map[string]any{},
files: map[string]map[string][]byte{},
}
m.server = httptest.NewServer(http.HandlerFunc(m.handle))
t.Cleanup(m.server.Close)
return m
}
func (m *cubeMockServer) URL() string { return m.server.URL }
// SetExecutor installs a callback that is invoked when a command is executed
// inside any sandbox managed by this mock.
func (m *cubeMockServer) SetExecutor(f func(sandboxID, cmd string, args []string) (stdout, stderr string, exitCode int)) {
m.mu.Lock()
defer m.mu.Unlock()
m.executor = f
}
func (m *cubeMockServer) handle(w http.ResponseWriter, r *http.Request) {
// envd data-plane requests are routed through the proxy with a Host
// header of the form "49983-{sandboxID}.{domain}". Detect and handle
// them before falling through to the control-plane routes.
if isEnvdRequest(r.Host, "cube.app") {
m.handleEnvd(w, r)
return
}
switch {
case r.URL.Path == "/sandboxes" && r.Method == http.MethodPost:
m.handleCreate(w, r)
case r.URL.Path == "/sandboxes" && r.Method == http.MethodGet:
m.handleList(w, r)
case strings.HasPrefix(r.URL.Path, "/sandboxes/") && strings.HasSuffix(r.URL.Path, "/timeout") && r.Method == http.MethodPost:
m.handleSetTimeout(w, r)
case strings.HasPrefix(r.URL.Path, "/sandboxes/") && strings.HasSuffix(r.URL.Path, "/connect") && r.Method == http.MethodPost:
m.connectCount.Add(1)
m.handleConnect(w, r)
case strings.HasPrefix(r.URL.Path, "/sandboxes/") && strings.HasSuffix(r.URL.Path, "/snapshots") && r.Method == http.MethodPost:
m.handleCreateSnapshot(w, r)
case r.URL.Path == "/snapshots" && r.Method == http.MethodGet:
m.handleListSnapshots(w, r)
case strings.HasPrefix(r.URL.Path, "/templates/") && r.Method == http.MethodDelete:
m.handleDeleteSnapshot(w, r)
case strings.HasPrefix(r.URL.Path, "/sandboxes/") && r.Method == http.MethodGet:
m.infoCount.Add(1)
m.handleGetInfo(w, r)
case strings.HasPrefix(r.URL.Path, "/sandboxes/") && r.Method == http.MethodDelete:
m.handleDelete(w, r)
case r.URL.Path == "/health" && r.Method == http.MethodGet:
writeJSON(w, http.StatusOK, map[string]string{"status": "ok"})
default:
http.NotFound(w, r)
}
}
func (m *cubeMockServer) handleCreate(w http.ResponseWriter, r *http.Request) {
m.createCount.Add(1)
body, _ := io.ReadAll(r.Body)
var raw map[string]any
_ = json.Unmarshal(body, &raw)
m.mu.Lock()
m.createBody = raw
id := "cube-" + strconv.FormatInt(m.nextID.Add(1), 10)
metadata := map[string]string{}
if rawMeta, ok := raw["metadata"].(map[string]any); ok {
for k, v := range rawMeta {
metadata[k] = fmt.Sprint(v)
}
}
m.sandboxes[id] = map[string]any{
"sandboxID": id,
"templateID": raw["templateID"],
"clientID": "client-" + id,
"state": "running",
"envdVersion": "test",
"metadata": metadata,
"startedAt": time.Now().UTC().Format(time.RFC3339),
}
m.files[id] = map[string][]byte{}
trafficAccessToken := m.trafficAccessToken
m.mu.Unlock()
response := map[string]any{
"sandboxID": id,
"clientID": "client-" + id,
"envdVersion": "test",
"domain": "cube.app",
}
if trafficAccessToken != "" {
response["trafficAccessToken"] = trafficAccessToken
}
writeJSON(w, http.StatusCreated, response)
}
func (m *cubeMockServer) handleConnect(w http.ResponseWriter, r *http.Request) {
id := extractSandboxID(r.URL.Path, "/connect")
m.mu.Lock()
_, ok := m.sandboxes[id]
connectTrafficToken := m.connectTrafficToken
m.mu.Unlock()
if !ok {
w.WriteHeader(http.StatusNotFound)
writeJSON(w, http.StatusNotFound, map[string]string{"message": "sandbox not found"})
return
}
response := map[string]any{
"sandboxID": id,
"clientID": "client-" + id,
"envdVersion": "test",
"domain": "cube.app",
}
if connectTrafficToken != "" {
response["trafficAccessToken"] = connectTrafficToken
}
writeJSON(w, http.StatusOK, response)
}
func (m *cubeMockServer) handleGetInfo(w http.ResponseWriter, r *http.Request) {
id := extractSandboxID(r.URL.Path, "")
m.mu.Lock()
info, ok := m.sandboxes[id]
m.mu.Unlock()
if !ok {
w.WriteHeader(http.StatusNotFound)
writeJSON(w, http.StatusNotFound, map[string]string{"message": "sandbox not found"})
return
}
data := cloneMap(info)
data["sandboxID"] = id
writeJSON(w, http.StatusOK, data)
}
func (m *cubeMockServer) handleList(w http.ResponseWriter, r *http.Request) {
m.mu.Lock()
defer m.mu.Unlock()
items := make([]map[string]any, 0, len(m.sandboxes))
for id, info := range m.sandboxes {
cp := cloneMap(info)
cp["sandboxID"] = id
items = append(items, cp)
}
writeJSON(w, http.StatusOK, items)
}
func (m *cubeMockServer) handleDelete(w http.ResponseWriter, r *http.Request) {
id := extractSandboxID(r.URL.Path, "")
m.mu.Lock()
_, ok := m.sandboxes[id]
if ok {
delete(m.sandboxes, id)
delete(m.files, id)
}
m.mu.Unlock()
if !ok {
w.WriteHeader(http.StatusNotFound)
return
}
m.killCount.Add(1)
w.WriteHeader(http.StatusNoContent)
}
func (m *cubeMockServer) handleCreateSnapshot(w http.ResponseWriter, r *http.Request) {
id := extractSandboxID(r.URL.Path, "/snapshots")
body, _ := io.ReadAll(r.Body)
var raw map[string]any
_ = json.Unmarshal(body, &raw)
m.mu.Lock()
defer m.mu.Unlock()
if _, ok := m.sandboxes[id]; !ok {
writeJSON(w, http.StatusNotFound, map[string]string{"message": "sandbox not found"})
return
}
m.snapshotCreateBody = raw
m.snapshotSeq++
snapshotID := "snap-" + strconv.FormatInt(m.snapshotSeq, 10)
var names []string
if rawName, ok := raw["name"].(string); ok {
if name := strings.TrimSpace(rawName); name != "" {
names = []string{name}
}
}
m.snapshots = append(m.snapshots, cubeMockSnapshot{
id: snapshotID,
sandboxID: id,
names: names,
})
writeJSON(w, http.StatusCreated, map[string]any{
"snapshotID": snapshotID,
"names": names,
})
}
func (m *cubeMockServer) handleListSnapshots(w http.ResponseWriter, r *http.Request) {
sandboxID := r.URL.Query().Get("sandboxID")
start := 0
if token := r.URL.Query().Get("nextToken"); token != "" {
if parsed, err := strconv.Atoi(token); err == nil && parsed > 0 {
start = parsed
}
}
m.mu.Lock()
defer m.mu.Unlock()
pageSize := m.snapshotPageSize
if pageSize <= 0 {
pageSize = len(m.snapshots)
}
filtered := make([]cubeMockSnapshot, 0, len(m.snapshots))
for _, snapshot := range m.snapshots {
if sandboxID != "" && snapshot.sandboxID != sandboxID {
continue
}
filtered = append(filtered, snapshot)
}
if start > len(filtered) {
start = len(filtered)
}
end := start + pageSize
if end > len(filtered) {
end = len(filtered)
}
items := make([]map[string]any, 0, end-start)
for _, snapshot := range filtered[start:end] {
items = append(items, map[string]any{
"snapshotID": snapshot.id,
"names": snapshot.names,
})
}
if m.snapshotStuckPagination {
w.Header().Set("x-next-token", "stuck")
} else if end < len(filtered) {
w.Header().Set("x-next-token", strconv.Itoa(end))
}
writeJSON(w, http.StatusOK, items)
}
func (m *cubeMockServer) handleDeleteSnapshot(w http.ResponseWriter, r *http.Request) {
id := strings.TrimPrefix(r.URL.Path, "/templates/")
m.mu.Lock()
failWith := m.snapshotDeleteFailWith
m.mu.Unlock()
if failWith != 0 {
writeJSON(w, failWith, map[string]string{"message": "internal error"})
return
}
m.mu.Lock()
defer m.mu.Unlock()
for i, snapshot := range m.snapshots {
if snapshot.id != id {
continue
}
m.snapshots = append(m.snapshots[:i], m.snapshots[i+1:]...)
w.WriteHeader(http.StatusNoContent)
return
}
writeJSON(w, http.StatusNotFound, map[string]string{"message": "template not found"})
}
// handleEnvd intercepts data-plane requests that the Cube SDK sends through
// the proxy. These carry a Host header like "49983-{sandboxID}.cube.app".
func (m *cubeMockServer) handleEnvd(w http.ResponseWriter, r *http.Request) {
sandboxID := extractSandboxIDFromHost(r.Host, "cube.app")
if sandboxID == "" {
http.NotFound(w, r)
return
}
switch {
case strings.Contains(r.URL.Path, "/process.Process/Start"):
body, _ := io.ReadAll(r.Body)
if envdBodyLooksLikePty(body) {
m.ptyStartCount.Add(1)
m.handlePtyStream(w, r)
return
}
r.Body = io.NopCloser(bytes.NewBuffer(body))
m.handleCommandExec(w, r, sandboxID)
case strings.Contains(r.URL.Path, "/process.Process/Connect"):
m.ptyConnectCount.Add(1)
m.handlePtyStream(w, r)
return
case strings.Contains(r.URL.Path, "/filesystem") && (strings.Contains(r.URL.Path, "Read") || strings.Contains(r.URL.Path, "Stat") || strings.Contains(r.URL.Path, "ListDir")):
m.handleFileRead(w, r, sandboxID)
case strings.Contains(r.URL.Path, "/filesystem") && strings.Contains(r.URL.Path, "MakeDir"):
body, _ := io.ReadAll(r.Body)
r.Body = io.NopCloser(bytes.NewBuffer(body))
writeJSON(w, http.StatusOK, map[string]any{"type": "directory"})
case strings.Contains(r.URL.Path, "/files") || containsPath(r.URL.Path, "Write"):
body, _ := io.ReadAll(r.Body)
r.Body = io.NopCloser(bytes.NewBuffer(body))
m.handleFileWrite(w, r, sandboxID)
default:
writeJSON(w, http.StatusOK, map[string]any{})
}
}
// handleCommandExec intercepts envd /process.Process/Start and dispatches to
// the mock's executor callback.
func (m *cubeMockServer) handleCommandExec(w http.ResponseWriter, r *http.Request, sandboxID string) {
m.mu.Lock()
exec := m.executor
m.mu.Unlock()
if exec == nil {
writeEnvdCommandResult(w, "", "", 0)
return
}
cmd := "/bin/bash"
args := []string{"-l", "-c", "<shell-line>"}
body, _ := io.ReadAll(r.Body)
// The envd body is connect-framed: [1 byte flags][4 bytes big-endian len][JSON].
if len(body) >= 5 {
msgLen := binary.BigEndian.Uint32(body[1:5])
if int(msgLen)+5 <= len(body) {
jsonBytes := body[5 : 5+int(msgLen)]
var req struct {
Process struct {
Cmd string `json:"cmd"`
Args []string `json:"args"`
} `json:"process"`
}
if json.Unmarshal(jsonBytes, &req) == nil && req.Process.Cmd != "" {
cmd = req.Process.Cmd
args = req.Process.Args
}
}
}
m.mu.Lock()
m.cmdHistory = append(m.cmdHistory, commandRecord{
sandboxID: sandboxID,
cmd: cmd,
args: args,
})
m.mu.Unlock()
stdout, stderr, code := exec(sandboxID, cmd, args)
writeEnvdCommandResult(w, stdout, stderr, code)
}
func (m *cubeMockServer) handleSetTimeout(w http.ResponseWriter, r *http.Request) {
id := extractSandboxID(r.URL.Path, "/timeout")
m.mu.Lock()
_, ok := m.sandboxes[id]
m.mu.Unlock()
if !ok {
writeJSON(w, http.StatusNotFound, map[string]string{"message": "sandbox not found"})
return
}
m.timeoutPOSTs.Add(1)
w.WriteHeader(http.StatusNoContent)
}
func envdBodyLooksLikePty(body []byte) bool {
payload := body
if len(body) >= 5 {
n := binary.BigEndian.Uint32(body[1:5])
if int(n)+5 <= len(body) {
payload = body[5 : 5+int(n)]
}
}
var req struct {
PTY json.RawMessage `json:"pty"`
}
return json.Unmarshal(payload, &req) == nil && len(req.PTY) > 0
}
func (m *cubeMockServer) handlePtyStream(w http.ResponseWriter, r *http.Request) {
flusher, _ := w.(http.Flusher)
pid := m.ptyPID
if pid == 0 {
pid = 4321
}
late := m.ptyLatePayload
if late == "" {
late = "late-frame"
}
hold := m.ptyHoldAfterStart
w.Header().Set("Content-Type", "application/connect+json")
w.WriteHeader(http.StatusOK)
startJSON, _ := json.Marshal(map[string]any{
"event": map[string]any{"start": map[string]any{"pid": pid}},
})
var startBuf bytes.Buffer
writeConnectFrame(&startBuf, startJSON)
_, _ = w.Write(startBuf.Bytes())
if flusher != nil {
flusher.Flush()
}
if hold > 0 {
select {
case <-r.Context().Done():
return
case <-time.After(hold):
}
}
dataJSON, _ := json.Marshal(map[string]any{
"event": map[string]any{
"data": map[string]any{"pty": base64Encode(late)},
},
})
var dataBuf bytes.Buffer
writeConnectFrame(&dataBuf, dataJSON)
_, _ = w.Write(dataBuf.Bytes())
if flusher != nil {
flusher.Flush()
}
<-r.Context().Done()
}
func (m *cubeMockServer) handleFileWrite(w http.ResponseWriter, r *http.Request, sandboxID string) {
body, _ := io.ReadAll(r.Body)
r.Body = io.NopCloser(bytes.NewBuffer(body))
// The Cube SDK sends WriteFile as POST /files?path=%2Fworkspace%2Fhello.txt
// with the raw file content as the body (no connect framing).
path := r.URL.Query().Get("path")
if path == "" || !strings.HasPrefix(path, "/") {
path = "/workspace/unknown"
}
m.mu.Lock()
if m.files[sandboxID] == nil {
m.files[sandboxID] = map[string][]byte{}
}
// Store only the raw file content, not the full HTTP body framing.
m.files[sandboxID][path] = body
m.mu.Unlock()
writeJSON(w, http.StatusOK, map[string]any{})
}
// extractFilePathFromBody strips connect framing from the body and parses
// the JSON content to extract the file path. The Cube SDK uses connect+json
// for filesystem RPC, so the body is: [1 byte flags][4 bytes big-endian len][JSON].
// The JSON contains a "path" field.
func extractFilePathFromBody(body []byte) string {
// Strip connect frame envelope: 1 byte flags + 4 bytes big-endian length.
if len(body) < 5 {
return "/workspace/unknown"
}
msgLen := binary.BigEndian.Uint32(body[1:5])
if int(msgLen)+5 > len(body) {
return "/workspace/unknown"
}
jsonBytes := body[5 : 5+int(msgLen)]
var req struct {
Path string `json:"path"`
}
if json.Unmarshal(jsonBytes, &req) == nil && strings.HasPrefix(req.Path, "/") {
return req.Path
}
return "/workspace/unknown"
}
func (m *cubeMockServer) handleFileRead(w http.ResponseWriter, _ *http.Request, sandboxID string) {
m.mu.Lock()
files := m.files[sandboxID]
m.mu.Unlock()
if files == nil {
writeJSON(w, http.StatusOK, map[string]any{"content": ""})
return
}
// Return the content of the requested file.
writeJSON(w, http.StatusOK, map[string]any{"content": ""})
}
// --- helpers ---
func cloneMap(src map[string]any) map[string]any {
dst := make(map[string]any, len(src))
for k, v := range src {
dst[k] = v
}
return dst
}
func writeJSON(w http.ResponseWriter, status int, v any) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
_ = json.NewEncoder(w).Encode(v)
}
func writeEnvdCommandResult(w http.ResponseWriter, stdout, stderr string, exitCode int) {
// The Cube SDK ProcessEvent format: {"event":{...}}
// stdout/stderr in data events MUST be base64-encoded (SDK calls
// base64.StdEncoding.DecodeString on them).
// Stream must include: start event, optional data events, end event,
// then an end-of-stream connect frame (flags=0x02).
var body bytes.Buffer
// start event
startJSON, _ := json.Marshal(map[string]any{
"event": map[string]any{
"start": map[string]any{"pid": 1},
},
})
writeConnectFrame(&body, startJSON)
// data event (if there is output) — stdout/stderr must be base64-encoded
if stdout != "" || stderr != "" {
dataJSON, _ := json.Marshal(map[string]any{
"event": map[string]any{
"data": map[string]any{
"stdout": base64Encode(stdout),
"stderr": base64Encode(stderr),
},
},
})
writeConnectFrame(&body, dataJSON)
}
// end event
endJSON, _ := json.Marshal(map[string]any{
"event": map[string]any{
"end": map[string]any{
"exitCode": exitCode,
"exited": true,
},
},
})
writeConnectFrame(&body, endJSON)
// End-of-stream frame (connectEndStreamFlag = 0x02, empty payload).
var eosHeader [5]byte
eosHeader[0] = 0x02 // end-stream flag
body.Write(eosHeader[:])
w.Header().Set("Content-Type", "application/connect+json")
w.Header().Set("Trailer", "grpc-status")
w.Header().Set("Trailer", "grpc-message")
w.WriteHeader(http.StatusOK)
_, _ = w.Write(body.Bytes())
w.Header().Set("grpc-status", "0")
w.Header().Set("grpc-message", "")
}
// base64Encode returns base64-encoded string, or empty string for empty input.
func base64Encode(s string) string {
if s == "" {
return ""
}
return base64.StdEncoding.EncodeToString([]byte(s))
}
// writeConnectFrame appends a connect-framed message to buf:
// [1 byte flags=0x00][4 bytes big-endian length][payload]
func writeConnectFrame(buf *bytes.Buffer, payload []byte) {
var header [5]byte
binary.BigEndian.PutUint32(header[1:5], uint32(len(payload)))
buf.Write(header[:])
buf.Write(payload)
}
func extractSandboxID(urlPath string, suffix string) string {
path := urlPath
if suffix != "" {
path = strings.TrimSuffix(path, suffix)
}
parts := strings.Split(strings.Trim(path, "/"), "/")
if len(parts) >= 2 && parts[0] == "sandboxes" {
return parts[1]
}
return ""
}
func extractSandboxIDFromHost(host string, domain string) string {
// Strip port if present (Go HTTP request Host may include port).
if h, _, err := net.SplitHostPort(host); err == nil {
host = h
}
// Host format is "{port}-{sandboxID}.{domain}". Strip the port
// prefix (everything before the first "-").
idx := strings.Index(host, "-")
if idx < 0 {
return ""
}
host = host[idx+1:]
// Strip the domain suffix.
host = strings.TrimSuffix(host, "."+domain)
return host
}
func isEnvdRequest(host, domain string) bool {
if h, _, err := net.SplitHostPort(host); err == nil {
host = h
}
return strings.Contains(host, "-") && strings.HasSuffix(host, "."+domain)
}
func containsPath(urlPath, needle string) bool {
return strings.Contains(urlPath, needle)
}
// testConfig builds a *Config wired against the mock server. Both the control
// plane (CubeAPIURL) and the data plane (CubeProxyURL) are pointed at the
// mock so every SDK-initiated request goes through the mock's net/http server.
func testConfig(t *testing.T, mock *cubeMockServer) *Config {
t.Helper()
return &Config{
Type: SandboxTypeCube,
AllowPrivateEndpoints: true,
CubeAPIURL: mock.URL(),
CubeAPIKey: "",
CubeProxyURL: mock.URL(),
CubeTemplate: "template-a",
CubeSandboxDomain: "cube.app",
CubeSandboxTTL: 30 * time.Minute,
CubeHTTPTimeout: 30 * time.Second,
DefaultTimeout: 60 * time.Second,
}
}
File diff suppressed because it is too large. Load diff
+738
View File
@@ -0,0 +1,738 @@
package sandbox
import (
"context"
"errors"
"net/http"
"testing"
"time"
cubesandbox "github.com/tencentcloud/CubeSandbox/sdk/go"
"academy/internal/types"
"github.com/stretchr/testify/require"
)
// newTestCubeRemoteClient wires a real CubeRemoteClient at the cubeMockServer.
// Tests exercise the adapter through its public RemoteSandboxClient surface
// only — no intermediate backend interfaces exist below CubeRemoteClient.
func newTestCubeRemoteClient(t *testing.T, mock *cubeMockServer) *CubeRemoteClient {
t.Helper()
client, err := NewCubeRemoteClient(testConfig(t, mock))
require.NoError(t, err)
return client
}
func TestCubeRemoteClientProviderAndCapabilities(t *testing.T) {
client := newTestCubeRemoteClient(t, newCubeMockServer(t))
require.Equal(t, SandboxTypeCube, client.Provider())
require.Equal(t, RemoteSandboxCapabilities{
SupportsReconnect: true,
SupportsMetadata: true,
SupportsListSandboxes: true,
SupportsPauseResume: true,
SupportsTimeoutRefresh: true,
SupportsFilesystemEnumeration: true,
SupportsSnapshots: true,
SupportsTerminals: true,
SupportsDesktop: true,
}, client.Capabilities())
}
func TestCubeCommandTimeoutIsIndependentOfHTTPTimeout(t *testing.T) {
mock := newCubeMockServer(t)
mock.executor = func(string, string, []string) (string, string, int) {
time.Sleep(300 * time.Millisecond)
return "finished", "", 0
}
cfg := testConfig(t, mock)
cfg.CubeHTTPTimeout = 100 * time.Millisecond
client, err := NewCubeRemoteClient(cfg)
require.NoError(t, err)
handle, err := client.Create(context.Background(), RemoteCreateRequest{TemplateID: "template-a"})
require.NoError(t, err)
result, err := client.Exec(context.Background(), handle, RemoteExecRequest{
Command: "slow command", Shell: true, Timeout: 2 * time.Second,
})
require.NoError(t, err)
require.Equal(t, "finished", result.Stdout)
require.False(t, result.Killed)
}
func TestCubeRemoteClientCreateSnapshot(t *testing.T) {
mock := newCubeMockServer(t)
client := newTestCubeRemoteClient(t, mock)
ctx := context.Background()
handle, err := client.Create(ctx, RemoteCreateRequest{TemplateID: "template-a"})
require.NoError(t, err)
ref, err := client.CreateSnapshot(ctx, handle.ID(), "academy-sk-cfg1-g1")
require.NoError(t, err)
require.Equal(t, "snap-1", ref.ID)
require.Equal(t, []string{"academy-sk-cfg1-g1"}, ref.Names)
mock.mu.Lock()
body := mock.snapshotCreateBody
mock.mu.Unlock()
require.Equal(t, "academy-sk-cfg1-g1", body["name"])
}
func TestCubeRemoteClientCreateSnapshotRejectsEmptySandboxID(t *testing.T) {
client := newTestCubeRemoteClient(t, newCubeMockServer(t))
_, err := client.CreateSnapshot(context.Background(), " ", "n")
require.Error(t, err)
require.True(t, IsRemoteInvalidRequest(err))
}
func TestCubeRemoteClientDeleteSnapshotTreatsMissingAsSuccess(t *testing.T) {
client := newTestCubeRemoteClient(t, newCubeMockServer(t))
err := client.DeleteSnapshot(context.Background(), "snap-missing")
require.NoError(t, err, "a missing snapshot must not fail the delete path")
}
func TestCubeRemoteClientDeleteSnapshotRejectsEmptySnapshotID(t *testing.T) {
client := newTestCubeRemoteClient(t, newCubeMockServer(t))
err := client.DeleteSnapshot(context.Background(), " ")
require.Error(t, err)
require.True(t, IsRemoteInvalidRequest(err))
}
func TestCubeRemoteClientDeleteSnapshotReturnsUnexpectedErrors(t *testing.T) {
mock := newCubeMockServer(t)
mock.snapshotDeleteFailWith = http.StatusInternalServerError
client := newTestCubeRemoteClient(t, mock)
err := client.DeleteSnapshot(context.Background(), "snap-any")
require.Error(t, err)
require.False(t, IsRemoteNotFound(err))
}
func TestCubeRemoteClientListSnapshotsRejectsStuckPagination(t *testing.T) {
mock := newCubeMockServer(t)
mock.snapshotStuckPagination = true
client := newTestCubeRemoteClient(t, mock)
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
_, err := client.ListSnapshots(ctx, "")
require.Error(t, err)
require.True(t, IsRemoteInvalidRequest(err))
}
func TestCubeRemoteClientListSnapshotsPagesAllResults(t *testing.T) {
mock := newCubeMockServer(t)
mock.snapshotPageSize = 1
client := newTestCubeRemoteClient(t, mock)
ctx := context.Background()
first, err := client.Create(ctx, RemoteCreateRequest{TemplateID: "template-a"})
require.NoError(t, err)
second, err := client.Create(ctx, RemoteCreateRequest{TemplateID: "template-a"})
require.NoError(t, err)
firstRef, err := client.CreateSnapshot(ctx, first.ID(), "academy-sk-cfg1-g1")
require.NoError(t, err)
secondRef, err := client.CreateSnapshot(ctx, first.ID(), "academy-sk-cfg2-g1")
require.NoError(t, err)
_, err = client.CreateSnapshot(ctx, second.ID(), "other")
require.NoError(t, err)
list, err := client.ListSnapshots(ctx, first.ID())
require.NoError(t, err)
require.Equal(t, []RemoteSnapshotRef{firstRef, secondRef}, list)
}
func TestCubeRemoteClientCreateWritesLifecyclePayload(t *testing.T) {
mock := newCubeMockServer(t)
client := newTestCubeRemoteClient(t, mock)
handle, err := client.Create(context.Background(), RemoteCreateRequest{
TemplateID: "template-a",
Timeout: RemoteTimeoutPolicy{
Mode: RemoteTimeoutExplicit,
Value: 15 * time.Minute,
Action: RemoteOnTimeoutPause,
AutoResume: true,
},
Metadata: map[string]string{"owner": "session-a"},
EnvVars: map[string]string{"LANG": "C.UTF-8"},
})
require.NoError(t, err)
require.NotEmpty(t, handle.ID())
require.Equal(t, SandboxTypeCube, handle.Provider())
require.Equal(t, map[string]string{"owner": "session-a"}, handle.Metadata())
mock.mu.Lock()
body := mock.createBody
mock.mu.Unlock()
require.Equal(t, "template-a", body["templateID"])
require.Equal(t, float64(900), body["timeout"])
require.Equal(t, map[string]any{"owner": "session-a"}, body["metadata"])
require.Equal(t, map[string]any{"LANG": "C.UTF-8"}, body["envVars"])
require.Equal(t, map[string]any{
"onTimeout": "pause",
"autoResume": true,
}, body["lifecycle"])
}
// Counterpart to the E2B test of the same name. resolveNetworkPolicy
// materialises DenyEgressByDefault into an explicit deny-all entry, and both
// adapters must put it on the wire — otherwise the two providers drift and only
// one of them enforces what the admin ticked.
func TestCubeRemoteClientCreateSendsDenyAllForStoredDenyByDefault(t *testing.T) {
tenantCfg := completeCubeTenantConfig()
tenantCfg.Network = &types.SandboxNetworkPolicy{
DenyEgressByDefault: true,
AllowOut: []string{"*.example.com"},
}
effective, err := ResolveEffectiveConfig(tenantCfg, DefaultConfig())
require.NoError(t, err)
mock := newCubeMockServer(t)
client := newTestCubeRemoteClient(t, mock)
_, err = client.Create(context.Background(), RemoteCreateRequest{
TemplateID: "template-a",
Network: effective.Network,
})
require.NoError(t, err)
mock.mu.Lock()
body := mock.createBody
mock.mu.Unlock()
require.Equal(t, false, body["allowInternetAccess"])
networkPayload := body["network"].(map[string]any)
require.Equal(t, []any{"*.example.com"}, networkPayload["allowOut"])
require.Equal(t, []any{"0.0.0.0/0"}, networkPayload["denyOut"])
}
func TestCubeRemoteClientCreateForwardsNetworkPolicy(t *testing.T) {
mock := newCubeMockServer(t)
client := newTestCubeRemoteClient(t, mock)
deny := false
privateSandbox := false
_, err := client.Create(context.Background(), RemoteCreateRequest{
TemplateID: "template-a",
Network: RemoteNetworkPolicy{
AllowInternetAccess: &deny,
AllowPublicTraffic: &privateSandbox,
AllowOut: []string{"*.example.com"},
DenyOut: []string{"0.0.0.0/0"},
CubeRules: []RemoteCubeEgressRule{{
Name: "allow-payment-api",
Scheme: "https",
SNI: "pay.example.com",
Host: "pay.example.com",
Methods: []string{"POST"},
Path: "/api/payments/*",
Allow: true,
Audit: "full",
Inject: []RemoteHeaderInject{{
Header: "Authorization",
Secret: "tok",
Format: "Bearer ${SECRET}",
}},
}, {
Name: "deny-uploads",
SNI: "uploads.example.com",
Allow: false,
}},
},
})
require.NoError(t, err)
mock.mu.Lock()
body := mock.createBody
mock.mu.Unlock()
require.Equal(t, false, body["allowInternetAccess"])
networkPayload, ok := body["network"].(map[string]any)
require.True(t, ok, "network payload missing: %#v", body["network"])
require.Equal(t, false, networkPayload["allowPublicTraffic"])
require.Equal(t, []any{"*.example.com"}, networkPayload["allowOut"])
require.Equal(t, []any{"0.0.0.0/0"}, networkPayload["denyOut"])
rules, ok := networkPayload["rules"].([]any)
require.True(t, ok, "rules payload missing: %#v", networkPayload["rules"])
require.Len(t, rules, 2)
first := rules[0].(map[string]any)
require.Equal(t, "allow-payment-api", first["name"])
match := first["match"].(map[string]any)
require.Equal(t, "https", match["scheme"])
require.Equal(t, "pay.example.com", match["sni"])
require.Equal(t, "pay.example.com", match["host"])
require.Equal(t, []any{"POST"}, match["method"])
require.Equal(t, "/api/payments/*", match["path"])
action := first["action"].(map[string]any)
require.Equal(t, true, action["allow"])
require.Equal(t, "full", action["audit"])
inject := action["inject"].([]any)[0].(map[string]any)
require.Equal(t, "Authorization", inject["header"])
require.Equal(t, "tok", inject["secret"])
require.Equal(t, "Bearer ${SECRET}", inject["format"])
// A deny rule must still be sent: it is what gets the target into
// CubeEgress so the proxy can answer 403 instead of the network dropping
// the packet.
second := rules[1].(map[string]any)
require.Equal(t, false, second["action"].(map[string]any)["allow"])
}
// Academy's default deliberately differs from Cube's: an unspecified policy
// closes inbound access, because "anyone who knows the sandbox ID" used to be
// the only barrier in front of the sandbox URL. Egress stays open so skill
// installs keep working.
func TestCubeRemoteClientCreateDefaultsInboundClosed(t *testing.T) {
mock := newCubeMockServer(t)
client := newTestCubeRemoteClient(t, mock)
_, err := client.Create(context.Background(), RemoteCreateRequest{TemplateID: "template-a"})
require.NoError(t, err)
mock.mu.Lock()
body := mock.createBody
mock.mu.Unlock()
require.Equal(t, true, body["allowInternetAccess"])
networkPayload := body["network"].(map[string]any)
require.Equal(t, false, networkPayload["allowPublicTraffic"])
require.NotContains(t, networkPayload, "rules")
}
func TestCubeRemoteHandleExposesTrafficAccessToken(t *testing.T) {
mock := newCubeMockServer(t)
mock.trafficAccessToken = "traffic-token"
client := newTestCubeRemoteClient(t, mock)
handle, err := client.Create(context.Background(), RemoteCreateRequest{TemplateID: "template-a"})
require.NoError(t, err)
require.Equal(t, "traffic-token", InboundTokenOf(handle))
require.Empty(t, InboundTokenOf(
&contractHandle{id: "e2b-1", provider: SandboxTypeE2B},
))
}
// The provider issues the traffic token once, at create time. Everything that
// re-attaches later — auto-resume, a Academy restart, an artifact download —
// has to put it back or every data-plane call answers 403.
func TestCubeRemoteClientConnectRestoresTrafficAccessToken(t *testing.T) {
mock := newCubeMockServer(t)
// Deliberately empty: Cube does not repeat the token on connect.
mock.trafficAccessToken = ""
client := newTestCubeRemoteClient(t, mock)
created, err := client.Create(context.Background(), RemoteCreateRequest{
TemplateID: "template-a",
})
require.NoError(t, err)
handle, err := client.Connect(context.Background(), RemoteConnectRequest{
SandboxID: created.ID(),
TrafficAccessToken: "recovered-token",
})
require.NoError(t, err)
carrier, ok := handle.(RemoteInboundTokenCarrier)
require.True(t, ok)
require.Equal(t, "recovered-token", carrier.TrafficAccessToken())
}
// A provider that does return one wins: it is fresher than our copy.
func TestCubeRemoteClientConnectKeepsProviderToken(t *testing.T) {
mock := newCubeMockServer(t)
client := newTestCubeRemoteClient(t, mock)
created, err := client.Create(context.Background(), RemoteCreateRequest{
TemplateID: "template-a",
})
require.NoError(t, err)
mock.connectTrafficToken = "provider-token"
handle, err := client.Connect(context.Background(), RemoteConnectRequest{
SandboxID: created.ID(),
TrafficAccessToken: "recovered-token",
})
require.NoError(t, err)
require.Equal(t, "provider-token",
handle.(RemoteInboundTokenCarrier).TrafficAccessToken())
}
func TestCubeRemoteClientCreatePreservesTimeoutModes(t *testing.T) {
t.Run("server default omits timeout", func(t *testing.T) {
mock := newCubeMockServer(t)
client := newTestCubeRemoteClient(t, mock)
_, err := client.Create(context.Background(), RemoteCreateRequest{
TemplateID: "template-a",
Timeout: RemoteTimeoutPolicy{
Mode: RemoteTimeoutServerDefault,
Action: RemoteOnTimeoutKill,
},
})
require.NoError(t, err)
mock.mu.Lock()
body := mock.createBody
mock.mu.Unlock()
_, hasTimeout := body["timeout"]
require.False(t, hasTimeout)
})
t.Run("negative means never", func(t *testing.T) {
mock := newCubeMockServer(t)
client := newTestCubeRemoteClient(t, mock)
_, err := client.Create(context.Background(), RemoteCreateRequest{
TemplateID: "template-a",
Timeout: RemoteTimeoutPolicy{
Mode: RemoteTimeoutExplicit,
Value: -time.Hour,
Action: RemoteOnTimeoutKill,
},
})
require.NoError(t, err)
mock.mu.Lock()
body := mock.createBody
mock.mu.Unlock()
// Cube's three-value semantics send -1 verbatim as "never timeout".
require.Equal(t, float64(-1), body["timeout"])
})
t.Run("auto resume requires pause", func(t *testing.T) {
client := newTestCubeRemoteClient(t, newCubeMockServer(t))
_, err := client.Create(context.Background(), RemoteCreateRequest{
TemplateID: "template-a",
Timeout: RemoteTimeoutPolicy{
Mode: RemoteTimeoutExplicit,
Value: time.Minute,
Action: RemoteOnTimeoutKill,
AutoResume: true,
},
})
require.True(t, IsRemoteInvalidRequest(err))
})
t.Run("missing template rejected before wire", func(t *testing.T) {
mock := newCubeMockServer(t)
client := newTestCubeRemoteClient(t, mock)
_, err := client.Create(context.Background(), RemoteCreateRequest{})
require.True(t, IsRemoteInvalidRequest(err))
require.Zero(t, mock.createCount.Load())
})
}
func TestCubeRemoteClientLifecycleRoundTrip(t *testing.T) {
mock := newCubeMockServer(t)
mock.trafficAccessToken = "create-only-traffic-token"
client := newTestCubeRemoteClient(t, mock)
ctx := context.Background()
handle, err := client.Create(ctx, RemoteCreateRequest{
TemplateID: "template-a",
Timeout: RemoteTimeoutPolicy{
Mode: RemoteTimeoutExplicit,
Value: time.Minute,
Action: RemoteOnTimeoutKill,
},
})
require.NoError(t, err)
summary, err := client.Get(ctx, handle.ID())
require.NoError(t, err)
require.Equal(t, handle.ID(), summary.ID)
require.Equal(t, RemoteStateRunning, summary.State)
list, err := client.List(ctx, RemoteListFilter{
States: []RemoteSandboxState{RemoteStateRunning},
})
require.NoError(t, err)
require.Len(t, list, 1)
require.Equal(t, handle.ID(), list[0].ID)
reconnected, err := client.Connect(ctx, RemoteConnectRequest{SandboxID: handle.ID()})
require.NoError(t, err)
require.Equal(t, handle.ID(), reconnected.ID())
require.Empty(t, InboundTokenOf(reconnected),
"Cube connect responses do not repeat the create-time traffic token")
require.NoError(t, client.Delete(ctx, handle.ID()))
require.Equal(t, int32(1), mock.killCount.Load())
mock.mu.Lock()
_, stillAlive := mock.sandboxes[handle.ID()]
mock.mu.Unlock()
require.False(t, stillAlive)
}
func TestCubeRemoteClientExecArgvAndShell(t *testing.T) {
mock := newCubeMockServer(t)
client := newTestCubeRemoteClient(t, mock)
ctx := context.Background()
var (
gotCmd string
gotArgs []string
)
mock.SetExecutor(func(_, cmd string, args []string) (string, string, int) {
gotCmd = cmd
gotArgs = args
return "ok\n", "", 0
})
handle, err := client.Create(ctx, RemoteCreateRequest{
TemplateID: "template-a",
Timeout: RemoteTimeoutPolicy{
Mode: RemoteTimeoutServerDefault,
Action: RemoteOnTimeoutKill,
},
})
require.NoError(t, err)
// Argv → cubeClient assembles /bin/bash -l -c "<shell-quoted argv>". The
// mock records the wrapper argv, which lets us assert both the wrapper
// shape and that the caller's arguments are shell-quoted (not lost).
result, err := client.Exec(ctx, handle, RemoteExecRequest{
Command: "python3",
Args: []string{"script.py", "argument with spaces"},
})
require.NoError(t, err)
require.Equal(t, 0, result.ExitCode)
require.Contains(t, result.Stdout, "ok")
require.Equal(t, "/bin/bash", gotCmd)
require.Len(t, gotArgs, 3)
require.Equal(t, "-l", gotArgs[0])
require.Equal(t, "-c", gotArgs[1])
require.Contains(t, gotArgs[2], "python3")
require.Contains(t, gotArgs[2], "'argument with spaces'")
// Shell → the caller's raw expression is passed through verbatim.
gotCmd, gotArgs = "", nil
mock.SetExecutor(func(_, cmd string, args []string) (string, string, int) {
gotCmd = cmd
gotArgs = args
return "shell\n", "", 0
})
_, err = client.Exec(ctx, handle, RemoteExecRequest{
Command: "printf '%s' ok | cat",
Shell: true,
})
require.NoError(t, err)
require.Equal(t, "/bin/bash", gotCmd)
require.Equal(t, "printf '%s' ok | cat", gotArgs[2])
// Shell + argv is mutually exclusive.
_, err = client.Exec(ctx, handle, RemoteExecRequest{
Command: "echo",
Args: []string{"unsafe ambiguity"},
Shell: true,
})
require.True(t, IsRemoteInvalidRequest(err))
}
func TestCubeRemoteClientExecForwardsBufferedOutput(t *testing.T) {
mock := newCubeMockServer(t)
mock.SetExecutor(func(string, string, []string) (string, string, int) {
return "out-line\n", "err-line\n", 0
})
client := newTestCubeRemoteClient(t, mock)
ctx := context.Background()
handle, err := client.Create(ctx, RemoteCreateRequest{TemplateID: "template-a"})
require.NoError(t, err)
var got []string
result, err := client.Exec(ctx, handle, RemoteExecRequest{
Command: "printf '%s' ok",
Shell: true,
OnOutput: func(stream string, chunk []byte) {
got = append(got, stream+":"+string(chunk))
},
})
require.NoError(t, err)
require.Equal(t, "out-line\n", result.Stdout)
require.Equal(t, "err-line\n", result.Stderr)
require.Equal(t, []string{"stdout:out-line\n", "stderr:err-line\n"}, got)
}
func TestCubeRemoteClientExecTimeoutIsKilled(t *testing.T) {
mock := newCubeMockServer(t)
// A slow executor lets the outer request timeout fire before the mock
// returns a stream. cubeClient's RunCommand cancellation path then
// synthesises Killed=true, ExitCode=-1.
mock.SetExecutor(func(string, string, []string) (string, string, int) {
time.Sleep(200 * time.Millisecond)
return "", "", 0
})
client := newTestCubeRemoteClient(t, mock)
ctx := context.Background()
handle, err := client.Create(ctx, RemoteCreateRequest{
TemplateID: "template-a",
})
require.NoError(t, err)
result, err := client.Exec(ctx, handle, RemoteExecRequest{
Command: "sleep",
Args: []string{"10"},
Timeout: 20 * time.Millisecond,
})
require.NoError(t, err)
require.NotNil(t, result)
require.True(t, result.Killed)
require.Equal(t, -1, result.ExitCode)
}
func TestCubeRemoteClientFileWriteRoundTrip(t *testing.T) {
mock := newCubeMockServer(t)
client := newTestCubeRemoteClient(t, mock)
ctx := context.Background()
handle, err := client.Create(ctx, RemoteCreateRequest{TemplateID: "template-a"})
require.NoError(t, err)
require.NoError(t, client.WriteFile(ctx, handle, "/workspace/hello.txt", []byte("hi")))
require.NoError(t, client.MakeDir(ctx, handle, "/workspace/nested"))
mock.mu.Lock()
files := mock.files[handle.ID()]
mock.mu.Unlock()
require.Equal(t, "hi", string(files["/workspace/hello.txt"]))
}
func TestCubeRemoteClientRejectsForeignHandle(t *testing.T) {
client := newTestCubeRemoteClient(t, newCubeMockServer(t))
_, err := client.ReadFile(
context.Background(),
&contractHandle{id: "e2b-1", provider: SandboxTypeE2B},
"/workspace/file",
)
require.True(t, IsRemoteInvalidRequest(err))
}
func TestCubeRemoteClientListFilters(t *testing.T) {
mock := newCubeMockServer(t)
client := newTestCubeRemoteClient(t, mock)
ctx := context.Background()
handle, err := client.Create(ctx, RemoteCreateRequest{
TemplateID: "template-a",
Metadata: map[string]string{"owner": "keep"},
})
require.NoError(t, err)
_, err = client.Create(ctx, RemoteCreateRequest{
TemplateID: "template-a",
Metadata: map[string]string{"owner": "other"},
})
require.NoError(t, err)
list, err := client.List(ctx, RemoteListFilter{
Metadata: map[string]string{"owner": "keep"},
})
require.NoError(t, err)
require.Len(t, list, 1)
require.Equal(t, handle.ID(), list[0].ID)
}
func TestNormalizeCubeState(t *testing.T) {
tests := map[string]RemoteSandboxState{
"running": RemoteStateRunning,
"paused": RemoteStatePaused,
"pausing": RemoteStateTransitioning,
"resuming": RemoteStateTransitioning,
"pending": RemoteStateTransitioning,
"killing": RemoteStateTerminal,
"killed": RemoteStateTerminal,
"terminated": RemoteStateTerminal,
"deleted": RemoteStateTerminal,
"failed": RemoteStateTerminal,
"": RemoteStateUnknown,
"weird": RemoteStateUnknown,
}
for raw, want := range tests {
require.Equalf(t, want, normalizeCubeState(raw), "state %q", raw)
}
}
func TestNormalizeCubeError(t *testing.T) {
tests := []struct {
name string
op string
err error
kind RemoteErrorKind
}{
{"sandbox not found", "Get", cubesandbox.ErrSandboxNotFound, RemoteErrorKindNotFound},
{"template not found", "Create", cubesandbox.ErrTemplateNotFound, RemoteErrorKindInvalidRequest},
{"authentication", "Health", cubesandbox.ErrAuthentication, RemoteErrorKindAuthentication},
{"path not found", "Stat", &cubesandbox.NotFoundError{Path: "/x"}, RemoteErrorKindNotFound},
{"list missing session dir", "ListDir", errors.New(
"failed to list /workspace/sessions/f2e82fcb-abf8-4677-9567-5e20d6cbcb1f/input: " +
"path not found: lstat /workspace/sessions/f2e82fcb-abf8-4677-9567-5e20d6cbcb1f: " +
"no such file or directory"), RemoteErrorKindNotFound},
{"gone", "Get", &cubesandbox.APIError{StatusCode: http.StatusGone}, RemoteErrorKindTerminal},
{"conflict", "Connect", &cubesandbox.APIError{StatusCode: http.StatusConflict}, RemoteErrorKindConflict},
{"rate limited", "Create", &cubesandbox.APIError{StatusCode: http.StatusTooManyRequests}, RemoteErrorKindCapacity},
{"bad gateway", "List", &cubesandbox.APIError{StatusCode: http.StatusBadGateway}, RemoteErrorKindUnavailable},
{"deadline", "Exec", context.DeadlineExceeded, RemoteErrorKindTimeout},
{"unknown", "List", errors.New("unknown"), RemoteErrorKindInternal},
{"delete snapshot in use", "DeleteSnapshot", &cubesandbox.APIError{
StatusCode: http.StatusBadRequest,
Message: "cannot delete template x because there are paused sandboxes using it",
}, RemoteErrorKindConflict},
{"delete snapshot runtime refs", "DeleteSnapshot", &cubesandbox.APIError{
StatusCode: http.StatusInternalServerError,
Message: "CubeMaster returned error code 130409: template attempt is already in progress: " +
"snapshot snap-x still has 2 active runtime ref(s): a@host, b@host",
}, RemoteErrorKindConflict},
{"delete snapshot bad id", "DeleteSnapshot", &cubesandbox.APIError{
StatusCode: http.StatusBadRequest,
Message: "invalid snapshot id",
}, RemoteErrorKindInvalidRequest},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
err := normalizeCubeError(tt.op, tt.err)
var remoteErr *RemoteError
require.ErrorAs(t, err, &remoteErr)
require.Equal(t, tt.kind, remoteErr.Kind)
require.Equal(t, SandboxTypeCube, remoteErr.Provider)
require.ErrorIs(t, err, tt.err)
})
}
}
func TestCubeDesktopTemplateSpecDoesNotNatWebsockify(t *testing.T) {
spec := cubeDesktopTemplateSpec(nil)
require.Equal(t, DefaultCubeDesktopTemplateImage, spec["image"])
require.Equal(t, DesktopTemplateName, spec["name"])
// envd stays in exposedPorts so the template probe can reach :49983.
// 6080 must not: Cube NATs that list onto the host NIC and bypasses
// CubeProxy. The desktop relay dials 6080 through CubeProxy instead.
require.Equal(t, []uint16{CubeEnvdPort}, spec["exposedPorts"])
require.Equal(t, uint16(CubeEnvdPort), spec["probePort"])
require.Equal(t, CubeEnvdHealthPath, spec["probePath"])
// 1G (the standard value) is too small once XFCE is installed.
require.Equal(t, "8G", spec["writableLayerSize"])
require.Equal(t, true, spec["allowInternetAccess"])
require.Equal(t, []string{"/usr/bin/envd"}, spec["command"])
require.Equal(t, []string{"-port", "49983", "-isnotfc"}, spec["args"])
}
func TestCubeStandardTemplateSpecStillExposesOnlyEnvd(t *testing.T) {
// Host ports are a finite resource (CubeVS allocates 20000-29999). Neither
// the CLI nor the desktop template may NAT extra guest ports onto the host.
spec := cubeStandardTemplateSpec(nil)
require.Equal(t, []uint16{CubeEnvdPort}, spec["exposedPorts"])
}
func TestDesktopReadyCmdDoesNotUseSS(t *testing.T) {
// e2b.WaitForPort generates `ss -tln`, and iproute2 is not in the image:
// ss exits 127, the loop never terminates, and the template build hangs
// instead of failing. Keep the python3 probe.
require.NotContains(t, desktopReadyCmd, "ss ")
require.Contains(t, desktopReadyCmd, "python3")
require.Contains(t, desktopReadyCmd, "6080")
}
@@ -0,0 +1,604 @@
package sandbox
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"sync/atomic"
"testing"
"time"
"github.com/stretchr/testify/require"
)
// newCubeTemplateClient points a CubeRemoteClient at a bare catalog-API stub.
// The full cubeMockServer models sandboxes rather than the template catalog.
func newCubeTemplateClient(t *testing.T, handler http.HandlerFunc) *CubeRemoteClient {
t.Helper()
server := httptest.NewServer(handler)
t.Cleanup(server.Close)
client, err := NewCubeRemoteClient(&Config{
Type: SandboxTypeCube,
AllowPrivateEndpoints: true,
CubeAPIURL: server.URL,
CubeProxyURL: server.URL,
CubeSandboxDomain: "cube.app",
CubeHTTPTimeout: 5 * time.Second,
})
require.NoError(t, err)
return client
}
// Cube omits the name of a template that carries no alias, which used to make
// our own template unrecognisable and every catalog refresh build another one.
func TestCubeRemoteClientListTemplatesRecognisesStandardByImage(t *testing.T) {
client := newCubeTemplateClient(t, func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/snapshots" {
writeJSON(w, http.StatusOK, []map[string]any{})
return
}
require.Equal(t, "/templates", r.URL.Path)
writeJSON(w, http.StatusOK, []map[string]any{
{
"templateID": "tpl-nameless",
"status": "READY",
"imageInfo": DefaultDockerImage,
},
{
"templateID": "tpl-other",
"status": "READY",
"imageInfo": "python:3.11",
},
})
})
templates, err := client.ListTemplates(context.Background())
require.NoError(t, err)
require.Len(t, templates, 2)
require.True(t, templates[0].Standard)
require.Equal(t, StandardTemplateName, templates[0].Name,
"a recognised template must be labelled, not shown as a bare ID")
require.False(t, templates[1].Standard)
require.Equal(t, "tpl-other", templates[1].Name)
}
func TestCubeRemoteClientListTemplatesRecognisesDesktopByImage(t *testing.T) {
client := newCubeTemplateClient(t, func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/snapshots" {
writeJSON(w, http.StatusOK, []map[string]any{})
return
}
require.Equal(t, "/templates", r.URL.Path)
writeJSON(w, http.StatusOK, []map[string]any{
{
"templateID": "tpl-cli",
"status": "READY",
"imageInfo": DefaultCubeTemplateImage,
},
{
"templateID": "tpl-desktop",
"status": "READY",
"imageInfo": DefaultCubeDesktopTemplateImage,
},
})
})
templates, err := client.ListTemplates(context.Background())
require.NoError(t, err)
require.Len(t, templates, 2)
require.True(t, templates[0].Standard)
require.False(t, templates[0].Desktop)
require.Equal(t, StandardTemplateName, templates[0].Name)
require.True(t, templates[1].Desktop)
require.False(t, templates[1].Standard)
require.Equal(t, DesktopTemplateName, templates[1].Name)
}
func TestCubeRemoteClientEnsureDesktopTemplateBuildsWhenAbsent(t *testing.T) {
var payload map[string]any
client := newCubeTemplateClient(t, func(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case http.MethodGet:
writeJSON(w, http.StatusOK, []map[string]any{{
"templateID": "tpl-cli",
"status": "READY",
"imageInfo": DefaultCubeTemplateImage,
"name": StandardTemplateName,
}})
case http.MethodPost:
require.NoError(t, json.NewDecoder(r.Body).Decode(&payload))
writeJSON(w, http.StatusAccepted, map[string]any{
"templateID": "tpl-desk",
"status": "PENDING",
})
}
})
template, err := client.EnsureDesktopTemplate(context.Background())
require.NoError(t, err)
require.Equal(t, "tpl-desk", template.ID)
require.True(t, template.Desktop)
require.False(t, template.Standard)
require.Equal(t, DefaultCubeDesktopTemplateImage, payload["image"])
require.Equal(t, DesktopTemplateName, payload["name"])
}
func TestCubeRemoteClientListTemplatesMapsCatalogMetadata(t *testing.T) {
allowInternet := true
client := newCubeTemplateClient(t, cubeCatalogHandler(
[]map[string]any{{
"templateID": "tpl-full",
"name": "custom",
"status": "READY",
"version": "v2",
"imageInfo": "python:3.11",
"createdAt": "2026-08-01T12:00:00Z",
"instanceType": "small",
"networkType": "tap",
"allowInternetAccess": allowInternet,
}},
nil,
))
templates, err := client.ListTemplates(context.Background())
require.NoError(t, err)
require.Len(t, templates, 1)
require.Equal(t, "tpl-full", templates[0].ID)
require.Equal(t, "custom", templates[0].Name)
require.Equal(t, "v2", templates[0].Version)
require.Equal(t, "python:3.11", templates[0].Image)
require.Equal(t, "2026-08-01T12:00:00Z", templates[0].CreatedAt)
require.Equal(t, "small", templates[0].InstanceType)
require.Equal(t, "tap", templates[0].NetworkType)
require.NotNil(t, templates[0].AllowInternetAccess)
require.True(t, *templates[0].AllowInternetAccess)
}
func TestCubeRemoteClientListTemplatesSurfacesLastError(t *testing.T) {
client := newCubeTemplateClient(t, cubeCatalogHandler(
[]map[string]any{{
"templateID": "tpl-broken",
"status": "FAILED",
"imageInfo": DefaultDockerImage,
"lastError": "pull access denied for wechatopenai/weknora-sandbox",
}},
nil,
))
templates, err := client.ListTemplates(context.Background())
require.NoError(t, err)
require.Len(t, templates, 1)
require.Equal(t, "pull access denied for wechatopenai/weknora-sandbox", templates[0].Error)
}
// Cube stores snapshots in the template store. The settings step is for
// picking a base template, so snap- IDs must not appear even if GET
// /snapshots is empty or missing.
func TestCubeRemoteClientListTemplatesHidesSnapPrefixedIDs(t *testing.T) {
client := newCubeTemplateClient(t, cubeCatalogHandler(
[]map[string]any{
{
"templateID": "tpl-academy",
"name": "academy",
"status": "READY",
},
{
"templateID": "snap-1546901f7e5e40bdb8794c78",
"aliases": []string{"academy-sk-c838ac20-g2"},
"status": "READY",
},
{
"templateID": "SNAP-uppercase",
"status": "READY",
},
},
nil,
))
templates, err := client.ListTemplates(context.Background())
require.NoError(t, err)
require.Len(t, templates, 1)
require.Equal(t, "tpl-academy", templates[0].ID)
}
// Snapshot IDs that do not use the snap- prefix still belong to GET
// /snapshots, and must not be offered as a base template.
func TestCubeRemoteClientListTemplatesHidesListedSnapshots(t *testing.T) {
client := newCubeTemplateClient(t, cubeCatalogHandler(
[]map[string]any{
{"templateID": "tpl-academy", "name": "academy", "status": "READY"},
{"templateID": "abc123unprefixed", "aliases": []string{"academy-sk-cfg-g1"}, "status": "READY"},
},
[]map[string]any{
{"snapshotID": "abc123unprefixed", "names": []string{"academy-sk-cfg-g1"}},
},
))
templates, err := client.ListTemplates(context.Background())
require.NoError(t, err)
require.Len(t, templates, 1)
require.Equal(t, "tpl-academy", templates[0].ID)
}
func TestCubeRemoteClientListTemplatesKeepsTemplatesWhenSnapshotListFails(t *testing.T) {
client := newCubeTemplateClient(t, func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/templates":
writeJSON(w, http.StatusOK, []map[string]any{
{"templateID": "tpl-academy", "status": "READY"},
{"templateID": "snap-orphan", "status": "READY"},
})
case "/snapshots":
http.Error(w, "unavailable", http.StatusInternalServerError)
default:
http.NotFound(w, r)
}
})
templates, err := client.ListTemplates(context.Background())
require.NoError(t, err)
require.Len(t, templates, 1)
require.Equal(t, "tpl-academy", templates[0].ID)
}
func TestCubeTemplateIsSnapshot(t *testing.T) {
listed := map[string]struct{}{"listed-id": {}}
require.True(t, cubeTemplateIsSnapshot("snap-1", nil))
require.True(t, cubeTemplateIsSnapshot("SNAP-1", nil))
require.True(t, cubeTemplateIsSnapshot("listed-id", listed))
require.False(t, cubeTemplateIsSnapshot("tpl-academy", listed))
require.False(t, cubeTemplateIsSnapshot("", listed))
}
func cubeCatalogHandler(templates, snapshots []map[string]any) http.HandlerFunc {
if templates == nil {
templates = []map[string]any{}
}
if snapshots == nil {
snapshots = []map[string]any{}
}
return func(w http.ResponseWriter, r *http.Request) {
switch {
case r.URL.Path == "/templates" && r.Method == http.MethodGet:
writeJSON(w, http.StatusOK, templates)
case r.URL.Path == "/snapshots" && r.Method == http.MethodGet:
writeJSON(w, http.StatusOK, snapshots)
default:
http.NotFound(w, r)
}
}
}
// The bug this guards: an unnamed Academy template was invisible to the
// idempotency check, so every visit to the template step queued another build.
func TestCubeRemoteClientEnsureStandardTemplateSkipsBuildForNamelessTemplate(t *testing.T) {
var builds atomic.Int32
client := newCubeTemplateClient(t, func(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodPost {
builds.Add(1)
}
writeJSON(w, http.StatusOK, []map[string]any{{
"templateID": "tpl-nameless",
"status": "READY",
"imageInfo": DefaultDockerImage,
}})
})
for range 3 {
template, err := client.EnsureStandardTemplate(context.Background())
require.NoError(t, err)
require.Equal(t, "tpl-nameless", template.ID)
}
require.Equal(t, int32(0), builds.Load())
}
// A failed template must be rebuilt in place. Building a fresh one would leave
// the failure behind and repeat on the next refresh.
func TestCubeRemoteClientEnsureStandardTemplateRebuildsFailedTemplate(t *testing.T) {
var created atomic.Int32
var rebuilt atomic.Int32
client := newCubeTemplateClient(t, func(w http.ResponseWriter, r *http.Request) {
switch {
case r.URL.Path == "/templates" && r.Method == http.MethodGet:
writeJSON(w, http.StatusOK, []map[string]any{{
"templateID": "tpl-failed",
"status": "FAILED",
"imageInfo": DefaultDockerImage,
"lastError": "no space left on device",
}})
case r.URL.Path == "/templates" && r.Method == http.MethodPost:
created.Add(1)
writeJSON(w, http.StatusAccepted, map[string]any{"templateID": "tpl-new"})
case r.URL.Path == "/templates/tpl-failed" && r.Method == http.MethodPost:
rebuilt.Add(1)
var payload map[string]any
require.NoError(t, json.NewDecoder(r.Body).Decode(&payload))
require.Equal(t, DefaultCubeTemplateImage, payload["image"])
require.Equal(t, StandardTemplateName, payload["name"])
require.Equal(t, true, payload["allowInternetAccess"])
writeJSON(w, http.StatusAccepted, map[string]any{
"templateID": "tpl-failed",
"status": "PENDING",
})
default:
http.NotFound(w, r)
}
})
template, err := client.EnsureStandardTemplate(context.Background())
require.NoError(t, err)
require.Equal(t, "tpl-failed", template.ID)
require.Equal(t, "building", template.Status)
require.Equal(t, int32(1), rebuilt.Load())
require.Equal(t, int32(0), created.Load(), "a rebuild must not add a template")
}
func TestCubeRemoteClientListTemplatesNormalizesRunningStatus(t *testing.T) {
client := newCubeTemplateClient(t, cubeCatalogHandler(
[]map[string]any{{
"templateID": "tpl-pulling",
"status": "RUNNING",
"imageInfo": DefaultCubeTemplateImage,
}},
nil,
))
templates, err := client.ListTemplates(context.Background())
require.NoError(t, err)
require.Len(t, templates, 1)
require.Equal(t, "building", templates[0].Status)
require.True(t, templates[0].Standard)
require.False(t, IsTemplateBuildFailed(templates[0].Status))
}
// CubeMaster may refuse redo (for example when the source image never
// landed). The failed card stays in the catalog so the operator can delete
// it by hand; Ensure must not 500 or spawn a replacement.
func TestCubeRemoteClientEnsureStandardTemplateKeepsFailedWhenRedoBlocked(t *testing.T) {
var created atomic.Int32
var deleted atomic.Int32
client := newCubeTemplateClient(t, func(w http.ResponseWriter, r *http.Request) {
switch {
case r.URL.Path == "/templates" && r.Method == http.MethodGet:
writeJSON(w, http.StatusOK, []map[string]any{{
"templateID": "tpl-failed",
"status": "FAILED",
"imageInfo": DefaultCubeTemplateImage,
"lastError": "TOOMANYREQUESTS: You have reached your unauthenticated pull rate limit",
}})
case r.URL.Path == "/snapshots" && r.Method == http.MethodGet:
writeJSON(w, http.StatusOK, []map[string]any{})
case r.URL.Path == "/templates/tpl-failed" && r.Method == http.MethodPost:
writeJSON(w, http.StatusBadRequest, map[string]any{
"code": 400,
"message": "CubeMaster returned error code 130400: " +
"template redo is not allowed before source image has been pulled successfully",
})
case r.URL.Path == "/templates/tpl-failed" && r.Method == http.MethodDelete:
deleted.Add(1)
w.WriteHeader(http.StatusNoContent)
case r.URL.Path == "/templates" && r.Method == http.MethodPost:
created.Add(1)
writeJSON(w, http.StatusAccepted, map[string]any{
"templateID": "tpl-fresh",
"status": "PENDING",
})
default:
http.NotFound(w, r)
}
})
template, err := client.EnsureStandardTemplate(context.Background())
require.NoError(t, err)
require.Equal(t, "tpl-failed", template.ID)
require.Equal(t, "failed", template.Status)
require.Contains(t, template.Error, "TOOMANYREQUESTS")
require.Equal(t, int32(0), deleted.Load())
require.Equal(t, int32(0), created.Load())
}
func TestCubeRemoteClientEnsureStandardTemplateBuildsWhenAbsent(t *testing.T) {
var payload map[string]any
client := newCubeTemplateClient(t, func(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case http.MethodGet:
writeJSON(w, http.StatusOK, []map[string]any{})
case http.MethodPost:
require.NoError(t, json.NewDecoder(r.Body).Decode(&payload))
writeJSON(w, http.StatusAccepted, map[string]any{
"templateID": "tpl-fresh",
"status": "PENDING",
})
}
})
template, err := client.EnsureStandardTemplate(context.Background())
require.NoError(t, err)
require.Equal(t, "tpl-fresh", template.ID)
require.True(t, template.Standard)
// Cube probes envd to decide whether the build succeeded, so the template
// must be built from the variant that ships it.
require.Equal(t, DefaultCubeTemplateImage, payload["image"])
require.Equal(t, StandardTemplateName, payload["name"])
require.Equal(t, "1G", payload["writableLayerSize"])
require.EqualValues(t, CubeEnvdPort, payload["probePort"])
require.Equal(t, CubeEnvdHealthPath, payload["probePath"])
require.Equal(t, true, payload["allowInternetAccess"])
_, hasDNS := payload["dns"]
require.False(t, hasDNS, "empty DNS config must omit the field so Cubelet keeps its default")
}
func TestCubeRemoteClientEnsureStandardTemplateIncludesConfiguredDNS(t *testing.T) {
var payload map[string]any
client := newCubeTemplateClient(t, func(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case http.MethodGet:
writeJSON(w, http.StatusOK, []map[string]any{})
case http.MethodPost:
require.NoError(t, json.NewDecoder(r.Body).Decode(&payload))
writeJSON(w, http.StatusAccepted, map[string]any{
"templateID": "tpl-dns",
"status": "PENDING",
})
}
})
client.config.CubeDNSServers = []string{"8.8.8.8", "1.1.1.1"}
template, err := client.EnsureStandardTemplate(context.Background())
require.NoError(t, err)
require.Equal(t, "tpl-dns", template.ID)
require.Equal(t, []any{"8.8.8.8", "1.1.1.1"}, payload["dns"])
}
func TestCubeRemoteClientReplaceStandardTemplateRebuildsInPlace(t *testing.T) {
var deleted atomic.Int32
var created atomic.Int32
var payload map[string]any
client := newCubeTemplateClient(t, func(w http.ResponseWriter, r *http.Request) {
switch {
case r.URL.Path == "/templates" && r.Method == http.MethodGet:
writeJSON(w, http.StatusOK, []map[string]any{{
"templateID": "tpl-old",
"status": "READY",
"imageInfo": DefaultDockerImage,
"aliases": []string{StandardTemplateName},
}})
case r.URL.Path == "/templates/tpl-old" && r.Method == http.MethodPost:
require.NoError(t, json.NewDecoder(r.Body).Decode(&payload))
writeJSON(w, http.StatusAccepted, map[string]any{
"templateID": "tpl-old",
"status": "PENDING",
})
case r.URL.Path == "/templates/tpl-old" && r.Method == http.MethodDelete:
deleted.Add(1)
w.WriteHeader(http.StatusNoContent)
case r.URL.Path == "/templates" && r.Method == http.MethodPost:
created.Add(1)
writeJSON(w, http.StatusAccepted, map[string]any{
"templateID": "tpl-new",
"status": "PENDING",
})
case r.URL.Path == "/snapshots" && r.Method == http.MethodGet:
writeJSON(w, http.StatusOK, []map[string]any{})
default:
http.NotFound(w, r)
}
})
client.config.CubeDNSServers = []string{"8.8.8.8"}
template, err := client.ReplaceStandardTemplate(context.Background())
require.NoError(t, err)
require.Equal(t, "tpl-old", template.ID)
require.Equal(t, "building", template.Status)
require.Equal(t, int32(0), deleted.Load(), "in-place rebuild must keep the stored template ID")
require.Equal(t, int32(0), created.Load())
require.Equal(t, []any{"8.8.8.8"}, payload["dns"])
require.Equal(t, true, payload["allowInternetAccess"])
}
func TestCubeRemoteClientReplaceStandardTemplateBuildsWithoutDeletingWhenRedoBlocked(t *testing.T) {
var deleted atomic.Int32
var payload map[string]any
client := newCubeTemplateClient(t, func(w http.ResponseWriter, r *http.Request) {
switch {
case r.URL.Path == "/templates" && r.Method == http.MethodGet:
writeJSON(w, http.StatusOK, []map[string]any{{
"templateID": "tpl-old",
"status": "READY",
"imageInfo": DefaultDockerImage,
"aliases": []string{StandardTemplateName},
}})
case r.URL.Path == "/templates/tpl-old" && r.Method == http.MethodPost:
writeJSON(w, http.StatusBadRequest, map[string]any{
"code": 400,
"message": "template redo is not allowed",
})
case r.URL.Path == "/templates" && r.Method == http.MethodPost:
require.NoError(t, json.NewDecoder(r.Body).Decode(&payload))
writeJSON(w, http.StatusAccepted, map[string]any{
"templateID": "tpl-new",
"status": "PENDING",
})
case r.URL.Path == "/templates/tpl-old" && r.Method == http.MethodDelete:
deleted.Add(1)
w.WriteHeader(http.StatusNoContent)
case r.URL.Path == "/snapshots" && r.Method == http.MethodGet:
writeJSON(w, http.StatusOK, []map[string]any{})
default:
http.NotFound(w, r)
}
})
template, err := client.ReplaceStandardTemplate(context.Background())
require.NoError(t, err)
require.Equal(t, "tpl-new", template.ID)
require.Equal(t, "building", template.Status)
require.Equal(t, int32(0), deleted.Load(),
"replace must not retire the READY template while the replacement is still building")
require.Equal(t, DefaultCubeTemplateImage, payload["image"])
}
func TestCubeRemoteClientDeleteSupersededStandardTemplatesSkipsKeepID(t *testing.T) {
var deleted atomic.Int32
client := newCubeTemplateClient(t, func(w http.ResponseWriter, r *http.Request) {
switch {
case r.URL.Path == "/templates" && r.Method == http.MethodGet:
writeJSON(w, http.StatusOK, []map[string]any{
{
"templateID": "tpl-old",
"status": "READY",
"imageInfo": DefaultDockerImage,
"aliases": []string{StandardTemplateName},
},
{
"templateID": "tpl-new",
"status": "READY",
"imageInfo": DefaultDockerImage,
"aliases": []string{StandardTemplateName},
},
})
case r.URL.Path == "/templates/tpl-old" && r.Method == http.MethodDelete:
deleted.Add(1)
w.WriteHeader(http.StatusNoContent)
case r.URL.Path == "/templates/tpl-new" && r.Method == http.MethodDelete:
t.Fatal("keepID must not be deleted")
case r.URL.Path == "/snapshots" && r.Method == http.MethodGet:
writeJSON(w, http.StatusOK, []map[string]any{})
default:
http.NotFound(w, r)
}
})
require.NoError(t, client.DeleteSupersededStandardTemplates(context.Background(), "tpl-new"))
require.Equal(t, int32(1), deleted.Load())
}
// The plain and Cube images share a repository, so a template built from either
// one is still recognised as ours — which is what lets an existing template
// built from the envd-less image be rebuilt in place rather than duplicated.
func TestCubeTemplateImageIsRecognisedAsStandard(t *testing.T) {
require.True(t, isStandardTemplateImage(DefaultCubeTemplateImage))
require.True(t, isStandardTemplateImage(DefaultDockerImage))
}
func TestIsStandardTemplateImage(t *testing.T) {
for _, image := range []string{
DefaultDockerImage,
"wechatopenai/weknora-sandbox",
"docker.io/wechatopenai/weknora-sandbox:latest",
"docker.io/wechatopenai/weknora-sandbox@sha256:abc",
"registry.internal:5000/wechatopenai/weknora-sandbox:v1",
} {
require.True(t, isStandardTemplateImage(image), image)
}
for _, image := range []string{
"",
"python:3.11",
"wechatopenai/weknora-docreader:latest",
"someone-else/academy-sandbox:latest",
} {
require.False(t, isStandardTemplateImage(image), image)
}
}
+183
View File
@@ -0,0 +1,183 @@
// Package sandbox: interactive terminal capability for the Cube adapter.
//
// The Cube SDK wraps envd's PTY service (sandbox.Pty) and hands back a
// PtyHandle with an Output channel, so the adapter's job is mostly
// translating between the neutral RemoteTerminal* types and the SDK's.
package sandbox
import (
"context"
"strings"
"sync"
"time"
cubesandbox "github.com/tencentcloud/CubeSandbox/sdk/go"
)
// Compile-time proof that the Cube adapter serves the terminal capability.
var _ RemoteTerminalManager = (*CubeRemoteClient)(nil)
// cubeTerminalTimeout bounds the envd stream server-side (Connect-Timeout-Ms)
// and client-side (idle abort). The SDK treats <= 0 as "use its 60s default",
// which would silently kill idle terminals, so Academy always passes an
// explicit long window. A session hitting it ends; the frontend reconnects
// and reattaches by PID when the shell is still running.
const cubeTerminalTimeout = 24 * time.Hour
func cubeSandboxTTL(cfg *Config) time.Duration {
if cfg != nil && cfg.CubeSandboxTTL > 0 {
return cfg.CubeSandboxTTL
}
return DefaultCubeSandboxTTL
}
// OpenTerminal opens an interactive shell PTY inside the sandbox behind
// handle. The returned session keeps streaming until the shell exits, the
// context passed to OpenTerminal is cancelled (the session derives its own
// lifetime from it), or Close is called.
func (c *CubeRemoteClient) OpenTerminal(
ctx context.Context,
handle RemoteSandboxHandle,
opts RemoteTerminalOptions,
) (RemoteTerminalSession, error) {
if _, err := cubeHandleSandbox("OpenTerminal", handle); err != nil {
return nil, err
}
sandboxID := strings.TrimSpace(handle.ID())
// Reattach rather than reuse the handle's sandbox so the PTY rides a
// freshly resolved envd endpoint. The client carries no HTTP-level
// timeout, and cubeFilesystemTransport exempts /process.Process/, so the
// stream body is bounded by ctx alone rather than CubeHTTPTimeout.
sb, err := c.client.Connect(ctx, sandboxID)
if err != nil {
return nil, normalizeCubeError("OpenTerminal", err)
}
if sb.TrafficAccessToken == "" {
sb.TrafficAccessToken = handleTrafficAccessToken(handle)
}
// The caller's ctx governs the stream (the SDK derives its internal
// stream context from it); explicit teardown goes through Close.
ptyHandle, err := openCubePty(ctx, sb, opts)
if err != nil {
return nil, normalizeCubeError("OpenTerminal", err)
}
session := &cubeTerminalSession{
sb: sb,
handle: ptyHandle,
pid: ptyHandle.PID(),
out: make(chan RemoteTerminalEvent, terminalOutputBuffer),
closedCh: make(chan struct{}),
ttl: cubeSandboxTTL(c.config),
}
go session.pump()
startTerminalTTLRefresh(ctx, session.closedCh, session.ttl, func(rctx context.Context) error {
if session.sb == nil {
return nil
}
return session.sb.SetTimeout(rctx, session.ttl)
})
return session, nil
}
func openCubePty(
ctx context.Context,
sb *cubesandbox.Sandbox,
opts RemoteTerminalOptions,
) (*cubesandbox.PtyHandle, error) {
size := cubesandbox.PtySize{
Rows: int(terminalRows(opts)),
Cols: int(terminalCols(opts)),
}
createOpts := cubesandbox.PtyCreateOptions{
User: terminalUser(opts),
Cwd: terminalCwd(opts),
Envs: terminalEnvs(opts),
Timeout: cubeTerminalTimeout,
}
if opts.AttachPID > 0 {
handle, err := sb.Pty().Connect(ctx, int(opts.AttachPID), cubesandbox.PtyConnectOptions{
Timeout: cubeTerminalTimeout,
})
if err == nil {
return handle, nil
}
}
return sb.Pty().Create(ctx, size, createOpts)
}
// cubeTerminalSession bridges one Cube PtyHandle to the neutral
// RemoteTerminalSession contract. The SDK's Output channel is closed when
// the stream ends, and Wait also surfaces exit code / error state — pump
// uses Wait so the terminal end is reported exactly once.
type cubeTerminalSession struct {
sb *cubesandbox.Sandbox
handle *cubesandbox.PtyHandle
pid int
out chan RemoteTerminalEvent
closedCh chan struct{}
closeOnce sync.Once
ttl time.Duration
// no cancel field: the SDK's handle owns its stream context and
// Disconnect tears it down.
}
func (s *cubeTerminalSession) pump() {
defer close(s.out)
// Every send goes through emitTerminalEvent: Close() can abandon the
// consumer at any point, and a bare send would strand this goroutine.
code, err := s.handle.Wait(func(chunk []byte) {
emitTerminalEvent(s.out, s.closedCh, RemoteTerminalEvent{Data: chunk})
})
select {
case <-s.closedCh:
return
default:
}
if err != nil {
emitTerminalEvent(s.out, s.closedCh,
RemoteTerminalEvent{Err: normalizeCubeError("terminal stream", err)})
return
}
emitTerminalEvent(s.out, s.closedCh, RemoteTerminalEvent{Exited: true, ExitCode: code})
}
func (s *cubeTerminalSession) Output() <-chan RemoteTerminalEvent { return s.out }
func (s *cubeTerminalSession) PID() uint32 { return uint32(s.pid) }
func (s *cubeTerminalSession) Write(ctx context.Context, data []byte) error {
if len(data) == 0 {
return nil
}
if err := s.handle.SendStdin(ctx, data); err != nil {
return normalizeCubeError("terminal input", err)
}
return nil
}
func (s *cubeTerminalSession) Resize(ctx context.Context, cols, rows uint32) error {
if cols == 0 || rows == 0 {
return nil
}
if err := s.handle.Resize(ctx, cubesandbox.PtySize{Rows: int(rows), Cols: int(cols)}); err != nil {
return normalizeCubeError("terminal resize", err)
}
return nil
}
// Close disconnects Academy from the PTY without killing the remote shell,
// leaving it reattachable via Pty.Connect. Wait unblocks through the
// disconnect without recording a stream error.
func (s *cubeTerminalSession) Close() error {
// Signal the pump before disconnecting so a blocked onData send cannot
// race the stream teardown. sync.Once rather than a select/default probe
// on closedCh: that check-then-close is not atomic, so two concurrent
// Close calls could both reach close() and panic.
s.closeOnce.Do(func() { close(s.closedCh) })
return s.handle.Disconnect()
}
+233
View File
@@ -0,0 +1,233 @@
package sandbox
import (
"bytes"
"context"
"net/http"
"sync"
"testing"
"time"
"github.com/stretchr/testify/require"
)
func pooledCubeClient(t *testing.T, mock *cubeMockServer, httpTimeout time.Duration) *CubeRemoteClient {
t.Helper()
cfg := testConfig(t, mock)
cfg.CubeHTTPTimeout = httpTimeout
cfg.AllowPrivateEndpoints = true
policy := OutboundURLPolicy{AllowPrivate: true}
pool := NewSandboxGatewayTransportPoolWithPolicy(
NewGuardedTransportWithPolicy(policy),
policy,
)
client, err := NewCubeRemoteClientWithPool(cfg, pool)
require.NoError(t, err)
return client
}
func TestCubeOpenTerminalStreamSurvivesHTTPClientTimeout(t *testing.T) {
mock := newCubeMockServer(t)
mock.ptyHoldAfterStart = 300 * time.Millisecond
mock.ptyLatePayload = "late-frame"
client := pooledCubeClient(t, mock, 120*time.Millisecond)
ctx := context.Background()
handle, err := client.Create(ctx, RemoteCreateRequest{
TemplateID: "template-a",
Timeout: RemoteTimeoutPolicy{
Mode: RemoteTimeoutExplicit,
Value: time.Minute,
Action: RemoteOnTimeoutKill,
},
})
require.NoError(t, err)
session, err := client.OpenTerminal(ctx, handle, RemoteTerminalOptions{Cols: 80, Rows: 24})
require.NoError(t, err)
t.Cleanup(func() { _ = session.Close() })
deadline := time.After(time.Second)
var got []byte
for {
select {
case ev, ok := <-session.Output():
if !ok {
t.Fatalf("PTY stream closed before the late frame; collected %q", got)
}
if ev.Err != nil {
t.Fatalf("PTY stream failed before the late frame: %v (collected %q)", ev.Err, got)
}
got = append(got, ev.Data...)
if bytes.Contains(got, []byte("late-frame")) {
return
}
case <-deadline:
t.Fatalf("timed out waiting for late PTY frame; collected %q", got)
}
}
}
func TestCubeOpenTerminalRefreshesSandboxTTL(t *testing.T) {
prevMin := terminalTTLRefreshMin
terminalTTLRefreshMin = 40 * time.Millisecond
t.Cleanup(func() { terminalTTLRefreshMin = prevMin })
mock := newCubeMockServer(t)
mock.ptyHoldAfterStart = time.Second
client := pooledCubeClient(t, mock, 5*time.Second)
cfg := testConfig(t, mock)
cfg.CubeSandboxTTL = 3 * time.Second
client.config = cfg
ctx := context.Background()
handle, err := client.Create(ctx, RemoteCreateRequest{
TemplateID: "template-a",
Timeout: RemoteTimeoutPolicy{
Mode: RemoteTimeoutExplicit,
Value: time.Minute,
Action: RemoteOnTimeoutKill,
},
})
require.NoError(t, err)
session, err := client.OpenTerminal(ctx, handle, RemoteTerminalOptions{})
require.NoError(t, err)
t.Cleanup(func() { _ = session.Close() })
require.Eventually(t, func() bool {
return mock.timeoutPOSTs.Load() >= 1
}, 2*time.Second, 20*time.Millisecond, "expected SetTimeout while the PTY is open")
}
func TestCubeDialDesktopRefreshesSandboxTTL(t *testing.T) {
// Desktop traffic is websockify on 6080, not envd, so CubeMaster never
// sees it. SetTimeout must follow the relay lifetime (WithoutCancel),
// not DialDesktop's request ctx — that ctx is cancelled on handshake
// abort and must not take the refresh loop with it.
prevMin := terminalTTLRefreshMin
terminalTTLRefreshMin = 40 * time.Millisecond
t.Cleanup(func() { terminalTTLRefreshMin = prevMin })
mock := newCubeMockServer(t)
var seen http.Request
proxy := desktopEchoServer(t, &seen)
t.Cleanup(proxy.Close)
cfg := testConfig(t, mock)
cfg.CubeProxyURL = proxy.URL
cfg.CubeSandboxTTL = 3 * time.Second
cfg.CubeHTTPTimeout = 5 * time.Second
policy := OutboundURLPolicy{AllowPrivate: true}
pool := NewSandboxGatewayTransportPoolWithPolicy(
NewGuardedTransportWithPolicy(policy),
policy,
)
client, err := NewCubeRemoteClientWithPool(cfg, pool)
require.NoError(t, err)
dialCtx, dialCancel := context.WithCancel(context.Background())
handle, err := client.Create(dialCtx, RemoteCreateRequest{
TemplateID: "template-a",
Timeout: RemoteTimeoutPolicy{
Mode: RemoteTimeoutExplicit,
Value: time.Minute,
Action: RemoteOnTimeoutKill,
},
})
require.NoError(t, err)
conn, err := client.DialDesktop(dialCtx, handle, RemoteDesktopOptions{})
require.NoError(t, err)
t.Cleanup(func() { _ = conn.Close() })
dialCancel()
require.Never(t, func() bool {
return mock.timeoutPOSTs.Load() >= 1
}, 150*time.Millisecond, 20*time.Millisecond,
"DialDesktop must not bind SetTimeout to the request context")
ttlCtx, ttlCancel := context.WithCancel(context.Background())
t.Cleanup(ttlCancel)
client.StartDesktopTTLRefresh(ttlCtx, handle)
require.Eventually(t, func() bool {
return mock.timeoutPOSTs.Load() >= 1
}, 2*time.Second, 20*time.Millisecond, "expected SetTimeout on the relay lifetime ctx")
}
func TestCubeOpenTerminalReattachesByPID(t *testing.T) {
mock := newCubeMockServer(t)
client := pooledCubeClient(t, mock, 5*time.Second)
ctx := context.Background()
handle, err := client.Create(ctx, RemoteCreateRequest{
TemplateID: "template-a",
Timeout: RemoteTimeoutPolicy{
Mode: RemoteTimeoutExplicit,
Value: time.Minute,
Action: RemoteOnTimeoutKill,
},
})
require.NoError(t, err)
session, err := client.OpenTerminal(ctx, handle, RemoteTerminalOptions{AttachPID: 99})
require.NoError(t, err)
t.Cleanup(func() { _ = session.Close() })
require.Equal(t, int32(1), mock.ptyConnectCount.Load())
require.Equal(t, int32(0), mock.ptyStartCount.Load())
require.Equal(t, uint32(4321), session.PID())
}
// RemoteTerminalSession documents Close as safe to call more than once, and
// the bridge can reach it from several goroutines. A check-then-close probe
// on the teardown channel would panic here.
func TestCubeTerminalCloseIsIdempotentUnderConcurrency(t *testing.T) {
mock := newCubeMockServer(t)
mock.ptyHoldAfterStart = time.Second
client := pooledCubeClient(t, mock, 5*time.Second)
ctx := context.Background()
handle, err := client.Create(ctx, RemoteCreateRequest{
TemplateID: "template-a",
Timeout: RemoteTimeoutPolicy{
Mode: RemoteTimeoutExplicit,
Value: time.Minute,
Action: RemoteOnTimeoutKill,
},
})
require.NoError(t, err)
session, err := client.OpenTerminal(ctx, handle, RemoteTerminalOptions{})
require.NoError(t, err)
drained := make(chan struct{})
go func() {
defer close(drained)
for range session.Output() {
}
}()
// A shared start barrier: the racy version's window between "channel
// looks open" and close() is only a few nanoseconds, so staggered
// goroutines would sail past it.
start := make(chan struct{})
var wg sync.WaitGroup
for i := 0; i < 64; i++ {
wg.Add(1)
go func() {
defer wg.Done()
<-start
_ = session.Close()
}()
}
close(start)
wg.Wait()
// The pump must also terminate, closing Output exactly once.
select {
case <-drained:
case <-time.After(3 * time.Second):
t.Fatal("Output channel never closed after Close")
}
}
+140
View File
@@ -0,0 +1,140 @@
// Package sandbox provides graphical desktop (VNC over WebSocket) capability.
//
// The desktop is an optional, provider-neutral capability alongside
// RemoteTerminalManager. It differs from the terminal in one structural way:
// the terminal rides envd's PTY service, while the desktop is a raw WebSocket
// to a non-envd port (websockify on 6080) routed through the same gateway.
// That is why it needs its own capability bit and its own dialer.
package sandbox
import (
"context"
"encoding/base64"
"errors"
"net/http"
"strings"
"github.com/gorilla/websocket"
)
// ErrDesktopUnsupported is returned when the session's backend cannot relay a
// desktop, or the config's template is not a desktop image.
var ErrDesktopUnsupported = errors.New("sandbox: desktop is not supported by this backend")
// RemoteDesktopOptions carries the neutral parameters for dialling a desktop.
type RemoteDesktopOptions struct {
// BasicAuthUser / BasicAuthPassword authenticate against websockify's
// BasicHTTPAuth plugin. The password is read out of the sandbox at
// DesktopSecretPath and MUST NOT be sent to the browser: it is a
// backend-to-sandbox credential only.
// An empty user falls back to DesktopBasicAuthUser.
BasicAuthUser string
BasicAuthPassword string
}
// dialSandboxDesktop is the provider-neutral half of DialDesktop. Both
// adapters call it so the credential shape and the error mapping cannot drift.
func dialSandboxDesktop(
ctx context.Context,
provider RemoteProvider,
dialer *WebsocketDialer,
handle RemoteSandboxHandle,
opts RemoteDesktopOptions,
) (*websocket.Conn, error) {
if handle == nil || strings.TrimSpace(handle.ID()) == "" {
return nil, &RemoteError{
Kind: RemoteErrorKindInvalidRequest, Provider: provider,
Op: "DialDesktop", Message: "handle is required",
}
}
header := http.Header{}
// Cube exec/PTY attach this from the SDK sandbox object, so a terminal
// still works when the pool registry is empty. DialDesktop used to read
// only the registry, which Cube Create/Connect never wrote, and CubeProxy
// answered 401 on 6080 while envd on 49983 was fine.
if token := InboundTokenOf(handle); token != "" {
header.Set(InboundTokenHeader, token)
}
if opts.BasicAuthPassword != "" {
user := opts.BasicAuthUser
if user == "" {
user = DesktopBasicAuthUser
}
header.Set("Authorization", "Basic "+base64.StdEncoding.EncodeToString(
[]byte(user+":"+opts.BasicAuthPassword)))
}
conn, resp, err := dialer.Dial(
ctx, handle.ID(), DesktopWebsockifyPort, DesktopWebsockifyPath, header)
if err != nil {
kind := RemoteErrorKindUnavailable
status := 0
if resp != nil {
status = resp.StatusCode
if status == http.StatusUnauthorized || status == http.StatusForbidden {
kind = RemoteErrorKindAuthentication
}
}
return nil, &RemoteError{
Kind: kind, Provider: provider, Op: "DialDesktop",
Message: "dial websockify", StatusCode: status, Cause: err,
}
}
return conn, nil
}
// RemoteDesktopManager is the optional capability interface for backends that
// can relay a WebSocket to the desktop port of a running sandbox. Mirrors
// RemoteTerminalManager: advertised via RemoteSandboxCapabilities
// (SupportsDesktop) and narrowed with DesktopManagerFrom.
type RemoteDesktopManager interface {
// DialDesktop opens a WebSocket to websockify inside the sandbox behind
// handle. The returned connection carries raw RFB bytes in binary frames.
DialDesktop(ctx context.Context, handle RemoteSandboxHandle, opts RemoteDesktopOptions) (*websocket.Conn, error)
}
// DesktopManagerFrom narrows a client to its desktop capability.
//
// Both signals must agree, exactly as in TerminalManagerFrom: the type
// assertion finds the method, and SupportsDesktop is the advertised
// capability. Either one alone is not enough — a decorator can carry the
// method while the inner backend cannot serve it.
func DesktopManagerFrom(client RemoteSandboxClient) (RemoteDesktopManager, bool) {
if client == nil {
return nil, false
}
mgr, ok := client.(RemoteDesktopManager)
if !ok {
return nil, false
}
if !client.Capabilities().SupportsDesktop {
return nil, false
}
return mgr, true
}
// RemoteDesktopTTLRefresher extends a desktop backend with provider idle-TTL
// refresh. DialDesktop must not start that loop: its ctx is the HTTP request,
// which is cancelled on handshake abort. The WebSocket handler starts refresh
// on the relay ctx (WithoutCancel) after upgrade, matching OpenTerminal.
type RemoteDesktopTTLRefresher interface {
StartDesktopTTLRefresh(ctx context.Context, handle RemoteSandboxHandle)
}
// DesktopTTLRefresherFrom narrows a client to desktop TTL refresh.
//
// SupportsTimeoutRefresh is the advertised capability (Docker is false: it
// has no SetTimeout). The type assertion finds the method through wrappers
// such as Langfuse, the same two-signal pattern as DesktopManagerFrom.
func DesktopTTLRefresherFrom(client RemoteSandboxClient) (RemoteDesktopTTLRefresher, bool) {
if client == nil {
return nil, false
}
refresher, ok := client.(RemoteDesktopTTLRefresher)
if !ok {
return nil, false
}
if !client.Capabilities().SupportsTimeoutRefresh {
return nil, false
}
return refresher, true
}
+67
View File
@@ -0,0 +1,67 @@
// Package sandbox provides the shell fed to the desktop sandbox over Exec.
//
// These live as real .sh files rather than Go string literals so they keep
// shell tooling (shellcheck, `sh -n`, an editor that knows the language) and
// so a diff reads as shell instead of as an escaped blob. They are sent as
// the command body rather than invoked by path on purpose: unlike
// DesktopStartScript they are not baked into the image, so they also reach
// sandboxes booted from an older desktop template.
package sandbox
import (
"regexp"
"strings"
_ "embed"
)
//go:embed desktopscripts/ensure.sh
var desktopEnsureScript string
//go:embed desktopscripts/reset-listeners.sh
var desktopResetListenersScript string
// DesktopEnsureUnsupportedExit is ensure.sh when DesktopStartScript is missing.
// POSIX sh also exits 2 on syntax errors; pair with the stderr marker.
const DesktopEnsureUnsupportedExit = 2
// DesktopEnsureUnsupportedMarker is written to stderr immediately before
// that exit 2. Go must see both or the failure is a broken wrapper, not
// a BYO image without a desktop.
const DesktopEnsureUnsupportedMarker = "ACADEMY_DESKTOP_UNSUPPORTED"
var desktopReadyLine = regexp.MustCompile(`^READY ([A-Za-z0-9]{32})$`)
// DesktopEnsureCmd starts the desktop listeners (or takes the image script's
// fast path) and prints READY <secret> on stdout. Invoking DesktopStartScript
// by path hangs the Exec: envd waits for stdout/stderr to close, and the
// daemons keep those pipes. This wrapper points them at a log file.
func DesktopEnsureCmd() string { return desktopEnsureScript }
// DesktopResetListenersCmd drops a half-started desktop so the next
// DesktopEnsureCmd run rebuilds it instead of taking its fast path.
func DesktopResetListenersCmd() string { return desktopResetListenersScript }
// ParseDesktopEnsureSecret requires stdout to be exactly one READY line.
// ensure.sh promises that; a last-non-empty-line parser would accept
// "garbage\nREADY <secret>" and dial, hiding the leak behind a 401/502.
// A single trailing newline (printf) is allowed; nothing else is.
func ParseDesktopEnsureSecret(stdout string) (string, bool) {
s := strings.ReplaceAll(stdout, "\r\n", "\n")
s = strings.TrimSuffix(s, "\n")
m := desktopReadyLine.FindStringSubmatch(s)
if m == nil {
return "", false
}
return m[1], true
}
// IsDesktopEnsureUnsupported is the BYO-image miss: exit 2 plus the
// marker. A bare 2 is a shell/wrapper failure and must not become
// ErrDesktopUnsupported.
func IsDesktopEnsureUnsupported(result *ExecuteResult) bool {
if result == nil || result.Killed || result.ExitCode != DesktopEnsureUnsupportedExit {
return false
}
return strings.Contains(result.Stderr, DesktopEnsureUnsupportedMarker)
}
+218
View File
@@ -0,0 +1,218 @@
package sandbox
import (
"context"
"os"
"path/filepath"
"strings"
"testing"
"github.com/gorilla/websocket"
"github.com/stretchr/testify/require"
)
type desktopFakeClient struct {
*fakeRemoteClient
dialed bool
ttlStarted int
}
func (c *desktopFakeClient) DialDesktop(
context.Context, RemoteSandboxHandle, RemoteDesktopOptions,
) (*websocket.Conn, error) {
c.dialed = true
return nil, nil
}
func (c *desktopFakeClient) StartDesktopTTLRefresh(context.Context, RemoteSandboxHandle) {
c.ttlStarted++
}
func TestDesktopManagerFromRequiresBothSignals(t *testing.T) {
// Methods present but capability off: a provider that grew the method
// before the deployment was ready must still read as unsupported.
off := &desktopFakeClient{fakeRemoteClient: newFakeRemoteClient(SandboxTypeCube)}
off.capabilities.SupportsDesktop = false
_, ok := DesktopManagerFrom(off)
require.False(t, ok, "capability flag alone must be able to veto")
// Capability on but no methods: the plain fake has no DialDesktop.
plain := newFakeRemoteClient(SandboxTypeCube)
plain.capabilities.SupportsDesktop = true
_, ok = DesktopManagerFrom(plain)
require.False(t, ok, "type assertion alone must be able to veto")
on := &desktopFakeClient{fakeRemoteClient: newFakeRemoteClient(SandboxTypeCube)}
on.capabilities.SupportsDesktop = true
mgr, ok := DesktopManagerFrom(on)
require.True(t, ok)
require.NotNil(t, mgr)
}
func TestDesktopManagerFromNilClient(t *testing.T) {
_, ok := DesktopManagerFrom(nil)
require.False(t, ok)
}
func TestDesktopTTLRefresherFromRequiresTimeoutCapability(t *testing.T) {
off := &desktopFakeClient{fakeRemoteClient: newFakeRemoteClient(SandboxTypeCube)}
off.capabilities.SupportsTimeoutRefresh = false
_, ok := DesktopTTLRefresherFrom(off)
require.False(t, ok, "Docker-like backends have the method via wrappers but no timeout to refresh")
on := &desktopFakeClient{fakeRemoteClient: newFakeRemoteClient(SandboxTypeCube)}
on.capabilities.SupportsTimeoutRefresh = true
refresher, ok := DesktopTTLRefresherFrom(on)
require.True(t, ok)
require.NotNil(t, refresher)
}
func startDesktopScript(t *testing.T) string {
t.Helper()
body, err := os.ReadFile(filepath.Join("..", "..", "docker", "scripts", "start-desktop.sh"))
require.NoError(t, err)
return string(body)
}
// shellCode drops comment lines so an assertion about what a script *does*
// cannot be satisfied (or broken) by prose explaining it.
func shellCode(src string) string {
var code []string
for _, line := range strings.Split(src, "\n") {
if strings.HasPrefix(strings.TrimSpace(line), "#") {
continue
}
code = append(code, line)
}
return strings.Join(code, "\n")
}
func TestStartDesktopScriptFastPathRequiresVNCPort(t *testing.T) {
// 6080-only "already ready" lets websockify sit up while x11vnc is dead.
// DialDesktop then 101s, RFB hello never comes, and the session slot is
// held until the handshake read times out — every retry is DESKTOP_BUSY.
src := startDesktopScript(t)
require.Contains(t, src, "port_open 6080")
require.Contains(t, src, "port_open 5900")
}
func TestStartDesktopScriptClosesLockFDInEveryDaemon(t *testing.T) {
// Reproduced against wechatopenai/weknora-sandbox:main-desktop: Xvfb,
// xfce4-session, dbus-launch, x11vnc and websockify all inherited fd 9
// and kept holding the flock after the script exited. Killing x11vnc and
// websockify then left Xvfb/XFCE holding it, so the next run blocked on
// flock forever — Exec timed out at 60s (exit=-1) and 6080 never returned.
code := shellCode(startDesktopScript(t))
// spawn() carries both `9>&-` and the private stdio; the two daemons that
// cannot use it (dbus --fork, x11vnc -bg) spell it out.
require.Contains(t, code, `"$@" </dev/null >>"/run/desktop/$name.log" 2>&1 9>&- &`)
for _, launch := range []string{
"spawn xvfb Xvfb :0",
"spawn xfce4-session xfce4-session",
"spawn websockify websockify --auth-plugin",
"dbus-daemon --system --fork </dev/null >>/run/desktop/dbus.log 2>&1 9>&-",
"</dev/null >>/run/desktop/x11vnc.log 2>&1 9>&-",
} {
require.Contains(t, code, launch,
"every daemon must close fd 9 and own its stdio")
}
}
func TestParseDesktopEnsureSecretAcceptsExactReadyLine(t *testing.T) {
const secret = "abcdefghijklmnopqrstuvwxyz012345"
got, ok := ParseDesktopEnsureSecret("READY " + secret + "\n")
require.True(t, ok)
require.Equal(t, secret, got)
got, ok = ParseDesktopEnsureSecret("READY " + secret)
require.True(t, ok)
require.Equal(t, secret, got)
}
func TestParseDesktopEnsureSecretRejectsNoise(t *testing.T) {
const line = "READY abcdefghijklmnopqrstuvwxyz012345\n"
_, ok := ParseDesktopEnsureSecret(line + "extra\n")
require.False(t, ok, "suffix after READY is a leak")
_, ok = ParseDesktopEnsureSecret("started\n" + line)
require.False(t, ok, "prefix before READY must not be ignored; last-line parse would dial with a polluted buffer")
_, ok = ParseDesktopEnsureSecret("\n" + line)
require.False(t, ok)
_, ok = ParseDesktopEnsureSecret("started\n")
require.False(t, ok)
_, ok = ParseDesktopEnsureSecret("READY short\n")
require.False(t, ok)
_, ok = ParseDesktopEnsureSecret("")
require.False(t, ok)
}
func TestIsDesktopEnsureUnsupportedRequiresMarker(t *testing.T) {
require.False(t, IsDesktopEnsureUnsupported(nil))
require.False(t, IsDesktopEnsureUnsupported(&ExecuteResult{
ExitCode: 2, Stderr: "Syntax error: end of file unexpected",
}), "POSIX sh uses exit 2 for syntax errors")
require.True(t, IsDesktopEnsureUnsupported(&ExecuteResult{
ExitCode: 2, Stderr: DesktopEnsureUnsupportedMarker + "\n",
}))
require.False(t, IsDesktopEnsureUnsupported(&ExecuteResult{
ExitCode: 2, Killed: true, Stderr: DesktopEnsureUnsupportedMarker,
}))
require.False(t, IsDesktopEnsureUnsupported(&ExecuteResult{
ExitCode: 1, Stderr: DesktopEnsureUnsupportedMarker,
}))
}
func TestDesktopEnsureCmdDetachesDaemonStdio(t *testing.T) {
// envd's exec waits for stdout and stderr to close. Invoking
// DesktopStartScript by path let the backgrounded daemons hold those
// pipes for the life of the sandbox, so the Exec hit its 60s timeout
// (exit=-1 -> DESKTOP_START_FAILED) while the desktop was actually up.
cmd := DesktopEnsureCmd()
code := shellCode(cmd)
require.Contains(t, cmd, DesktopStartScript)
require.Contains(t, code, "</dev/null")
require.Contains(t, code, ">>\"$log\" 2>&1")
require.Contains(t, code, "tail -c")
require.Contains(t, code, `printf 'READY %s\n' "$secret"`)
require.Contains(t, code, "ACADEMY_DESKTOP_UNSUPPORTED")
require.Contains(t, code, "exit 2")
require.NotContains(t, code, "pkill")
}
func TestDesktopEnsureCmdProbesNeverDial(t *testing.T) {
code := shellCode(DesktopEnsureCmd())
require.Contains(t, code, "/proc/net/tcp")
require.Contains(t, code, "5900")
require.Contains(t, code, "6080")
for _, dialish := range []string{"connect_ex", "create_connection", "nc -z", "ss -", "curl"} {
require.NotContains(t, code, dialish)
}
require.NotContains(t, shellCode(startDesktopScript(t)), "connect_ex")
}
func TestStartDesktopScriptGuardsListenersOnPortNotPgrep(t *testing.T) {
// Reproduced in the desktop image: x11vnc -bg leaves a zombie when PID 1
// does not reap it, pgrep counts zombies as running, and the x11vnc step
// becomes a permanent no-op. websockify keeps answering on 6080, so
// DialDesktop 101s and the RFB hello never arrives.
code := shellCode(startDesktopScript(t))
require.Contains(t, code, "port_open 5900 || \\")
require.Contains(t, code, "port_open 6080 || \\")
require.NotContains(t, code, "pgrep -x x11vnc")
require.NotContains(t, code, "pgrep -f \"websockify")
// The processes with no port of their own need the zombie-aware helper.
require.Contains(t, code, "proc_alive Xvfb")
require.Contains(t, code, "proc_alive xfce4-session")
require.NotContains(t, code, "pgrep -x Xvfb")
require.NotContains(t, code, "pgrep -x xfce4-session")
}
func TestDesktopResetListenersCmdClearsLeakedLock(t *testing.T) {
// Older images still leak the flock fd, so the reset has to unwedge them
// without an image rebuild.
reset := shellCode(DesktopResetListenersCmd())
require.Contains(t, reset, "x11vnc")
require.Contains(t, reset, "[w]ebsockify")
require.Contains(t, reset, "/run/desktop/.lock")
// Xvfb and XFCE are expensive and never the reason 6080 is mute.
require.NotContains(t, reset, "Xvfb")
require.NotContains(t, reset, "xfce4-session")
}
+63
View File
@@ -0,0 +1,63 @@
#!/bin/sh
# One Exec: prove the image has a desktop, start it, print the websockify secret.
#
# exit 2 — start-desktop.sh missing. stderr MUST contain
# ACADEMY_DESKTOP_UNSUPPORTED; POSIX sh also uses 2 for
# syntax errors, so Go ignores a bare 2.
# exit 1 — start failed or listeners never came up
# exit 0 — stdout is exactly one line: READY <32 alnum>
#
# Daemons must not inherit this Exec's pipes (envd waits for them to close)
# or fd 9 (see start-desktop.sh). Reset/retry lives in Go, not here: a 60s
# timeout kill cannot run the rest of this script.
set -u
if [ ! -x /usr/local/bin/start-desktop.sh ]; then
echo ACADEMY_DESKTOP_UNSUPPORTED >&2
exit 2
fi
export LANG="${LANG:-C.UTF-8}"
export LC_ALL="${LC_ALL:-C.UTF-8}"
mkdir -p /run/desktop
log=/run/desktop/start-desktop.log
/usr/local/bin/start-desktop.sh </dev/null >>"$log" 2>&1
rc=$?
if [ "$rc" -ne 0 ]; then
tail -c 2000 "$log" >&2
exit 1
fi
listening() {
hex=$(printf '%04X' "$1")
cat /proc/net/tcp /proc/net/tcp6 2>/dev/null | awk -v hex="$hex" '
$4 == "0A" {
n = split($2, addr, ":")
if (toupper(addr[n]) == hex) { found = 1 }
}
END { exit !found }
'
}
if ! listening 5900 || ! listening 6080; then
tail -c 2000 "$log" >&2
exit 1
fi
secret=$(cat /run/desktop/secret 2>/dev/null) || true
case "$secret" in
*[!A-Za-z0-9]*|"")
echo "desktop secret missing or malformed" >&2
exit 1
;;
esac
# start-desktop.sh writes 32 bytes; reject anything else so Go can require
# ^READY ([A-Za-z0-9]{32})$ without a second round trip.
if [ "${#secret}" -ne 32 ]; then
echo "desktop secret length ${#secret}" >&2
exit 1
fi
printf 'READY %s\n' "$secret"
@@ -0,0 +1,32 @@
#!/bin/sh
# Tear down a half-started desktop so the next start-desktop.sh rebuilds it.
#
# Xvfb and the XFCE session are deliberately left alone: they are expensive to
# restart and never the reason 6080 is mute.
#
# Sent over Exec by SandboxDesktopService, not baked into the image, so it
# also applies to sandboxes running an older desktop image.
set -u
pkill -x x11vnc >/dev/null 2>&1 || true
pkill -f '[w]ebsockify.*6080' >/dev/null 2>&1 || true
# Images built before the 9>&- fix leak the flock fd into every daemon the
# script spawns, so killing x11vnc/websockify leaves Xvfb and xfce4-session
# holding the lock and the next start-desktop.sh blocks on flock until its
# Exec times out (exit=-1, 6080 never returns). Unlinking the lock file gives
# that run a fresh inode to lock. Safe here: the per-sandbox secret the lock
# protects is written once and already exists by the time anything is reset.
if [ -e /run/desktop/.lock ]; then
for holder in /proc/[0-9]*/fd/*; do
[ -e "$holder" ] || continue
case "$(readlink "$holder" 2>/dev/null)" in
*/run/desktop/.lock)
rm -f /run/desktop/.lock
break
;;
esac
done
fi
exit 0
+69
View File
@@ -0,0 +1,69 @@
package sandbox
import (
"errors"
"os"
"strconv"
"strings"
"sync/atomic"
)
// DockerBackendEnabledEnv is the process-level fallback for the Docker
// sandbox backend. System Settings (sandbox.docker_enabled) override it
// when a row has been pushed by SystemSettingService.
//
// A workspace admin who can save a Docker config can create containers on
// whatever Engine API this process can reach — typically the host's
// docker.sock, which is host root. It is therefore off until a
// SystemAdmin or deployer opts in.
const DockerBackendEnabledEnv = "ACADEMY_SANDBOX_DOCKER_ENABLED"
// DockerBackendEnabledSettingKey is the system_settings registry key.
const DockerBackendEnabledSettingKey = "sandbox.docker_enabled"
// ErrDockerBackendDisabled is returned when a Docker sandbox config is saved,
// probed, or resolved and the process has not opted in.
var ErrDockerBackendDisabled = errors.New(
"sandbox: docker backend is disabled; enable it in System Settings or set ACADEMY_SANDBOX_DOCKER_ENABLED=true",
)
// dockerBackendEnabledOverride is the runtime-tunable source. Nil means
// "SystemSettingService has not pushed yet"; DockerBackendEnabled then
// reads the env, matching the preload window and tests that only Setenv.
var dockerBackendEnabledOverride atomic.Pointer[bool]
// SetDockerBackendEnabled records the resolved 3-tier value (DB > env >
// false). Called at system_settings preload, Update, Reset, and pubsub reload.
func SetDockerBackendEnabled(enabled bool) {
v := enabled
dockerBackendEnabledOverride.Store(&v)
}
// ClearDockerBackendEnabledOverride restores env-only resolution. Tests that
// construct SystemSettingService can otherwise leak a preload push into later
// Setenv-based cases in the same package.
func ClearDockerBackendEnabledOverride() {
dockerBackendEnabledOverride.Store(nil)
}
// DockerBackendEnabled reports whether this process may run the Docker sandbox
// backend. Empty or unparsable env values are false.
func DockerBackendEnabled() bool {
if p := dockerBackendEnabledOverride.Load(); p != nil {
return *p
}
parsed, err := strconv.ParseBool(strings.TrimSpace(os.Getenv(DockerBackendEnabledEnv)))
return err == nil && parsed
}
// EnsureDockerBackendAllowed is the choke point for every path that would
// talk to a Docker daemon on behalf of a workspace config.
func EnsureDockerBackendAllowed(t SandboxType) error {
if t != SandboxTypeDocker {
return nil
}
if DockerBackendEnabled() {
return nil
}
return ErrDockerBackendDisabled
}
+66
View File
@@ -0,0 +1,66 @@
package sandbox
import "testing"
func isolateDockerEnabled(t *testing.T) {
t.Helper()
ClearDockerBackendEnabledOverride()
t.Cleanup(ClearDockerBackendEnabledOverride)
}
func TestDockerBackendEnabledDefaultsOff(t *testing.T) {
isolateDockerEnabled(t)
t.Setenv(DockerBackendEnabledEnv, "")
if DockerBackendEnabled() {
t.Fatal("empty env must leave the docker backend disabled")
}
if err := EnsureDockerBackendAllowed(SandboxTypeDocker); err != ErrDockerBackendDisabled {
t.Fatalf("EnsureDockerBackendAllowed(docker) = %v, want ErrDockerBackendDisabled", err)
}
if err := EnsureDockerBackendAllowed(SandboxTypeCube); err != nil {
t.Fatalf("EnsureDockerBackendAllowed(cube) = %v, want nil", err)
}
}
func TestDockerBackendEnabledAcceptsParseBoolTrue(t *testing.T) {
isolateDockerEnabled(t)
for _, raw := range []string{"true", "TRUE", "1", "t"} {
t.Run(raw, func(t *testing.T) {
isolateDockerEnabled(t)
t.Setenv(DockerBackendEnabledEnv, raw)
if !DockerBackendEnabled() {
t.Fatalf("%q should enable the docker backend", raw)
}
if err := EnsureDockerBackendAllowed(SandboxTypeDocker); err != nil {
t.Fatalf("EnsureDockerBackendAllowed(docker) = %v, want nil", err)
}
})
}
}
func TestDockerBackendEnabledRejectsFalsey(t *testing.T) {
isolateDockerEnabled(t)
for _, raw := range []string{"false", "0", "no", "yes", "on"} {
t.Run(raw, func(t *testing.T) {
isolateDockerEnabled(t)
t.Setenv(DockerBackendEnabledEnv, raw)
if DockerBackendEnabled() {
t.Fatalf("%q must not enable the docker backend", raw)
}
})
}
}
func TestSetDockerBackendEnabledOverridesEnv(t *testing.T) {
isolateDockerEnabled(t)
t.Setenv(DockerBackendEnabledEnv, "false")
SetDockerBackendEnabled(true)
if !DockerBackendEnabled() {
t.Fatal("system-settings push must enable even when env is false")
}
SetDockerBackendEnabled(false)
t.Setenv(DockerBackendEnabledEnv, "true")
if DockerBackendEnabled() {
t.Fatal("system-settings false must win over env true")
}
}
+473
View File
@@ -0,0 +1,473 @@
// Docker Engine plumbing for the docker backend.
//
// This file owns everything between Academy and the Docker Engine API that is
// not sandbox semantics: the narrow interface the adapter talks to (so unit
// tests need no daemon), how a daemon connection is built and shared, and how
// Engine errors are classified into the provider-neutral RemoteErrorKind.
//
// Connections are pooled per daemon endpoint. Managers are rebuilt on every
// request (see tenant_resolver.go), and each moby client owns an HTTP
// transport, so constructing one per request would leak a connection pool per
// request.
package sandbox
import (
"context"
"errors"
"fmt"
"path/filepath"
"strings"
"sync"
"time"
cerrdefs "github.com/containerd/errdefs"
"github.com/moby/moby/api/types/container"
"github.com/moby/moby/client"
)
// dockerEngineAPI is the slice of the Docker Engine API the sandbox adapter
// uses. It exists so tests can drive the adapter without a daemon; the real
// implementation is *client.Client, which satisfies it as-is.
type dockerEngineAPI interface {
Ping(ctx context.Context, options client.PingOptions) (client.PingResult, error)
ContainerCreate(ctx context.Context, options client.ContainerCreateOptions) (client.ContainerCreateResult, error)
ContainerStart(
ctx context.Context, containerID string, options client.ContainerStartOptions,
) (client.ContainerStartResult, error)
ContainerUnpause(
ctx context.Context, containerID string, options client.ContainerUnpauseOptions,
) (client.ContainerUnpauseResult, error)
ContainerInspect(
ctx context.Context, containerID string, options client.ContainerInspectOptions,
) (client.ContainerInspectResult, error)
ContainerList(ctx context.Context, options client.ContainerListOptions) (client.ContainerListResult, error)
ContainerRemove(
ctx context.Context, containerID string, options client.ContainerRemoveOptions,
) (client.ContainerRemoveResult, error)
ExecCreate(
ctx context.Context, containerID string, options client.ExecCreateOptions,
) (client.ExecCreateResult, error)
ExecAttach(ctx context.Context, execID string, options client.ExecAttachOptions) (client.ExecAttachResult, error)
// ExecStart starts an already-created exec. The terminal path uses it,
// detached, to run a best-effort teardown of a shell it is abandoning:
// a Docker exec can neither be re-attached nor stopped any other way.
ExecStart(ctx context.Context, execID string, options client.ExecStartOptions) (client.ExecStartResult, error)
ExecInspect(ctx context.Context, execID string, options client.ExecInspectOptions) (client.ExecInspectResult, error)
// ExecResize resizes the TTY of a running exec, which is what backs the
// interactive terminal's window-size changes.
ExecResize(ctx context.Context, execID string, options client.ExecResizeOptions) (client.ExecResizeResult, error)
// ContainerStatPath is the one archive endpoint this adapter uses, and only
// against the activity marker's fixed path. The copy endpoints are
// deliberately absent: they run as root and resolve symlinks, so exposing
// them to caller-supplied paths would undo the file operations' reliance on
// the kernel for access control (see DockerRemoteClient.WriteFile).
ContainerStatPath(
ctx context.Context, containerID string, options client.ContainerStatPathOptions,
) (client.ContainerStatPathResult, error)
ImageInspect(
ctx context.Context, imageID string, opts ...client.ImageInspectOption,
) (client.ImageInspectResult, error)
ImagePull(ctx context.Context, refStr string, options client.ImagePullOptions) (client.ImagePullResponse, error)
ImageList(ctx context.Context, options client.ImageListOptions) (client.ImageListResult, error)
ImageRemove(
ctx context.Context, imageID string, options client.ImageRemoveOptions,
) (client.ImageRemoveResult, error)
// ContainerCommit is a long call (a large skill image can take well
// over the short RPC budget), so the timeout wrapper leaves it on the
// caller's context the way it does ImagePull.
ContainerCommit(
ctx context.Context, containerID string, options client.ContainerCommitOptions,
) (client.ContainerCommitResult, error)
}
var _ dockerEngineAPI = (*client.Client)(nil)
// DefaultDockerHost is the last-resort daemon endpoint when the config, the
// DOCKER_HOST environment variable, and the current docker CLI context are
// all empty. Linux installs typically expose this socket; macOS tools such
// as Colima do not.
const DefaultDockerHost = "unix:///var/run/docker.sock"
// DefaultDockerHTTPTimeout bounds a single short Engine API call (ping, create,
// inspect, list, exec create/inspect). Streaming and long storage calls —
// image pull, image remove with prune, commit, exec hijack, archive copy —
// use the caller's context instead, because a 30s deadline would kill them
// mid-body.
const DefaultDockerHTTPTimeout = 30 * time.Second
// DefaultDockerIdleTTL is how long a session container may go without an exec
// before the idle sweep reclaims it. The daemon has no TTL of its own, so this
// is the only thing standing between an abandoned session and a container that
// lives until the host runs out of memory.
const DefaultDockerIdleTTL = 30 * time.Minute
// DefaultDockerMemoryLimit / DefaultDockerCPULimit / DefaultDockerPidsLimit are
// the per-sandbox resource ceilings applied when a config names none. They are
// deliberately larger than the stateless backend's old 256MB/1CPU: a session
// container hosts a whole turn's work (package installs, data processing),
// not one short script.
const (
DefaultDockerMemoryLimit int64 = 2 * 1024 * 1024 * 1024
DefaultDockerCPULimit = 2.0
DefaultDockerPidsLimit int64 = 512
)
// dockerSandboxCapabilities are granted back after CapDrop=ALL.
//
// Everything Docker grants by default that a sandbox does not need is left
// dropped (NET_RAW, NET_BIND_SERVICE, MKNOD, SYS_CHROOT, AUDIT_WRITE,
// SETPCAP, SETFCAP). What remains is what a root-run package installer needs:
// CHOWN/DAC_OVERRIDE/FOWNER/FSETID for writing into image-owned directories
// and fixing up ownership, SETUID/SETGID because apt and pip drop privileges
// while unpacking, KILL so a supervisor can stop its own children.
var dockerSandboxCapabilities = []string{
"CHOWN", "DAC_OVERRIDE", "FOWNER", "FSETID", "SETGID", "SETUID", "KILL",
}
// dockerEngineClientPool hands out one shared client per daemon endpoint.
type dockerEngineClientPool struct {
mu sync.Mutex
clients map[string]*client.Client
}
// sharedDockerEngineClients is process-wide on purpose: two tenant configs
// pointing at the same daemon should share one connection pool, and the check
// endpoint builds throwaway configs that must not each open their own.
var sharedDockerEngineClients = &dockerEngineClientPool{
clients: make(map[string]*client.Client),
}
// dockerEndpoint is the identity of a daemon connection. Two configs with
// equal endpoints may share a client.
type dockerEndpoint struct {
Host string
// TLSCertPath is a directory holding ca.pem / cert.pem / key.pem, the
// layout Docker's own DOCKER_CERT_PATH uses. Empty means plain HTTP,
// which is only acceptable for a local unix socket.
TLSCertPath string
// AllowPrivate mirrors the config's outbound policy. It is part of the
// endpoint identity because it changes the dialer this client installs:
// sharing a pooled client between a permissive and a restrictive config
// would hand the restrictive one a connection it is not allowed to make.
AllowPrivate bool
Timeout time.Duration
}
func (e dockerEndpoint) key() string {
// Timeout is applied per RPC, not on the HTTP client, so two configs
// that differ only in HTTP timeout still share one connection pool.
return fmt.Sprintf("%s|%s|%t", e.Host, e.TLSCertPath, e.AllowPrivate)
}
// get returns the shared client for endpoint, building it on first use.
func (p *dockerEngineClientPool) get(endpoint dockerEndpoint) (*client.Client, error) {
key := endpoint.key()
p.mu.Lock()
defer p.mu.Unlock()
if existing, ok := p.clients[key]; ok {
return existing, nil
}
built, err := newDockerEngineClient(endpoint)
if err != nil {
return nil, err
}
p.clients[key] = built
return built, nil
}
// newDockerEngineClient builds a moby client for one endpoint.
//
// API version negotiation is deliberately not performed here: it costs a
// round-trip against a daemon that may be down, and it would happen inside
// whatever request first touches the pool. The client's default version is
// negotiated lazily by the moby client itself on the first call.
func newDockerEngineClient(endpoint dockerEndpoint) (*client.Client, error) {
host := strings.TrimSpace(endpoint.Host)
if host == "" {
host = DetectLocalDockerHost()
}
// Do not set http.Client.Timeout. It covers the entire response body,
// so a cold image pull or a file copy longer than the RPC budget is
// killed mid-stream. Short calls are bounded by withDockerRPCTimeout;
// pulls, exec hijacks and archive streams honour the caller's context.
opts := []client.Opt{
client.WithHost(host),
}
if endpoint.TLSCertPath != "" {
// Certificates stay on the application host rather than in the
// workspace config: they are deployment infrastructure, and keeping
// them out of the database keeps them out of backups and API
// responses. The daemon certificate is always verified — a remote
// daemon accepts container creation, so an unauthenticated peer on
// that socket is a root shell on the sandbox host.
certPath := endpoint.TLSCertPath
opts = append(opts, client.WithTLSClientConfig(
filepath.Join(certPath, "ca.pem"),
filepath.Join(certPath, "cert.pem"),
filepath.Join(certPath, "key.pem"),
))
}
// A TCP daemon address is a tenant-supplied endpoint like any other, so it
// gets the same dial-time guard every other backend gets: saving the config
// validates the address it was given, but a hostname can resolve to a public
// address then and to 169.254.169.254 when the connection is actually made.
// Reaching a private daemon stays possible through the config's own
// "allow private endpoints" switch. Must come after WithHost, which
// installs its own dialer.
if dockerHostNeedsDialGuard(host) {
opts = append(opts, client.WithDialContext(
GuardedDialContext(OutboundURLPolicy{AllowPrivate: endpoint.AllowPrivate}),
))
}
built, err := client.New(opts...)
if err != nil {
return nil, fmt.Errorf("sandbox: build docker client for %s: %w", host, err)
}
return built, nil
}
// dockerHostNeedsDialGuard reports whether host is a network endpoint whose
// dials must pass the outbound policy. Unix sockets are local to the Academy
// process and carry no address to check.
func dockerHostNeedsDialGuard(host string) bool {
scheme, _, found := strings.Cut(strings.TrimSpace(host), "://")
if !found {
return false
}
switch strings.ToLower(scheme) {
case "tcp", "http", "https":
return true
default:
return false
}
}
// ValidateDockerHost checks a daemon endpoint before it is stored or dialled.
//
// A TCP endpoint gets the same outbound treatment as any other workspace-
// supplied URL: a daemon socket accepts container creation, so an admin who
// can point it anywhere can make Academy talk to an arbitrary internal
// service. Unix sockets are local by definition and only have to be absolute.
func ValidateDockerHost(host string, allowPrivate bool) error {
trimmed := strings.TrimSpace(host)
if trimmed == "" {
return nil
}
scheme, address, found := strings.Cut(trimmed, "://")
if !found {
return fmt.Errorf(
"sandbox: docker host %q must include a scheme (unix:// or tcp://)", host)
}
switch strings.ToLower(scheme) {
case "unix":
if !strings.HasPrefix(address, "/") {
return fmt.Errorf("sandbox: docker unix socket path %q must be absolute", address)
}
return nil
case "tcp", "http", "https":
// The guard speaks HTTP; the daemon's TCP endpoint is an HTTP
// endpoint, so the check is the same one every other backend gets.
return ValidateOutboundURLWithPolicy(
"http://"+address, OutboundURLPolicy{AllowPrivate: allowPrivate},
)
default:
return fmt.Errorf("sandbox: unsupported docker host scheme %q", scheme)
}
}
// ValidateDockerRemoteTLS requires client certificates for a TCP daemon.
// A remote Engine API that accepts container creation is a root shell on
// that host; plaintext tcp://2375 is not an acceptable way to reach it.
// Unix sockets are local to the Academy process and do not use TLS.
func ValidateDockerRemoteTLS(host, tlsCertPath string) error {
trimmed := strings.TrimSpace(host)
if trimmed == "" {
return nil
}
scheme, _, found := strings.Cut(trimmed, "://")
if !found {
return nil
}
switch strings.ToLower(scheme) {
case "tcp", "http", "https":
if strings.TrimSpace(tlsCertPath) == "" {
return fmt.Errorf(
"sandbox: remote docker host %q requires a TLS certificate directory", host)
}
}
return nil
}
// ValidateDockerNetworkMode allows only bridge (egress) and none (no egress).
//
// host and container: modes share another namespace outright, which would put
// sandbox code on the Academy host's or a sibling container's network. A
// user-defined network name is refused for the weaker but equally real version
// of the same problem: the usual deployment reaches its daemon through the
// mounted docker.sock, so naming the deployment's own compose network would
// place a sandbox on the same L3 network as Postgres and Redis. Only the
// operator can judge what a given named network exposes, and this value is set
// per workspace config, so it is not theirs to choose.
func ValidateDockerNetworkMode(mode string) error {
trimmed := strings.TrimSpace(mode)
if trimmed == "" {
return nil
}
switch strings.ToLower(trimmed) {
case "bridge", "none":
return nil
}
return fmt.Errorf(
"sandbox: docker network mode %q is not allowed; use \"bridge\" or \"none\"",
mode)
}
// dockerErrorKind classifies an Engine API error. The moby client tags its
// errors with containerd's errdefs, which is a far more reliable signal than
// the message text.
func dockerErrorKind(op string, err error) RemoteErrorKind {
switch {
case err == nil:
return ""
case errors.Is(err, context.DeadlineExceeded), cerrdefs.IsDeadlineExceeded(err):
return RemoteErrorKindTimeout
case cerrdefs.IsNotFound(err):
// A missing image on create is a bad template, not a vanished sandbox:
// classifying it as NotFound would tell the lifecycle it may rebind.
if op == "Create" {
return RemoteErrorKindInvalidRequest
}
return RemoteErrorKindNotFound
case cerrdefs.IsUnauthorized(err), cerrdefs.IsPermissionDenied(err):
return RemoteErrorKindAuthentication
case cerrdefs.IsInvalidArgument(err):
return RemoteErrorKindInvalidRequest
case cerrdefs.IsNotImplemented(err):
return RemoteErrorKindUnsupported
case cerrdefs.IsConflict(err), cerrdefs.IsAlreadyExists(err):
return RemoteErrorKindConflict
case cerrdefs.IsResourceExhausted(err):
return RemoteErrorKindCapacity
case cerrdefs.IsUnavailable(err), client.IsErrConnectionFailed(err):
return RemoteErrorKindUnavailable
default:
return RemoteErrorKindInternal
}
}
// dockerError wraps an Engine API error as a RemoteError.
func dockerError(op string, err error) error {
if err == nil {
return nil
}
var existing *RemoteError
if errors.As(err, &existing) {
return err
}
return &RemoteError{
Kind: snapshotDeleteKind(op, dockerErrorKind(op, err), err.Error()),
Provider: SandboxTypeDocker,
Op: op,
Message: err.Error(),
Cause: err,
}
}
// dockerInvalidRequest reports a caller-side mistake that never reached the
// daemon (an unusable path, an unsupported request shape).
func dockerInvalidRequest(op, message string) error {
return &RemoteError{
Kind: RemoteErrorKindInvalidRequest,
Provider: SandboxTypeDocker,
Op: op,
Message: message,
}
}
// awaitImagePull waits for a pull to finish. The daemon only performs the
// transfer while its progress stream is being consumed, so a caller that
// closes the body early aborts the pull.
func awaitImagePull(ctx context.Context, body client.ImagePullResponse) error {
if body == nil {
return nil
}
defer func() { _ = body.Close() }()
return body.Wait(ctx)
}
// dockerStateOf normalizes a container state string. "exited" is deliberately
// NOT terminal: a stopped container keeps its filesystem and Connect restarts
// it, which is the closest Docker gets to E2B's pause + auto-resume.
func dockerStateOf(status container.ContainerState) RemoteSandboxState {
switch strings.ToLower(strings.TrimSpace(string(status))) {
case "running":
return RemoteStateRunning
case "paused", "exited", "created":
return RemoteStatePaused
case "restarting", "removing":
return RemoteStateTransitioning
case "dead":
return RemoteStateTerminal
case "":
return RemoteStateUnknown
default:
return RemoteStateUnknown
}
}
// dockerContainerLabels projects sandbox metadata onto container labels and
// stamps the ownership marker every sweep relies on.
func dockerContainerLabels(metadata map[string]string) map[string]string {
labels := make(map[string]string, len(metadata)+1)
for key, value := range metadata {
labels[key] = value
}
labels[dockerManagedLabel] = "true"
return labels
}
// dockerSandboxMetadata is the inverse of dockerContainerLabels: it strips the
// ownership marker so callers see exactly the metadata they supplied.
func dockerSandboxMetadata(labels map[string]string) map[string]string {
if labels == nil {
return nil
}
metadata := make(map[string]string, len(labels))
for key, value := range labels {
if key == dockerManagedLabel {
continue
}
metadata[key] = value
}
return metadata
}
// dockerManagedLabel marks every container this backend creates. Sweeps filter
// on it so a Academy deployment sharing a daemon with other workloads can
// never delete a container it does not own.
const dockerManagedLabel = "com.academy.sandbox.managed"
// dockerContainerStartedAt parses the daemon's RFC3339Nano timestamps, which
// are the zero value string "0001-01-01T00:00:00Z" when unset.
func dockerContainerStartedAt(state *container.State) time.Time {
if state == nil {
return time.Time{}
}
parsed, err := time.Parse(time.RFC3339Nano, state.StartedAt)
if err != nil {
return time.Time{}
}
return parsed.UTC()
}
+100
View File
@@ -0,0 +1,100 @@
package sandbox
import (
"encoding/json"
"os"
"path/filepath"
"strings"
)
// DetectLocalDockerHost returns the daemon endpoint the Docker CLI would use
// on this machine when the workspace config leaves the host blank: DOCKER_HOST
// first, then the current docker context, then DefaultDockerHost.
//
// /var/run/docker.sock is the Linux default and is often absent on macOS
// (Colima, Docker Desktop, OrbStack each expose a socket under $HOME). An
// operator who can run `docker ps` should not have to copy that path into
// the settings form.
func DetectLocalDockerHost() string {
if host := strings.TrimSpace(os.Getenv("DOCKER_HOST")); host != "" {
return host
}
if host := dockerCLIContextHost(); host != "" {
return host
}
return DefaultDockerHost
}
func dockerCLIContextHost() string {
configDir := strings.TrimSpace(os.Getenv("DOCKER_CONFIG"))
if configDir == "" {
home, err := os.UserHomeDir()
if err != nil || home == "" {
return ""
}
configDir = filepath.Join(home, ".docker")
}
name := strings.TrimSpace(os.Getenv("DOCKER_CONTEXT"))
if name == "" {
name = dockerCurrentContextName(configDir)
}
if name == "" || name == "default" {
return ""
}
entries, err := os.ReadDir(filepath.Join(configDir, "contexts", "meta"))
if err != nil {
return ""
}
for _, entry := range entries {
if !entry.IsDir() {
continue
}
host := dockerContextHost(
filepath.Join(configDir, "contexts", "meta", entry.Name(), "meta.json"),
name,
)
if host != "" {
return host
}
}
return ""
}
func dockerCurrentContextName(configDir string) string {
body, err := os.ReadFile(filepath.Join(configDir, "config.json"))
if err != nil {
return ""
}
var parsed struct {
CurrentContext string `json:"currentContext"`
}
if err := json.Unmarshal(body, &parsed); err != nil {
return ""
}
return strings.TrimSpace(parsed.CurrentContext)
}
func dockerContextHost(metaPath, wantName string) string {
body, err := os.ReadFile(metaPath)
if err != nil {
return ""
}
var parsed struct {
Name string `json:"Name"`
Endpoints map[string]struct {
Host string `json:"Host"`
} `json:"Endpoints"`
}
if err := json.Unmarshal(body, &parsed); err != nil {
return ""
}
if parsed.Name != wantName {
return ""
}
if parsed.Endpoints == nil {
return ""
}
return strings.TrimSpace(parsed.Endpoints["docker"].Host)
}
+47
View File
@@ -0,0 +1,47 @@
package sandbox
import (
"encoding/json"
"os"
"path/filepath"
"testing"
"github.com/stretchr/testify/require"
)
func TestDetectLocalDockerHostPrefersEnv(t *testing.T) {
t.Setenv("DOCKER_HOST", "unix:///tmp/from-env.sock")
t.Setenv("DOCKER_CONTEXT", "colima")
require.Equal(t, "unix:///tmp/from-env.sock", DetectLocalDockerHost())
}
func TestDetectLocalDockerHostUsesCurrentContext(t *testing.T) {
t.Setenv("DOCKER_HOST", "")
t.Setenv("DOCKER_CONTEXT", "")
dir := t.TempDir()
t.Setenv("DOCKER_CONFIG", dir)
require.NoError(t, os.MkdirAll(filepath.Join(dir, "contexts", "meta", "abc"), 0o755))
require.NoError(t, os.WriteFile(filepath.Join(dir, "config.json"), []byte(
`{"currentContext":"colima"}`,
), 0o644))
meta, err := json.Marshal(map[string]any{
"Name": "colima",
"Endpoints": map[string]any{
"docker": map[string]any{"Host": "unix:///tmp/colima.sock"},
},
})
require.NoError(t, err)
require.NoError(t, os.WriteFile(
filepath.Join(dir, "contexts", "meta", "abc", "meta.json"), meta, 0o644,
))
require.Equal(t, "unix:///tmp/colima.sock", DetectLocalDockerHost())
}
func TestDetectLocalDockerHostFallsBackToDefault(t *testing.T) {
t.Setenv("DOCKER_HOST", "")
t.Setenv("DOCKER_CONTEXT", "")
t.Setenv("DOCKER_CONFIG", t.TempDir())
require.Equal(t, DefaultDockerHost, DetectLocalDockerHost())
}
+207
View File
@@ -0,0 +1,207 @@
// Idle reclamation for the docker backend.
//
// Every other backend gets this for free. Cube and E2B are told an idle
// timeout at creation and the provider pauses or kills the sandbox when it
// elapses, which is why SessionBoundManager never reaps anything itself. The
// Docker daemon has no such concept: a container runs until something stops
// it. Without a sweep, one abandoned session pins its memory and CPU share on
// the host forever.
//
// The sweep needs to know when a sandbox was last used, and Docker exposes no
// exec timestamps. Labels cannot help either — they are immutable after
// create. So each exec touches an activity marker file inside the container
// (folded into the exec wrapper, costing no extra round-trip), and the sweep
// reads its mtime with a single HEAD /archive call per container.
//
// Deleting an idle container needs no coordination with the binding store: the
// lifecycle already treats a sandbox the provider no longer has as replaceable
// (see CanReplaceRemoteBinding), which is exactly how an E2B sandbox reaped by
// its own TTL is handled.
package sandbox
import (
"context"
"log"
"strconv"
"sync"
"time"
"academy/internal/logger"
"github.com/moby/moby/client"
)
// dockerIdleTTLLabel records the TTL each container was created with, so a
// sweep triggered by one workspace config never applies its own TTL to a
// container belonging to another.
const dockerIdleTTLLabel = "com.academy.sandbox.idle-ttl-seconds"
// dockerSweepMinInterval bounds how often one daemon is swept, no matter how
// many requests trigger it. Sweeping is a list plus one stat per container;
// cheap, but not free enough to run on every execution.
const dockerSweepMinInterval = time.Minute
// dockerSweepBudget bounds one sweep so a wedged daemon cannot leave a
// goroutine hanging around forever.
const dockerSweepBudget = 2 * time.Minute
// dockerSweepThrottle records the last sweep per daemon endpoint. It is
// process-wide because the adapter is rebuilt per request; per-instance state
// would throttle nothing.
var dockerSweepThrottle = struct {
mu sync.Mutex
last map[string]time.Time
}{last: make(map[string]time.Time)}
// dockerIdleSweeper reclaims containers that have not executed anything for
// longer than their TTL.
type dockerIdleSweeper struct {
client *DockerRemoteClient
ttl time.Duration
// now is injected by tests.
now func() time.Time
}
func newDockerIdleSweeper(cli *DockerRemoteClient, ttl time.Duration) *dockerIdleSweeper {
return &dockerIdleSweeper{client: cli, ttl: ttl, now: time.Now}
}
// trigger runs a sweep in the background unless one ran recently. It detaches
// from the caller's context so finishing the request does not abort the sweep,
// and it never reports failures upward: reclaiming storage must not turn a
// working execution into an error.
func (s *dockerIdleSweeper) trigger(ctx context.Context) {
if s == nil || s.client == nil {
return
}
if !s.claimSweep() {
return
}
go func() {
// Drop the chat-trace parent: Engine API list/stat/delete from a
// sweep must not appear as siblings of agent.round after the tool
// that triggered the sweep has already finished its span.
sweepCtx, cancel := context.WithTimeout(
logger.CloneContextWithoutTrace(ctx), dockerSweepBudget,
)
defer cancel()
if reclaimed, err := s.sweep(sweepCtx); err != nil {
log.Printf("[sandbox] docker idle sweep failed: %v", err)
} else if reclaimed > 0 {
log.Printf("[sandbox] docker idle sweep reclaimed %d container(s)", reclaimed)
}
}()
}
// claimSweep reports whether this caller won the right to sweep now.
func (s *dockerIdleSweeper) claimSweep() bool {
key := s.client.settings.Endpoint.key()
now := s.now()
dockerSweepThrottle.mu.Lock()
defer dockerSweepThrottle.mu.Unlock()
if last, ok := dockerSweepThrottle.last[key]; ok &&
now.Sub(last) < dockerSweepMinInterval {
return false
}
dockerSweepThrottle.last[key] = now
return true
}
// sweep deletes every managed container idle beyond its own TTL and reports
// how many went away.
func (s *dockerIdleSweeper) sweep(ctx context.Context) (int, error) {
summaries, err := s.client.List(ctx, RemoteListFilter{})
if err != nil {
return 0, err
}
reclaimed := 0
for _, summary := range summaries {
select {
case <-ctx.Done():
return reclaimed, ctx.Err()
default:
}
if !s.isIdle(ctx, summary) {
continue
}
// Re-check immediately before deleting. Listing every container and
// stat'ing each one takes long enough on a busy daemon that a session
// can be resumed in between, and deleting it then destroys a sandbox
// the user is actively working in.
if !s.isIdle(ctx, summary) {
continue
}
if err := s.client.Delete(ctx, summary.ID); err != nil {
// One undeletable container must not stop the sweep; the next
// pass will try again.
log.Printf("[sandbox] docker idle sweep: delete %s: %v", summary.ID, err)
continue
}
reclaimed++
}
return reclaimed, nil
}
// isIdle decides whether one container has gone unused for longer than the
// TTL it was created with.
func (s *dockerIdleSweeper) isIdle(ctx context.Context, summary RemoteSandboxSummary) bool {
ttl := s.ttlFor(summary)
if ttl <= 0 {
return false
}
lastUsed := s.lastActivity(ctx, summary)
if lastUsed.IsZero() {
// Neither a marker nor a creation timestamp: treating that as idle
// would risk deleting a sandbox that is merely unreadable right now.
return false
}
return s.now().UTC().Sub(lastUsed) > ttl
}
// ttlFor prefers the TTL stamped on the container at creation over this
// client's own configuration.
func (s *dockerIdleSweeper) ttlFor(summary RemoteSandboxSummary) time.Duration {
if raw, ok := summary.Metadata[dockerIdleTTLLabel]; ok {
if seconds, err := strconv.Atoi(raw); err == nil {
return time.Duration(seconds) * time.Second
}
}
return s.ttl
}
// lastActivity returns when the container last ran a command, falling back to
// when it started for a sandbox that has not executed anything yet.
//
// The marker lives inside the container and has to be writable by the account
// the execs run as, so its mtime is attacker-influenced: a script can
// `touch -d` it. A timestamp in the future is the one form of that which
// would disable reclamation permanently, so it is refused outright and the
// container falls back to its start time. Backdating only makes a sandbox look
// idle sooner, which costs the container that did it and nothing else.
func (s *dockerIdleSweeper) lastActivity(
ctx context.Context,
summary RemoteSandboxSummary,
) time.Time {
stat, err := s.client.api.ContainerStatPath(ctx, summary.ID,
client.ContainerStatPathOptions{Path: dockerActivityMarker})
if err == nil && !stat.Stat.Mtime.IsZero() {
marker := stat.Stat.Mtime.UTC()
if marker.After(s.now().UTC().Add(dockerActivityClockSkew)) {
log.Printf(
"[sandbox] docker idle sweep: container %s reports activity at %s, "+
"which is in the future; falling back to its start time",
summary.ID, marker.Format(time.RFC3339),
)
} else {
return marker
}
}
return summary.StartedAt.UTC()
}
// dockerActivityClockSkew is how far ahead of Academy the daemon's clock may
// run before a marker is treated as forged. The marker is stamped by the
// daemon host while the comparison happens here, and the two are not
// necessarily the same machine.
const dockerActivityClockSkew = 2 * time.Minute
@@ -0,0 +1,206 @@
package sandbox
import (
"context"
"testing"
"time"
"github.com/moby/moby/api/types/container"
"github.com/stretchr/testify/require"
)
// newSweeperFixture wires a sweeper over a fake daemon holding the given
// containers, with the activity marker of each one set from markers.
func newSweeperFixture(
t *testing.T,
ttl time.Duration,
now time.Time,
containers []container.Summary,
) (*dockerIdleSweeper, *fakeDockerEngine) {
t.Helper()
engine := newFakeDockerEngine()
engine.list = containers
docker := newTestDockerClient(t, engine)
sweeper := newDockerIdleSweeper(docker, ttl)
sweeper.now = func() time.Time { return now }
return sweeper, engine
}
func TestDockerIdleSweeperReclaimsOnlyIdleContainers(t *testing.T) {
now := time.Now().UTC()
sweeper, engine := newSweeperFixture(t, 30*time.Minute, now, []container.Summary{
{
ID: "busy", State: "running", Created: now.Add(-4 * time.Hour).Unix(),
Labels: map[string]string{dockerManagedLabel: "true"},
},
{
ID: "idle", State: "running", Created: now.Add(-4 * time.Hour).Unix(),
Labels: map[string]string{dockerManagedLabel: "true"},
},
})
// The marker is what every exec touches; its mtime is the only record of
// when a sandbox was last used.
engine.statResult[dockerActivityMarker] = container.PathStat{Mtime: now.Add(-2 * time.Minute)}
reclaimed, err := sweeper.sweep(context.Background())
require.NoError(t, err)
require.Zero(t, reclaimed, "a recently used sandbox must survive")
require.Empty(t, engine.removed)
engine.statResult[dockerActivityMarker] = container.PathStat{Mtime: now.Add(-90 * time.Minute)}
reclaimed, err = sweeper.sweep(context.Background())
require.NoError(t, err)
require.Equal(t, 2, reclaimed)
require.ElementsMatch(t, []string{"busy", "idle"}, engine.removed)
}
// A sandbox that has never executed anything has no marker, so its creation
// time decides. Without this a freshly created container would look infinitely
// idle and be deleted out from under the session that just created it.
func TestDockerIdleSweeperFallsBackToCreationTime(t *testing.T) {
now := time.Now().UTC()
sweeper, engine := newSweeperFixture(t, 30*time.Minute, now, []container.Summary{
{
ID: "fresh", State: "running", Created: now.Add(-time.Minute).Unix(),
Labels: map[string]string{dockerManagedLabel: "true"},
},
})
reclaimed, err := sweeper.sweep(context.Background())
require.NoError(t, err)
require.Zero(t, reclaimed)
require.Empty(t, engine.removed)
}
// The marker has to be writable by the account the execs run as, so a script
// can backdate or postdate it. Postdating is the dangerous direction: a
// single `touch -d 2099-01-01` would otherwise exempt the container from
// reclamation forever.
func TestDockerIdleSweeperRejectsFutureActivityMarker(t *testing.T) {
now := time.Now().UTC()
sweeper, engine := newSweeperFixture(t, 30*time.Minute, now, []container.Summary{
{
ID: "forged", State: "running", Created: now.Add(-4 * time.Hour).Unix(),
Labels: map[string]string{dockerManagedLabel: "true"},
},
})
engine.statResult[dockerActivityMarker] = container.PathStat{
Mtime: now.Add(100 * 365 * 24 * time.Hour),
}
reclaimed, err := sweeper.sweep(context.Background())
require.NoError(t, err)
require.Equal(t, 1, reclaimed,
"a forged future marker must fall back to the container's start time")
require.Equal(t, []string{"forged"}, engine.removed)
}
// A daemon on another host may run slightly ahead of Academy. That must not be
// mistaken for tampering, or every sandbox on that daemon would be judged by
// its start time alone and reclaimed mid-session.
func TestDockerIdleSweeperToleratesSmallClockSkew(t *testing.T) {
now := time.Now().UTC()
sweeper, engine := newSweeperFixture(t, 30*time.Minute, now, []container.Summary{
{
ID: "skewed", State: "running", Created: now.Add(-4 * time.Hour).Unix(),
Labels: map[string]string{dockerManagedLabel: "true"},
},
})
engine.statResult[dockerActivityMarker] = container.PathStat{
Mtime: now.Add(dockerActivityClockSkew / 2),
}
reclaimed, err := sweeper.sweep(context.Background())
require.NoError(t, err)
require.Zero(t, reclaimed)
require.Empty(t, engine.removed)
}
// Listing plus one stat per container is slow enough on a busy daemon that a
// session can be resumed in between. Deleting then would destroy a sandbox the
// user is working in, so the decision is re-taken right before the delete.
func TestDockerIdleSweeperRechecksActivityBeforeDeleting(t *testing.T) {
now := time.Now().UTC()
sweeper, engine := newSweeperFixture(t, 30*time.Minute, now, []container.Summary{
{
ID: "resumed", State: "running", Created: now.Add(-4 * time.Hour).Unix(),
Labels: map[string]string{dockerManagedLabel: "true"},
},
})
calls := 0
engine.statHook = func(path string) (container.PathStat, bool) {
if path != dockerActivityMarker {
return container.PathStat{}, false
}
calls++
if calls == 1 {
return container.PathStat{Mtime: now.Add(-2 * time.Hour)}, true
}
return container.PathStat{Mtime: now.Add(-time.Second)}, true
}
reclaimed, err := sweeper.sweep(context.Background())
require.NoError(t, err)
require.Zero(t, reclaimed)
require.Empty(t, engine.removed, "a sandbox used since the listing must survive")
require.Equal(t, 2, calls)
}
// Each container carries the TTL it was created with, so a sweep triggered by
// one workspace config cannot apply its own TTL to another config's sandboxes.
func TestDockerIdleSweeperHonoursPerContainerTTL(t *testing.T) {
now := time.Now().UTC()
sweeper, engine := newSweeperFixture(t, time.Minute, now, []container.Summary{
{
ID: "long-ttl", State: "running", Created: now.Add(-2 * time.Hour).Unix(),
Labels: map[string]string{
dockerManagedLabel: "true",
dockerIdleTTLLabel: "86400",
},
},
})
engine.statResult[dockerActivityMarker] = container.PathStat{Mtime: now.Add(-2 * time.Hour)}
reclaimed, err := sweeper.sweep(context.Background())
require.NoError(t, err)
require.Zero(t, reclaimed)
require.Empty(t, engine.removed)
}
// The sweep runs off the back of ordinary requests, so it must not turn into a
// list-plus-stat storm when a workspace is busy.
func TestDockerIdleSweeperThrottlesPerDaemon(t *testing.T) {
now := time.Now().UTC()
sweeper, _ := newSweeperFixture(t, time.Minute, now, nil)
dockerSweepThrottle.mu.Lock()
delete(dockerSweepThrottle.last, sweeper.client.settings.Endpoint.key())
dockerSweepThrottle.mu.Unlock()
require.True(t, sweeper.claimSweep(), "the first caller sweeps")
require.False(t, sweeper.claimSweep(), "a second caller in the same minute does not")
sweeper.now = func() time.Time { return now.Add(2 * dockerSweepMinInterval) }
require.True(t, sweeper.claimSweep(), "the throttle expires")
}
// A container the daemon refuses to delete must not abort the pass: the rest
// of the idle set still has to be reclaimed.
func TestDockerIdleSweeperContinuesAfterDeleteFailure(t *testing.T) {
now := time.Now().UTC()
sweeper, engine := newSweeperFixture(t, time.Minute, now, []container.Summary{
{
ID: "wedged", State: "running", Created: now.Add(-2 * time.Hour).Unix(),
Labels: map[string]string{dockerManagedLabel: "true"},
},
{
ID: "reclaimable", State: "running", Created: now.Add(-2 * time.Hour).Unix(),
Labels: map[string]string{dockerManagedLabel: "true"},
},
})
engine.removeErr = context.DeadlineExceeded
reclaimed, err := sweeper.sweep(context.Background())
require.NoError(t, err)
require.Zero(t, reclaimed)
require.Len(t, engine.removed, 2, "every candidate is attempted")
}
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+170
View File
@@ -0,0 +1,170 @@
package sandbox
import (
"context"
"time"
"github.com/moby/moby/client"
)
// withDockerRPCTimeout bounds short Engine API calls. Streaming and long
// storage methods (pull, commit, image remove) are left on the caller's
// context: http.Client.Timeout (and a blanket RPC deadline) would abort them
// after the budget, which is exactly how the previous 30s client timeout
// broke cold image pulls.
func withDockerRPCTimeout(inner dockerEngineAPI, timeout time.Duration) dockerEngineAPI {
if inner == nil || timeout <= 0 {
return inner
}
return &dockerRPCTimeoutAPI{inner: inner, timeout: timeout}
}
type dockerRPCTimeoutAPI struct {
inner dockerEngineAPI
timeout time.Duration
}
func (a *dockerRPCTimeoutAPI) rpcCtx(ctx context.Context) (context.Context, context.CancelFunc) {
return context.WithTimeout(ctx, a.timeout)
}
func (a *dockerRPCTimeoutAPI) Ping(
ctx context.Context, options client.PingOptions,
) (client.PingResult, error) {
rpcCtx, cancel := a.rpcCtx(ctx)
defer cancel()
return a.inner.Ping(rpcCtx, options)
}
func (a *dockerRPCTimeoutAPI) ContainerCreate(
ctx context.Context, options client.ContainerCreateOptions,
) (client.ContainerCreateResult, error) {
rpcCtx, cancel := a.rpcCtx(ctx)
defer cancel()
return a.inner.ContainerCreate(rpcCtx, options)
}
func (a *dockerRPCTimeoutAPI) ContainerStart(
ctx context.Context, containerID string, options client.ContainerStartOptions,
) (client.ContainerStartResult, error) {
rpcCtx, cancel := a.rpcCtx(ctx)
defer cancel()
return a.inner.ContainerStart(rpcCtx, containerID, options)
}
func (a *dockerRPCTimeoutAPI) ContainerUnpause(
ctx context.Context, containerID string, options client.ContainerUnpauseOptions,
) (client.ContainerUnpauseResult, error) {
rpcCtx, cancel := a.rpcCtx(ctx)
defer cancel()
return a.inner.ContainerUnpause(rpcCtx, containerID, options)
}
func (a *dockerRPCTimeoutAPI) ContainerInspect(
ctx context.Context, containerID string, options client.ContainerInspectOptions,
) (client.ContainerInspectResult, error) {
rpcCtx, cancel := a.rpcCtx(ctx)
defer cancel()
return a.inner.ContainerInspect(rpcCtx, containerID, options)
}
func (a *dockerRPCTimeoutAPI) ContainerList(
ctx context.Context, options client.ContainerListOptions,
) (client.ContainerListResult, error) {
rpcCtx, cancel := a.rpcCtx(ctx)
defer cancel()
return a.inner.ContainerList(rpcCtx, options)
}
func (a *dockerRPCTimeoutAPI) ContainerRemove(
ctx context.Context, containerID string, options client.ContainerRemoveOptions,
) (client.ContainerRemoveResult, error) {
rpcCtx, cancel := a.rpcCtx(ctx)
defer cancel()
return a.inner.ContainerRemove(rpcCtx, containerID, options)
}
func (a *dockerRPCTimeoutAPI) ExecCreate(
ctx context.Context, containerID string, options client.ExecCreateOptions,
) (client.ExecCreateResult, error) {
rpcCtx, cancel := a.rpcCtx(ctx)
defer cancel()
return a.inner.ExecCreate(rpcCtx, containerID, options)
}
func (a *dockerRPCTimeoutAPI) ExecAttach(
ctx context.Context, execID string, options client.ExecAttachOptions,
) (client.ExecAttachResult, error) {
return a.inner.ExecAttach(ctx, execID, options)
}
func (a *dockerRPCTimeoutAPI) ExecStart(
ctx context.Context, execID string, options client.ExecStartOptions,
) (client.ExecStartResult, error) {
rpcCtx, cancel := a.rpcCtx(ctx)
defer cancel()
return a.inner.ExecStart(rpcCtx, execID, options)
}
func (a *dockerRPCTimeoutAPI) ExecInspect(
ctx context.Context, execID string, options client.ExecInspectOptions,
) (client.ExecInspectResult, error) {
rpcCtx, cancel := a.rpcCtx(ctx)
defer cancel()
return a.inner.ExecInspect(rpcCtx, execID, options)
}
func (a *dockerRPCTimeoutAPI) ExecResize(
ctx context.Context, execID string, options client.ExecResizeOptions,
) (client.ExecResizeResult, error) {
rpcCtx, cancel := a.rpcCtx(ctx)
defer cancel()
return a.inner.ExecResize(rpcCtx, execID, options)
}
func (a *dockerRPCTimeoutAPI) ContainerStatPath(
ctx context.Context, containerID string, options client.ContainerStatPathOptions,
) (client.ContainerStatPathResult, error) {
rpcCtx, cancel := a.rpcCtx(ctx)
defer cancel()
return a.inner.ContainerStatPath(rpcCtx, containerID, options)
}
func (a *dockerRPCTimeoutAPI) ImageInspect(
ctx context.Context, imageID string, opts ...client.ImageInspectOption,
) (client.ImageInspectResult, error) {
rpcCtx, cancel := a.rpcCtx(ctx)
defer cancel()
return a.inner.ImageInspect(rpcCtx, imageID, opts...)
}
func (a *dockerRPCTimeoutAPI) ImagePull(
ctx context.Context, refStr string, options client.ImagePullOptions,
) (client.ImagePullResponse, error) {
return a.inner.ImagePull(ctx, refStr, options)
}
func (a *dockerRPCTimeoutAPI) ImageList(
ctx context.Context, options client.ImageListOptions,
) (client.ImageListResult, error) {
rpcCtx, cancel := a.rpcCtx(ctx)
defer cancel()
return a.inner.ImageList(rpcCtx, options)
}
func (a *dockerRPCTimeoutAPI) ImageRemove(
ctx context.Context, imageID string, options client.ImageRemoveOptions,
) (client.ImageRemoveResult, error) {
// PruneChildren on a retired skill chain can run well past the short
// RPC budget, the way a commit or pull does. Timing out here would
// leave the ledger unmarked and the layers on disk.
return a.inner.ImageRemove(ctx, imageID, options)
}
func (a *dockerRPCTimeoutAPI) ContainerCommit(
ctx context.Context, containerID string, options client.ContainerCommitOptions,
) (client.ContainerCommitResult, error) {
return a.inner.ContainerCommit(ctx, containerID, options)
}
var _ dockerEngineAPI = (*dockerRPCTimeoutAPI)(nil)
+338
View File
@@ -0,0 +1,338 @@
package sandbox
import (
"context"
"strings"
"unicode"
"github.com/moby/moby/api/types/image"
"github.com/moby/moby/client"
)
const (
// dockerSkillSnapshotRepo is the local image namespace every skill
// snapshot is committed into. It is not a registry path: these tags are
// never pulled, and ListTemplates hides anything under it so an admin
// cannot pick a baked skill image as the config's base template.
dockerSkillSnapshotRepo = "academy-skill"
dockerSkillSnapshotLabel = "com.academy.sandbox.skill-snapshot"
dockerSkillSnapshotSourceLabel = "com.academy.sandbox.skill-snapshot-source"
// DockerForkSnapshotRepo is the local image namespace for session-fork
// snapshots. It is deliberately separate from dockerSkillSnapshotRepo: the
// skill reaper prunes by the skill namespace and labels, and letting fork
// snapshots share them would have each reaper collecting the other's
// images.
DockerForkSnapshotRepo = "academy-fork"
dockerForkSnapshotLabel = "com.academy.sandbox.fork-snapshot"
dockerForkSnapshotSourceLabel = "com.academy.sandbox.fork-snapshot-source"
)
// CreateSnapshot commits the container's filesystem into a tagged local image.
//
// The Engine pauses the container for the duration of the commit unless we
// opt out (we do not): that is the same "provider pauses while snapshotting"
// contract Cube and E2B honour. The resulting tag is a template ID — Create
// accepts it as RemoteCreateRequest.TemplateID — so the skill install path
// needs no Docker-specific branch past this adapter.
func (c *DockerRemoteClient) CreateSnapshot(
ctx context.Context, sandboxID string, name string,
) (RemoteSnapshotRef, error) {
id := strings.TrimSpace(sandboxID)
if id == "" {
return RemoteSnapshotRef{}, dockerInvalidRequest("CreateSnapshot", "sandbox ID is required")
}
return c.commitSnapshot(
ctx, id, name,
dockerSkillSnapshotRepo,
"academy skill snapshot",
dockerSkillSnapshotLabel,
dockerSkillSnapshotSourceLabel,
"CreateSnapshot",
)
}
// CreateForkSnapshot commits the container into the fork image namespace.
// Same shape as CreateSnapshot; a different repo and labels keep the skill
// reaper from collecting (or being collected by) session-fork images.
func (c *DockerRemoteClient) CreateForkSnapshot(
ctx context.Context, sandboxID string, name string,
) (RemoteSnapshotRef, error) {
id := strings.TrimSpace(sandboxID)
if id == "" {
return RemoteSnapshotRef{}, dockerInvalidRequest("CreateForkSnapshot", "sandbox ID is required")
}
return c.commitSnapshot(
ctx, id, name,
DockerForkSnapshotRepo,
"academy fork snapshot",
dockerForkSnapshotLabel,
dockerForkSnapshotSourceLabel,
"CreateForkSnapshot",
)
}
func (c *DockerRemoteClient) commitSnapshot(
ctx context.Context,
sandboxID, name, repo, comment, label, sourceLabel, op string,
) (RemoteSnapshotRef, error) {
reference, err := dockerSnapshotReference(repo, name, sandboxID, op)
if err != nil {
return RemoteSnapshotRef{}, err
}
committed, err := c.api.ContainerCommit(ctx, sandboxID, client.ContainerCommitOptions{
Reference: reference,
Comment: comment,
Changes: []string{
"LABEL " + label + "=true",
"LABEL " + sourceLabel + "=" + sandboxID,
},
})
if err != nil {
return RemoteSnapshotRef{}, dockerError(op, err)
}
if strings.TrimSpace(committed.ID) == "" {
return RemoteSnapshotRef{}, dockerInvalidRequest(op, "provider returned an empty snapshot ID")
}
return RemoteSnapshotRef{
ID: dockerCanonicalSnapshotID(reference),
Names: []string{dockerCanonicalSnapshotID(reference)},
}, nil
}
// DeleteSnapshot removes a committed skill image. A missing image is success:
// the reaper and the install-compensation path both retry deletes.
//
// PruneChildren is what makes the delete reclaim anything. Each generation is
// committed from a container started off the previous one, so generation N+1
// holds generation N's layers as ancestors. Untagging N alone therefore frees
// nothing while N+1 exists — which is correct and unavoidable — but the layers
// of a chain whose every tag has been retired would stay on disk forever
// without this, because the Go client defaults to noprune. Layers a live image
// still references are refcounted by the daemon, so cascading here cannot take
// the current image's storage out from under it.
func (c *DockerRemoteClient) DeleteSnapshot(ctx context.Context, snapshotID string) error {
id := strings.TrimSpace(snapshotID)
if id == "" {
return dockerInvalidRequest("DeleteSnapshot", "snapshot ID is required")
}
_, err := c.api.ImageRemove(ctx, id, client.ImageRemoveOptions{
PruneChildren: true,
})
if err != nil {
normalized := dockerError("DeleteSnapshot", err)
if IsRemoteNotFound(normalized) {
return nil
}
return normalized
}
if dockerIsForkSnapshotRef(id) {
c.pruneDanglingForkImages(ctx)
} else {
c.pruneDanglingSkillImages(ctx)
}
return nil
}
// pruneDanglingSkillImages drops skill-snapshot images that no longer carry a
// tag. Nothing can boot one: the ledger addresses snapshots by the tag minted
// in CreateSnapshot and never by digest, so an untagged one is unreachable by
// construction. They are left behind by a commit whose ledger write or pointer
// switch failed, and by every delete that ran before PruneChildren was set.
//
// Best effort by nature — reclaiming storage must never turn a successful
// delete into a failed one. An image a container still holds comes back as a
// conflict and is skipped; the next pass retries once that container is gone.
func (c *DockerRemoteClient) pruneDanglingSkillImages(ctx context.Context) {
listed, err := c.api.ImageList(ctx, client.ImageListOptions{
All: true,
Filters: client.Filters{}.Add("label", dockerSkillSnapshotLabel+"=true"),
})
if err != nil {
return
}
for _, item := range listed.Items {
if !dockerImageIsSkillSnapshot(item) || dockerImageHasTag(item) {
continue
}
id := strings.TrimSpace(item.ID)
if id == "" {
continue
}
_, _ = c.api.ImageRemove(ctx, id, client.ImageRemoveOptions{PruneChildren: true})
}
}
// pruneDanglingForkImages drops untagged fork-snapshot images. Same rationale
// as pruneDanglingSkillImages; the filter is the fork label so a skill delete
// cannot sweep a live fork image and vice versa.
func (c *DockerRemoteClient) pruneDanglingForkImages(ctx context.Context) {
listed, err := c.api.ImageList(ctx, client.ImageListOptions{
All: true,
Filters: client.Filters{}.Add("label", dockerForkSnapshotLabel+"=true"),
})
if err != nil {
return
}
for _, item := range listed.Items {
if !dockerImageIsForkSnapshot(item) || dockerImageHasTag(item) {
continue
}
id := strings.TrimSpace(item.ID)
if id == "" {
continue
}
_, _ = c.api.ImageRemove(ctx, id, client.ImageRemoveOptions{PruneChildren: true})
}
}
func dockerImageHasTag(item image.Summary) bool {
for _, tag := range item.RepoTags {
if strings.TrimSpace(tag) != "" && tag != "<none>:<none>" {
return true
}
}
return false
}
// ListSnapshots returns skill-snapshot images on this daemon. An empty
// sandboxID lists every skill snapshot; a non-empty one keeps those committed
// from that container.
func (c *DockerRemoteClient) ListSnapshots(
ctx context.Context, sandboxID string,
) ([]RemoteSnapshotRef, error) {
filters := client.Filters{}.Add("label", dockerSkillSnapshotLabel+"=true")
if src := strings.TrimSpace(sandboxID); src != "" {
filters = filters.Add("label", dockerSkillSnapshotSourceLabel+"="+src)
}
listed, err := c.api.ImageList(ctx, client.ImageListOptions{All: true, Filters: filters})
if err != nil {
return nil, dockerError("ListSnapshots", err)
}
wantSource := strings.TrimSpace(sandboxID)
out := make([]RemoteSnapshotRef, 0, len(listed.Items))
for _, item := range listed.Items {
if !dockerImageIsSkillSnapshot(item) {
continue
}
if wantSource != "" && item.Labels[dockerSkillSnapshotSourceLabel] != wantSource {
continue
}
out = append(out, dockerSnapshotRef(item))
}
return out, nil
}
func dockerImageIsSkillSnapshot(item image.Summary) bool {
if item.Labels[dockerSkillSnapshotLabel] == "true" {
return true
}
for _, tag := range item.RepoTags {
if dockerIsSkillSnapshotRef(tag) {
return true
}
}
return false
}
func dockerImageIsForkSnapshot(item image.Summary) bool {
if item.Labels[dockerForkSnapshotLabel] == "true" {
return true
}
for _, tag := range item.RepoTags {
if dockerIsForkSnapshotRef(tag) {
return true
}
}
return false
}
func dockerIsSkillSnapshotRef(ref string) bool {
return dockerIsRepoSnapshotRef(ref, dockerSkillSnapshotRepo)
}
func dockerIsForkSnapshotRef(ref string) bool {
return dockerIsRepoSnapshotRef(ref, DockerForkSnapshotRepo)
}
func dockerIsLocalSnapshotRef(ref string) bool {
return dockerIsSkillSnapshotRef(ref) || dockerIsForkSnapshotRef(ref)
}
func dockerIsRepoSnapshotRef(ref, repo string) bool {
trimmed := strings.TrimSpace(ref)
prefix := repo + "/"
if strings.HasPrefix(trimmed, prefix) {
return true
}
// ImageList sometimes returns the docker.io/ prefix. The tag we mint
// never has a registry, so this is only a listing alias.
return strings.HasPrefix(trimmed, "docker.io/"+prefix)
}
func dockerSnapshotRef(item image.Summary) RemoteSnapshotRef {
names := make([]string, 0, len(item.RepoTags))
id := strings.TrimSpace(item.ID)
for _, tag := range item.RepoTags {
if tag == "" || tag == "<none>:<none>" {
continue
}
canonical := dockerCanonicalSnapshotID(tag)
names = append(names, canonical)
if dockerIsSkillSnapshotRef(canonical) && (id == "" || !dockerIsSkillSnapshotRef(id)) {
id = canonical
}
}
if id == "" && len(names) > 0 {
id = names[0]
}
return RemoteSnapshotRef{ID: id, Names: names}
}
func dockerCanonicalSnapshotID(ref string) string {
trimmed := strings.TrimPrefix(strings.TrimSpace(ref), "docker.io/")
return strings.TrimSuffix(trimmed, ":latest")
}
func dockerSnapshotReference(repo, name, sandboxID, op string) (string, error) {
base := dockerSanitizeImageName(name)
if base == "" {
base = dockerSanitizeImageName(sandboxID)
}
if base == "" {
return "", dockerInvalidRequest(op, "snapshot name is required")
}
return repo + "/" + base, nil
}
// dockerSanitizeImageName maps an install-generated snapshot name onto a
// single Docker path component: lowercase [a-z0-9] with interior - separators.
func dockerSanitizeImageName(raw string) string {
var b strings.Builder
lastSep := true
for _, r := range strings.ToLower(strings.TrimSpace(raw)) {
switch {
case unicode.IsLetter(r) || unicode.IsDigit(r):
b.WriteRune(r)
lastSep = false
case r == '.' || r == '_' || r == '-':
if lastSep || b.Len() == 0 {
continue
}
b.WriteByte('-')
lastSep = true
}
}
out := strings.Trim(b.String(), "-")
const maxName = 80
if len(out) > maxName {
out = strings.Trim(out[:maxName], "-")
}
return out
}
var _ forkSnapshotCreator = (*DockerRemoteClient)(nil)
+295
View File
@@ -0,0 +1,295 @@
package sandbox
import (
"context"
"errors"
"testing"
"github.com/moby/moby/api/types/image"
"github.com/stretchr/testify/require"
)
func TestDockerCreateSnapshotTagsASkillImage(t *testing.T) {
engine := newFakeDockerEngine()
docker := newTestDockerClient(t, engine)
ref, err := docker.CreateSnapshot(context.Background(), "container-1", "academy-sk-cfg1-g1")
require.NoError(t, err)
require.Equal(t, "academy-skill/academy-sk-cfg1-g1", ref.ID)
require.Len(t, engine.committed, 1)
require.Equal(t, "academy-skill/academy-sk-cfg1-g1", engine.committed[0].Reference)
require.False(t, engine.committed[0].NoPause,
"the Engine must pause the container for the duration of the commit")
require.Contains(t, engine.committed[0].Changes, "LABEL "+dockerSkillSnapshotLabel+"=true")
require.Contains(t, engine.committed[0].Changes,
"LABEL "+dockerSkillSnapshotSourceLabel+"=container-1")
}
func TestDockerCreateSnapshotRejectsEmptySandboxID(t *testing.T) {
_, err := newTestDockerClient(t, newFakeDockerEngine()).
CreateSnapshot(context.Background(), " ", "n")
require.True(t, IsRemoteInvalidRequest(err))
}
func TestDockerDeleteSnapshotTreatsMissingAsSuccess(t *testing.T) {
err := newTestDockerClient(t, newFakeDockerEngine()).
DeleteSnapshot(context.Background(), "academy-skill/missing")
require.NoError(t, err)
}
func TestDockerDeleteSnapshotRejectsEmptySnapshotID(t *testing.T) {
err := newTestDockerClient(t, newFakeDockerEngine()).
DeleteSnapshot(context.Background(), " ")
require.True(t, IsRemoteInvalidRequest(err))
}
func TestDockerSnapshotRoundTripAndListFilter(t *testing.T) {
engine := newFakeDockerEngine()
docker := newTestDockerClient(t, engine)
ctx := context.Background()
first, err := docker.CreateSnapshot(ctx, "container-a", "academy-sk-a-g1")
require.NoError(t, err)
second, err := docker.CreateSnapshot(ctx, "container-a", "academy-sk-a-g2")
require.NoError(t, err)
_, err = docker.CreateSnapshot(ctx, "container-b", "academy-sk-b-g1")
require.NoError(t, err)
all, err := docker.ListSnapshots(ctx, "")
require.NoError(t, err)
require.Len(t, all, 3)
fromA, err := docker.ListSnapshots(ctx, "container-a")
require.NoError(t, err)
require.Len(t, fromA, 2)
ids := map[string]struct{}{fromA[0].ID: {}, fromA[1].ID: {}}
require.Contains(t, ids, first.ID)
require.Contains(t, ids, second.ID)
require.NoError(t, docker.DeleteSnapshot(ctx, first.ID))
require.NoError(t, docker.DeleteSnapshot(ctx, first.ID), "deleting twice must stay idempotent")
fromA, err = docker.ListSnapshots(ctx, "container-a")
require.NoError(t, err)
require.Len(t, fromA, 1)
require.Equal(t, second.ID, fromA[0].ID)
}
// Each generation is committed from a container started off the previous one,
// so untagging one alone frees nothing while its descendant lives. Without
// noprune=0 the layers of a fully retired chain would stay on disk forever.
func TestDockerDeleteSnapshotPrunesUntaggedAncestors(t *testing.T) {
engine := newFakeDockerEngine()
docker := newTestDockerClient(t, engine)
ref, err := docker.CreateSnapshot(context.Background(), "container-a", "academy-sk-a-g1")
require.NoError(t, err)
require.NoError(t, docker.DeleteSnapshot(context.Background(), ref.ID))
require.True(t, engine.removeImageOptions[0].PruneChildren,
"a delete that keeps untagged parents can never reclaim a retired chain")
require.False(t, engine.removeImageOptions[0].Force,
"force-remove would untag an image a live session container still holds")
}
// A skill snapshot the ledger cannot name is unreachable: snapshots are always
// addressed by the tag CreateSnapshot mints, never by digest.
func TestDockerDeleteSnapshotSweepsUntaggedSkillImages(t *testing.T) {
engine := newFakeDockerEngine()
engine.images = []image.Summary{
{
ID: "sha256:retired",
RepoTags: []string{"academy-skill/academy-sk-a-g1:latest"},
Labels: map[string]string{dockerSkillSnapshotLabel: "true"},
},
{
ID: "sha256:orphan",
RepoTags: []string{"<none>:<none>"},
Labels: map[string]string{dockerSkillSnapshotLabel: "true"},
},
{
ID: "sha256:live",
RepoTags: []string{"academy-skill/academy-sk-a-g2:latest"},
Labels: map[string]string{dockerSkillSnapshotLabel: "true"},
},
{
ID: "sha256:base",
RepoTags: []string{"academy/sandbox:test"},
Labels: map[string]string{dockerTemplateLabel: "true"},
},
}
docker := newTestDockerClient(t, engine)
require.NoError(t, docker.DeleteSnapshot(
context.Background(), "academy-skill/academy-sk-a-g1"))
require.Equal(t,
[]string{"academy-skill/academy-sk-a-g1", "sha256:orphan"},
engine.removedImages,
"the sweep must take the untagged snapshot and nothing that is still named")
}
func TestDockerDeleteSnapshotSweepsUntaggedForkImages(t *testing.T) {
engine := newFakeDockerEngine()
engine.images = []image.Summary{
{
ID: "sha256:retired-fork",
RepoTags: []string{DockerForkSnapshotRepo + "/fork-a:latest"},
Labels: map[string]string{dockerForkSnapshotLabel: "true"},
},
{
ID: "sha256:orphan-fork",
RepoTags: []string{"<none>:<none>"},
Labels: map[string]string{dockerForkSnapshotLabel: "true"},
},
{
ID: "sha256:orphan-skill",
RepoTags: []string{"<none>:<none>"},
Labels: map[string]string{dockerSkillSnapshotLabel: "true"},
},
{
ID: "sha256:live-fork",
RepoTags: []string{DockerForkSnapshotRepo + "/fork-b:latest"},
Labels: map[string]string{dockerForkSnapshotLabel: "true"},
},
}
docker := newTestDockerClient(t, engine)
require.NoError(t, docker.DeleteSnapshot(
context.Background(), DockerForkSnapshotRepo+"/fork-a"))
require.Equal(t,
[]string{DockerForkSnapshotRepo + "/fork-a", "sha256:orphan-fork"},
engine.removedImages,
"a fork delete must not sweep skill images")
}
func TestDockerDeleteSnapshotSweepFailureIsNotAnError(t *testing.T) {
engine := newFakeDockerEngine()
engine.images = []image.Summary{
{
ID: "sha256:orphan",
RepoTags: []string{"<none>:<none>"},
Labels: map[string]string{dockerSkillSnapshotLabel: "true"},
},
}
engine.imagePresent["academy-skill/academy-sk-a-g1"] = true
engine.listImagesErr = errors.New("daemon busy")
docker := newTestDockerClient(t, engine)
require.NoError(t, docker.DeleteSnapshot(
context.Background(), "academy-skill/academy-sk-a-g1"),
"reclaiming storage must not turn a completed delete into a failure")
}
func TestDockerListTemplatesHidesSkillSnapshots(t *testing.T) {
engine := newFakeDockerEngine()
engine.images = []image.Summary{
{
ID: "sha256:base",
RepoTags: []string{"academy/sandbox:test"},
Labels: map[string]string{dockerTemplateLabel: "true"},
},
{
ID: "sha256:snap",
RepoTags: []string{"academy-skill/academy-sk-cfg1-g1:latest"},
Labels: map[string]string{dockerSkillSnapshotLabel: "true"},
},
}
docker := newTestDockerClient(t, engine)
templates, err := docker.ListTemplates(context.Background())
require.NoError(t, err)
require.Len(t, templates, 1)
require.Equal(t, "academy/sandbox:test", templates[0].ID)
}
func TestDockerCreateDoesNotPullAMissingSkillSnapshot(t *testing.T) {
engine := newFakeDockerEngine()
docker := newTestDockerClient(t, engine)
_, err := docker.Create(context.Background(), RemoteCreateRequest{
TemplateID: "academy-skill/academy-sk-cfg1-g1",
})
require.True(t, IsRemoteInvalidRequest(err), err)
require.Empty(t, engine.pulled,
"a local commit must not be fetched from a registry")
}
func TestDockerCreateForkSnapshotTagsAForkImage(t *testing.T) {
engine := newFakeDockerEngine()
docker := newTestDockerClient(t, engine)
ref, err := docker.CreateForkSnapshot(context.Background(), "container-1", "fork-session-a-1")
require.NoError(t, err)
require.Equal(t, DockerForkSnapshotRepo+"/fork-session-a-1", ref.ID)
require.Len(t, engine.committed, 1)
require.Equal(t, DockerForkSnapshotRepo+"/fork-session-a-1", engine.committed[0].Reference)
require.Equal(t, "academy fork snapshot", engine.committed[0].Comment)
require.False(t, engine.committed[0].NoPause,
"the Engine must pause the container for the duration of the commit")
require.Contains(t, engine.committed[0].Changes, "LABEL "+dockerForkSnapshotLabel+"=true")
require.Contains(t, engine.committed[0].Changes,
"LABEL "+dockerForkSnapshotSourceLabel+"=container-1")
}
func TestDockerListTemplatesHidesForkSnapshots(t *testing.T) {
engine := newFakeDockerEngine()
engine.images = []image.Summary{
{
ID: "sha256:base",
RepoTags: []string{"academy/sandbox:test"},
Labels: map[string]string{dockerTemplateLabel: "true"},
},
{
ID: "sha256:fork",
RepoTags: []string{DockerForkSnapshotRepo + "/fork-session-a-1:latest"},
Labels: map[string]string{dockerForkSnapshotLabel: "true"},
},
{
ID: "sha256:fork-tag-only",
RepoTags: []string{DockerForkSnapshotRepo + "/untagged-label:latest"},
},
}
docker := newTestDockerClient(t, engine)
templates, err := docker.ListTemplates(context.Background())
require.NoError(t, err)
require.Len(t, templates, 1)
require.Equal(t, "academy/sandbox:test", templates[0].ID)
}
func TestDockerListSnapshotsExcludesForkImages(t *testing.T) {
engine := newFakeDockerEngine()
docker := newTestDockerClient(t, engine)
ctx := context.Background()
_, err := docker.CreateSnapshot(ctx, "container-1", "academy-sk-cfg1-g1")
require.NoError(t, err)
_, err = docker.CreateForkSnapshot(ctx, "container-1", "fork-session-a-1")
require.NoError(t, err)
listed, err := docker.ListSnapshots(ctx, "")
require.NoError(t, err)
require.Len(t, listed, 1)
require.Equal(t, "academy-skill/academy-sk-cfg1-g1", listed[0].ID)
}
func TestDockerCreateDoesNotPullAMissingForkSnapshot(t *testing.T) {
engine := newFakeDockerEngine()
docker := newTestDockerClient(t, engine)
_, err := docker.Create(context.Background(), RemoteCreateRequest{
TemplateID: DockerForkSnapshotRepo + "/fork-session-a-1",
})
require.True(t, IsRemoteInvalidRequest(err), err)
require.Empty(t, engine.pulled,
"a local fork commit must not be fetched from a registry")
}
func TestDockerSanitizeImageName(t *testing.T) {
require.Equal(t, "academy-sk-cfg1-g1", dockerSanitizeImageName("academy-sk-cfg1-g1"))
require.Equal(t, "abc-def", dockerSanitizeImageName("ABC_DEF"))
require.Equal(t, "snap", dockerSanitizeImageName("--snap--"))
require.Empty(t, dockerSanitizeImageName("***"))
}
+209
View File
@@ -0,0 +1,209 @@
// Images as templates for the docker backend.
//
// The settings wizard asks every backend the same two questions — which
// templates exist, and please make sure the standard one does. For Docker the
// answer is images on the daemon: an image is a pre-baked filesystem a sandbox
// starts from, which is exactly what a Cube or E2B template is.
//
// Three differences from the MicroVM backends shape this file:
//
// - A daemon holds every image its host ever pulled, most of which have
// nothing to do with sandboxes. Listing all of them would bury the one the
// admin needs, so the catalog only reports images that are recognisably
// sandbox templates.
// - Skill and fork snapshots live in the same image store (academy-skill/…
// and academy-fork/…), so they are subtracted the way Cube hides snap- IDs
// from GET /templates.
// - Making the standard template exist means pulling, which can take minutes
// on a cold host. The pull therefore runs in the background and the
// template reports "building" until it lands, mirroring how the other
// backends report an in-flight template build.
package sandbox
import (
"context"
"fmt"
"strings"
"sync"
"time"
"github.com/moby/moby/client"
)
// dockerTemplateLabel marks an image as a Academy sandbox template. Images
// built by an operator can opt into the catalog by carrying it.
const dockerTemplateLabel = "com.academy.sandbox.template"
// dockerImagePulls tracks background pulls per daemon endpoint and image, so a
// second refresh reports the in-flight pull instead of starting another one.
var dockerImagePulls = struct {
mu sync.Mutex
state map[string]*dockerPullState
}{state: make(map[string]*dockerPullState)}
type dockerPullState struct {
started time.Time
done bool
err error
}
// ListTemplates reports the sandbox images available on this daemon.
func (c *DockerRemoteClient) ListTemplates(ctx context.Context) ([]RemoteTemplate, error) {
listed, err := c.api.ImageList(ctx, client.ImageListOptions{})
if err != nil {
return nil, dockerError("ListTemplates", err)
}
templates := make([]RemoteTemplate, 0, len(listed.Items))
configured := strings.TrimSpace(c.settings.Image)
configuredPresent := false
for _, image := range listed.Items {
snapshot := dockerImageIsSkillSnapshot(image) || dockerImageIsForkSnapshot(image)
for _, tag := range image.RepoTags {
if tag == "" || tag == "<none>:<none>" {
continue
}
// Skill and fork snapshots are images, so they would otherwise
// appear in the "pick a base template" list the way Cube's snap-
// IDs used to. Hide them unless this config's stored image is
// that tag.
if snapshot && tag != configured {
continue
}
standard := isStandardTemplateImage(tag)
if !standard && !snapshot && image.Labels[dockerTemplateLabel] != "true" && tag != configured {
continue
}
if tag == configured {
configuredPresent = true
}
templates = append(templates, RemoteTemplate{
ID: tag,
Name: tag,
Status: "ready",
Image: tag,
Version: image.ID,
Standard: standard,
CreatedAt: time.Unix(image.Created, 0).UTC().Format(time.RFC3339),
})
}
}
// A configured image the daemon has not pulled yet is still the template
// this config will use. Hiding it would tell the admin their own choice
// does not exist, when all that is missing is a pull.
if configured != "" && !configuredPresent {
templates = append(templates, c.pendingTemplate(configured))
}
return templates, nil
}
// pendingTemplate describes an image that is not on the daemon yet, reporting
// any background pull's outcome.
func (c *DockerRemoteClient) pendingTemplate(image string) RemoteTemplate {
template := RemoteTemplate{
ID: image,
Name: image,
Image: image,
Status: "missing",
Standard: isStandardTemplateImage(image),
}
dockerImagePulls.mu.Lock()
state, ok := dockerImagePulls.state[c.pullKey(image)]
dockerImagePulls.mu.Unlock()
switch {
case !ok:
return template
case !state.done:
template.Status = "building"
case state.err != nil:
template.Status = "failed"
template.Error = state.err.Error()
}
return template
}
// EnsureStandardTemplate makes the configured image available on the daemon,
// pulling it in the background when it is missing.
func (c *DockerRemoteClient) EnsureStandardTemplate(ctx context.Context) (*RemoteTemplate, error) {
image := strings.TrimSpace(c.settings.Image)
if image == "" {
image = DefaultDockerImage
}
if _, err := c.api.ImageInspect(ctx, image); err == nil {
return &RemoteTemplate{
ID: image,
Name: image,
Image: image,
Status: "ready",
Standard: isStandardTemplateImage(image),
}, nil
}
key := c.pullKey(image)
dockerImagePulls.mu.Lock()
state, running := dockerImagePulls.state[key]
if running && !state.done {
dockerImagePulls.mu.Unlock()
pending := c.pendingTemplate(image)
return &pending, nil
}
dockerImagePulls.state[key] = &dockerPullState{started: time.Now()}
dockerImagePulls.mu.Unlock()
// Detached from the request: a cold pull outlives the HTTP call that
// asked for it, and cancelling mid-pull would leave a partial download
// that the next refresh restarts from scratch.
go c.pullInBackground(context.WithoutCancel(ctx), key, image)
pending := c.pendingTemplate(image)
return &pending, nil
}
// ReplaceStandardTemplate is a pull of the configured image. Docker has no
// cluster-side template object to delete; a missing image is fetched, a
// present one is left as-is.
func (c *DockerRemoteClient) ReplaceStandardTemplate(ctx context.Context) (*RemoteTemplate, error) {
return c.EnsureStandardTemplate(ctx)
}
// DeleteSupersededStandardTemplates is a no-op: Docker has no cluster-side
// template object, and skill snapshots live in a separate image namespace.
func (c *DockerRemoteClient) DeleteSupersededStandardTemplates(context.Context, string) error {
return nil
}
func (c *DockerRemoteClient) pullInBackground(ctx context.Context, key, image string) {
pullCtx, cancel := context.WithTimeout(ctx, dockerImagePullBudget)
defer cancel()
err := func() error {
body, err := c.api.ImagePull(pullCtx, image, client.ImagePullOptions{})
if err != nil {
return err
}
return awaitImagePull(pullCtx, body)
}()
dockerImagePulls.mu.Lock()
defer dockerImagePulls.mu.Unlock()
if err != nil {
dockerImagePulls.state[key] = &dockerPullState{done: true, err: err}
return
}
// A finished pull leaves no state behind: the image is now visible to
// ImageInspect, which is a better source of truth than our bookkeeping.
delete(dockerImagePulls.state, key)
}
// dockerImagePullBudget bounds a background pull. Sandbox images are large but
// not unbounded; a pull still running after this either hit a stalled registry
// or a network the daemon cannot reach.
const dockerImagePullBudget = 30 * time.Minute
func (c *DockerRemoteClient) pullKey(image string) string {
return fmt.Sprintf("%s|%s", c.settings.Endpoint.key(), image)
}
var _ RemoteTemplateCatalog = (*DockerRemoteClient)(nil)
+421
View File
@@ -0,0 +1,421 @@
// Interactive terminal (PTY) capability for the Docker adapter.
//
// Cube and E2B ride envd's PTY service, so their adapters translate an SDK
// handle. Docker has no such service: the PTY is a plain `exec` created with
// TTY=true whose hijacked connection is a raw byte stream, and window resizes
// go through a separate Engine call. This file bridges that to the neutral
// RemoteTerminalSession contract.
//
// One structural difference from envd: a Docker exec cannot be re-attached.
// /exec/{id}/start runs once and the Engine API has no exec attach endpoint,
// so RemoteTerminalOptions.AttachPID is ignored and every reconnecting browser
// gets a fresh shell. It also cannot be left running: unlike Cube/E2B, closing
// the hijacked connection does NOT end the shell (verified against a live
// daemon — an idle bash and its foreground jobs survive), so abandoning it
// would strand processes in the container. Close therefore hangs up the shell
// the way a closing terminal emulator would. See dockerTerminalKillCmd.
package sandbox
import (
"bufio"
"context"
"crypto/rand"
"encoding/hex"
"errors"
"io"
"net"
"strconv"
"sync"
"time"
"academy/internal/logger"
"github.com/moby/moby/client"
)
// Compile-time proof that the Docker adapter serves the terminal capability.
var _ RemoteTerminalManager = (*DockerRemoteClient)(nil)
const (
// dockerTerminalActivityTimeout bounds the marker-refresh exec. It is a
// trivial `true`, so this only has to outlast a round trip.
dockerTerminalActivityTimeout = 15 * time.Second
// dockerTerminalInspectTimeout bounds the exit-code read that follows the
// stream ending.
dockerTerminalInspectTimeout = 5 * time.Second
// dockerTerminalInspectPoll is how often that read retries while the
// daemon still reports the exec as running: the hijacked stream can hit
// EOF before the daemon records the exit code.
dockerTerminalInspectPoll = 100 * time.Millisecond
// dockerTerminalKillTimeout bounds the best-effort terminate exec issued
// when a terminal is closed while its shell is still alive.
dockerTerminalKillTimeout = 10 * time.Second
)
// dockerTerminalIDEnv tags every process of one terminal. The PTY exec gets
// this variable set to a per-open token, and every process it starts inherits
// it — which is what lets teardown find and kill the shell's whole tree from
// inside the container, without having to map ExecInspect's host PID into the
// container's PID namespace.
const dockerTerminalIDEnv = "ACADEMY_TERMINAL_ID"
// dockerTerminalToken mints a per-open marker. It only has to distinguish
// concurrent terminals in one container, so a random 16-byte hex string is
// more than enough and stays shell-safe.
func dockerTerminalToken() string {
var b [16]byte
if _, err := rand.Read(b[:]); err != nil {
// crypto/rand failing is a broken host; a time-based token still
// separates concurrent opens well enough for a best-effort kill.
return strconv.FormatInt(time.Now().UnixNano(), 16)
}
return hex.EncodeToString(b[:])
}
// dockerTerminalEnvs is the PTY's environment. Cube and E2B get TERM, LANG
// and LC_ALL from their SDK; a Docker exec gets nothing but the daemon's
// TERM=xterm, which loses 256 colours and, on an image without a LANG, breaks
// multibyte input. The defaults below mirror the E2B SDK, caller envs win, and
// the per-open marker is always set last so nothing can override it.
func dockerTerminalEnvs(opts RemoteTerminalOptions, terminalID string) map[string]string {
envs := map[string]string{
"TERM": "xterm-256color",
"LANG": "C.UTF-8",
"LC_ALL": "C.UTF-8",
}
for key, value := range terminalEnvs(opts) {
envs[key] = value
}
envs[dockerTerminalIDEnv] = terminalID
return envs
}
// dockerTerminalShellCmd is the argv the PTY runs. bash is preferred for line
// editing and job control; a minimal image that only ships the POSIX shell
// still gets a usable terminal instead of "no such file".
func dockerTerminalShellCmd() []string {
return []string{
"/bin/sh", "-c",
"if command -v bash >/dev/null 2>&1; then exec bash; else exec sh; fi",
}
}
// OpenTerminal opens an interactive shell PTY inside the container behind
// handle. The returned session streams until the shell exits, the context
// passed to OpenTerminal is cancelled, or Close is called — the last two end
// it identically (through Close, which also terminates the shell).
func (c *DockerRemoteClient) OpenTerminal(
ctx context.Context,
handle RemoteSandboxHandle,
opts RemoteTerminalOptions,
) (RemoteTerminalSession, error) {
id, err := dockerHandleID("OpenTerminal", handle)
if err != nil {
return nil, err
}
terminalID := dockerTerminalToken()
execOpts := client.ExecCreateOptions{
Cmd: dockerTerminalShellCmd(),
User: dockerExecUser(opts.User),
WorkingDir: terminalCwd(opts),
Env: dockerEnvSlice(dockerTerminalEnvs(opts, terminalID)),
TTY: true,
AttachStdin: true,
AttachStdout: true,
AttachStderr: true,
ConsoleSize: client.ConsoleSize{
Height: uint(terminalRows(opts)),
Width: uint(terminalCols(opts)),
},
}
created, err := c.api.ExecCreate(ctx, id, execOpts)
if err != nil && dockerContainerNotRunning(err) {
if readyErr := c.ensureRunning(ctx, id, "OpenTerminal"); readyErr != nil {
return nil, readyErr
}
created, err = c.api.ExecCreate(ctx, id, execOpts)
}
if err != nil {
return nil, dockerError("OpenTerminal", err)
}
// ExecAttach both starts the exec and hijacks its stdio. With TTY=true the
// hijacked stream is raw bytes — no stdcopy 8-byte framing — so the pump
// below reads it directly.
attached, err := c.api.ExecAttach(ctx, created.ID, client.ExecAttachOptions{TTY: true})
if err != nil {
return nil, dockerError("OpenTerminal", err)
}
// The exit code has to be readable after the WebSocket handler's request
// context is gone, so the session keeps a detached copy for its one
// inspect call at stream end.
inspectCtx := context.WithoutCancel(ctx)
session := &dockerTerminalSession{
api: c.api,
containerID: id,
execID: created.ID,
terminalID: terminalID,
conn: attached.Conn,
reader: attached.Reader,
out: make(chan RemoteTerminalEvent, terminalOutputBuffer),
closedCh: make(chan struct{}),
inspectCtx: inspectCtx,
}
go session.pump()
// The caller's context is part of the session's lifetime, matching Cube and
// E2B. Nothing else can honour it: the pump only reads the hijacked stream
// and the moby hijack stops watching the context once the connection is
// upgraded, so without this watcher a caller that only cancels its context
// (never calling Close) would leave the shell running — and, worse, the TTL
// refresh below rides a detached context, so it would keep the container
// from ever being idle-reclaimed. Cancellation goes through the same Close
// path as everything else, so it reaps the shell too.
go func() {
select {
case <-ctx.Done():
_ = session.Close()
case <-session.closedCh:
}
}()
// A PTY never runs the exec wrapper that touches the idle-sweep activity
// marker, so without this a session that only ever sits in the terminal
// would be reclaimed mid-use at its TTL. Exec refreshes the marker on its
// way through the wrapper; a zero IdleTTL (sweeping disabled) no-ops. The
// refresh is deliberately on the detached context: it must survive the
// request context the handler used, and stops when closedCh closes.
startTerminalTTLRefresh(inspectCtx, session.closedCh, c.settings.IdleTTL,
func(rctx context.Context) error {
_, err := c.Exec(rctx, handle, RemoteExecRequest{
Command: "true",
Timeout: dockerTerminalActivityTimeout,
})
return err
})
return session, nil
}
// dockerTerminalSession bridges one hijacked TTY exec stream to the neutral
// RemoteTerminalSession contract.
type dockerTerminalSession struct {
api dockerEngineAPI
// containerID is where the terminate exec is created; the shell lives in
// this container and the kill has to run there too.
containerID string
execID string
// terminalID is the per-open marker set in the shell's environment; the
// terminate exec matches it to find the shell and its descendants.
terminalID string
conn net.Conn
reader *bufio.Reader
out chan RemoteTerminalEvent
closedCh chan struct{}
// closeOnce guards both closedCh and conn so concurrent Close calls are
// safe (RemoteTerminalSession documents Close as idempotent).
closeOnce sync.Once
// killOnce serialises the terminate exec: pump reaching its end and an
// explicit Close can both arrive, and the kill must run at most once.
killOnce sync.Once
inspectCtx context.Context
}
// pump copies raw PTY output into the event channel until the stream ends.
func (s *dockerTerminalSession) pump() {
defer close(s.out)
var readErr error
buf := make([]byte, 32*1024)
for {
n, err := s.reader.Read(buf)
if n > 0 {
// The daemon reuses the buffer, so copy before emitting.
chunk := make([]byte, n)
copy(chunk, buf[:n])
emitTerminalEvent(s.out, s.closedCh, RemoteTerminalEvent{Data: chunk})
}
if err != nil {
readErr = err
break
}
}
// Close tears the stream down on purpose; that is not a terminal failure
// and must not be reported as one.
select {
case <-s.closedCh:
return
default:
}
switch {
case readErr == nil || errors.Is(readErr, io.EOF):
// The daemon ended the stream itself (the shell exited). Its exit code
// is the only useful thing left to report.
emitTerminalEvent(s.out, s.closedCh,
RemoteTerminalEvent{Exited: true, ExitCode: s.inspectExitCode()})
default:
emitTerminalEvent(s.out, s.closedCh,
RemoteTerminalEvent{Err: dockerError("terminal stream", readErr)})
}
// The stream is over; release the marker-refresh loop now instead of
// waiting for the handler to get around to Close.
s.teardown()
}
func (s *dockerTerminalSession) inspectExitCode() int {
ctx, cancel := context.WithTimeout(s.inspectCtx, dockerTerminalInspectTimeout)
defer cancel()
for {
inspected, err := s.api.ExecInspect(ctx, s.execID, client.ExecInspectOptions{})
if err != nil {
return -1
}
if !inspected.Running {
return inspected.ExitCode
}
select {
case <-ctx.Done():
return -1
case <-time.After(dockerTerminalInspectPoll):
}
}
}
func (s *dockerTerminalSession) Output() <-chan RemoteTerminalEvent { return s.out }
// PID is always 0. ExecInspect only knows the host PID, which means nothing
// inside the container and must not reach the browser; and since the exec
// cannot be re-attached there is no identifier worth handing out for a
// reconnect either. 0 keeps the frontend from sending a pty_id back.
func (s *dockerTerminalSession) PID() uint32 { return 0 }
// Write feeds keystrokes into the PTY. net.Conn is safe for concurrent use, so
// no lock is needed against Resize/Close.
//
// The hijacked conn does not see ctx, so its deadline is applied explicitly:
// a PTY whose foreground program stops reading stdin back-pressures this
// write, and without a deadline the caller's input loop would hang with it.
// Only the bridge's input pump writes, so setting the deadline here does not
// race another writer.
func (s *dockerTerminalSession) Write(ctx context.Context, data []byte) error {
if len(data) == 0 {
return nil
}
if deadline, ok := ctx.Deadline(); ok {
_ = s.conn.SetWriteDeadline(deadline)
defer func() { _ = s.conn.SetWriteDeadline(time.Time{}) }()
}
if _, err := s.conn.Write(data); err != nil {
return dockerError("terminal input", err)
}
return nil
}
func (s *dockerTerminalSession) Resize(ctx context.Context, cols, rows uint32) error {
if cols == 0 || rows == 0 {
return nil
}
if _, err := s.api.ExecResize(ctx, s.execID, client.ExecResizeOptions{
Height: uint(rows),
Width: uint(cols),
}); err != nil {
return dockerError("terminal resize", err)
}
return nil
}
// Close detaches Academy from the PTY and, because Docker has no re-attach to
// preserve, hangs up the shell inside the container. Unlike Cube/E2B,
// closing the hijacked connection does not end the exec — the daemon keeps it
// (and any foreground jobs) alive — so a bare disconnect would strand the
// process until the container is swept. Safe to call more than once.
func (s *dockerTerminalSession) Close() error {
s.teardown()
s.terminate()
return nil
}
// terminate hangs up the exec's shell and the processes it started, best
// effort. It runs from Close only, but Close follows every session end,
// including a shell that already exited on its own: then the shell is gone and
// the hangup only reaches jobs it left behind. Runs at most once.
//
// A failed terminate leaves the shell running until the container is swept, so
// it is logged: nothing else would ever surface the leak.
func (s *dockerTerminalSession) terminate() {
s.killOnce.Do(func() {
ctx, cancel := context.WithTimeout(s.inspectCtx, dockerTerminalKillTimeout)
defer cancel()
created, err := s.api.ExecCreate(ctx, s.containerID, client.ExecCreateOptions{
Cmd: dockerTerminalKillCmd(s.terminalID),
User: dockerExecUser(""),
})
if err != nil {
logger.Warnf(ctx, "[sandbox-terminal] docker terminate exec create failed container=%s exec=%s: %v",
s.containerID, s.execID, err)
return
}
// Detached: the kill outlives this context and needs no output.
if _, err := s.api.ExecStart(ctx, created.ID, client.ExecStartOptions{Detach: true}); err != nil {
logger.Warnf(ctx, "[sandbox-terminal] docker terminate exec start failed container=%s exec=%s: %v",
s.containerID, s.execID, err)
}
})
}
// dockerTerminalKillCmd builds the argv that hangs up an abandoned PTY shell
// and the processes it started.
//
// It matches on the marker environment variable rather than a PID because
// ExecInspect reports the *host* PID, which is meaningless inside the
// container's PID namespace — a kill exec running there cannot see /proc/<pid>.
// Every process the shell starts inherits ACADEMY_TERMINAL_ID, so walking
// /proc finds the shell and its whole job tree (a running foreground job is in
// its own process group, so signalling the shell or its group alone would
// orphan it). A shell that already exited has no carriers left, which is why
// no existence check is needed before running it.
//
// The signals mirror a terminal emulator closing: SIGHUP (plus SIGCONT so a
// stopped job sees it) ends the shell and its jobs, while anything the user
// detached on purpose with nohup or a HUP trap keeps running, as it would on
// any real terminal. Only the session leader — the shell itself — is SIGKILLed
// if it is still alive after the grace period.
//
// /proc is read directly instead of shelling out to pgrep/pkill, which minimal
// sandbox images do not ship; the entry is compared with a shell `case` rather
// than grep for the same reason.
func dockerTerminalKillCmd(token string) []string {
script := `m="` + dockerTerminalIDEnv + `=$1"
carriers() {
for d in /proc/[0-9]*; do
e=$(tr '\0' '\n' < "$d/environ" 2>/dev/null) || continue
case "$e" in *"$m"*) echo "${d#/proc/}" ;; esac
done
}
pids=$(carriers)
[ -n "$pids" ] || exit 0
kill -HUP $pids 2>/dev/null
kill -CONT $pids 2>/dev/null
sleep 2
for q in $(carriers); do
s=$(cat "/proc/$q/stat" 2>/dev/null) || continue
set -- ${s##*) }
[ "$4" = "$q" ] && kill -9 "$q" 2>/dev/null
done
exit 0`
return []string{"/bin/sh", "-c", script, "academy-terminate", token}
}
// teardown closes the stream and the marker-refresh loop exactly once. Both
// Close and the end of pump call it, so it is the single choke point for the
// idempotent-close contract.
func (s *dockerTerminalSession) teardown() {
s.closeOnce.Do(func() {
close(s.closedCh)
_ = s.conn.Close()
})
}
+478
View File
@@ -0,0 +1,478 @@
package sandbox
import (
"bytes"
"context"
"errors"
"net"
"strings"
"sync"
"testing"
"time"
"github.com/moby/moby/client"
"github.com/stretchr/testify/require"
)
// newTerminalTestClient builds a Docker client with the idle sweep enabled, so
// the terminal's activity-marker refresh actually runs (newTestDockerClient
// disables it). ttl is the sweep window handed to the client.
func newTerminalTestClient(
t *testing.T, engine *fakeDockerEngine, ttl time.Duration,
) *DockerRemoteClient {
t.Helper()
settings, err := dockerSettingsFromConfig(&Config{
Type: SandboxTypeDocker,
DockerImage: "academy/sandbox:test",
})
require.NoError(t, err)
settings.IdleTTL = ttl
return newDockerRemoteClientWithAPI(engine, settings)
}
func TestDockerOpenTerminalConfiguresTTYExec(t *testing.T) {
engine := newFakeDockerEngine()
engine.execStdout = "ready\n"
docker := newTestDockerClient(t, engine)
session, err := docker.OpenTerminal(context.Background(), testHandle("c"),
RemoteTerminalOptions{
Cols: 100, Rows: 40,
User: "user",
Cwd: "/workspace",
Envs: map[string]string{"FOO": "bar"},
})
require.NoError(t, err)
t.Cleanup(func() { _ = session.Close() })
require.Len(t, engine.execOptions, 1)
created := engine.execOptions[0]
require.True(t, created.TTY, "a PTY needs TTY=true")
require.True(t, created.AttachStdin)
require.True(t, created.AttachStdout)
require.True(t, created.AttachStderr)
require.Equal(t, "user", created.User)
require.Equal(t, "/workspace", created.WorkingDir)
require.Equal(t, uint(40), created.ConsoleSize.Height)
require.Equal(t, uint(100), created.ConsoleSize.Width)
require.Contains(t, created.Env, "FOO=bar")
require.Equal(t, []string{
"/bin/sh", "-c",
"if command -v bash >/dev/null 2>&1; then exec bash; else exec sh; fi",
}, created.Cmd, "the PTY must launch an interactive shell, not a bare command")
require.Len(t, engine.attachedOptions, 1)
require.True(t, engine.attachedOptions[0].TTY)
}
// A Docker exec gets only the daemon's TERM=xterm, so with no caller envs (the
// WebSocket handler never sends any) the adapter itself must supply what the
// Cube/E2B SDKs default: 256 colours and a UTF-8 locale.
func TestDockerOpenTerminalDefaultsInteractiveEnv(t *testing.T) {
engine := newFakeDockerEngine()
docker := newTestDockerClient(t, engine)
session, err := docker.OpenTerminal(context.Background(), testHandle("c"),
RemoteTerminalOptions{})
require.NoError(t, err)
t.Cleanup(func() { _ = session.Close() })
require.Len(t, engine.execOptions, 1)
env := engine.execOptions[0].Env
require.Contains(t, env, "TERM=xterm-256color")
require.Contains(t, env, "LANG=C.UTF-8")
require.Contains(t, env, "LC_ALL=C.UTF-8")
require.NotEmpty(t, terminalMarkerToken(t, engine.execOptions[0]))
}
// Caller envs override the defaults, but never the teardown marker: a caller
// that could pick it would steer the terminate exec at another terminal.
func TestDockerOpenTerminalCallerEnvOverridesDefaultsButNotMarker(t *testing.T) {
engine := newFakeDockerEngine()
docker := newTestDockerClient(t, engine)
session, err := docker.OpenTerminal(context.Background(), testHandle("c"),
RemoteTerminalOptions{Envs: map[string]string{
"TERM": "screen",
"LANG": "zh_CN.UTF-8",
dockerTerminalIDEnv: "chosen",
}})
require.NoError(t, err)
t.Cleanup(func() { _ = session.Close() })
env := engine.execOptions[0].Env
require.Contains(t, env, "TERM=screen")
require.Contains(t, env, "LANG=zh_CN.UTF-8")
require.NotContains(t, env, "TERM=xterm-256color")
require.NotEqual(t, "chosen", terminalMarkerToken(t, engine.execOptions[0]))
}
// The hijacked conn does not watch ctx. A PTY that stops reading stdin
// back-pressures Write, and without the ctx deadline the bridge's input loop
// would hang until something else tore the session down.
func TestDockerTerminalWriteHonoursContextDeadline(t *testing.T) {
local, remote := net.Pipe()
t.Cleanup(func() { _ = remote.Close() })
engine := newFakeDockerEngine()
engine.terminalConn = local
docker := newTestDockerClient(t, engine)
session, err := docker.OpenTerminal(context.Background(), testHandle("c"),
RemoteTerminalOptions{})
require.NoError(t, err)
t.Cleanup(func() { _ = session.Close() })
// Nobody reads remote, so the pipe write blocks like a full PTY.
ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
defer cancel()
errCh := make(chan error, 1)
go func() { errCh <- session.Write(ctx, []byte("ls\n")) }()
select {
case err := <-errCh:
require.Error(t, err, "a back-pressured write must give up at the ctx deadline")
case <-time.After(2 * time.Second):
t.Fatal("Write ignored the ctx deadline")
}
// The deadline is per call: a later write without one must not inherit
// the expired deadline and fail immediately.
received := make(chan []byte, 1)
go func() {
buf := make([]byte, 16)
n, _ := remote.Read(buf)
received <- buf[:n]
}()
require.NoError(t, session.Write(context.Background(), []byte("pwd\n")))
require.Equal(t, []byte("pwd\n"), <-received)
}
// The terminate exec is best effort: a daemon refusing to start it must not
// turn Close into an error or a hang.
func TestDockerTerminalCloseToleratesTerminateFailure(t *testing.T) {
engine := newFakeDockerEngine()
engine.terminalBlocks = true
engine.execStartErr = errors.New("daemon refused")
docker := newTestDockerClient(t, engine)
session, err := docker.OpenTerminal(context.Background(), testHandle("c"),
RemoteTerminalOptions{})
require.NoError(t, err)
go drainTerminalOutput(session)
require.NoError(t, session.Close())
require.Len(t, engine.execStarts, 1, "the terminate exec was attempted")
require.NoError(t, session.Close(), "a second Close stays a no-op")
require.Len(t, engine.execStarts, 1)
}
// A TTY attach is a raw byte stream. If the adapter reused the exec path's
// stdcopy demultiplexer here, the first 8 bytes would be eaten as a frame
// header and every keystroke echo would come back garbled.
func TestDockerTerminalStreamsRawBytesAndExitCode(t *testing.T) {
engine := newFakeDockerEngine()
engine.execStdout = "hello\r\n"
engine.execExit = 7
docker := newTestDockerClient(t, engine)
session, err := docker.OpenTerminal(context.Background(), testHandle("c"),
RemoteTerminalOptions{})
require.NoError(t, err)
t.Cleanup(func() { _ = session.Close() })
var got bytes.Buffer
var exitCode *int
deadline := time.After(2 * time.Second)
for exitCode == nil {
select {
case ev, ok := <-session.Output():
require.True(t, ok, "stream closed without an exit event")
require.NoError(t, ev.Err)
if ev.Exited {
code := ev.ExitCode
exitCode = &code
break
}
got.Write(ev.Data)
case <-deadline:
t.Fatalf("timed out waiting for exit; got %q", got.String())
}
}
require.Equal(t, "hello\r\n", got.String(),
"TTY output must be raw, not stdcopy-framed")
require.Equal(t, 7, *exitCode)
}
// The TTY stream can reach EOF before the daemon records the exit; reading the
// exit code once at that moment would report 0 for a shell that failed.
func TestDockerTerminalWaitsForExecExitBeforeReportingCode(t *testing.T) {
engine := newFakeDockerEngine()
engine.execExit = 23
engine.execInspectRunning.Store(2)
docker := newTestDockerClient(t, engine)
session, err := docker.OpenTerminal(context.Background(), testHandle("c"),
RemoteTerminalOptions{})
require.NoError(t, err)
t.Cleanup(func() { _ = session.Close() })
deadline := time.After(3 * time.Second)
for {
select {
case ev, ok := <-session.Output():
require.True(t, ok, "stream closed without an exit event")
require.NoError(t, ev.Err)
if !ev.Exited {
continue
}
require.Equal(t, 23, ev.ExitCode)
require.EqualValues(t, 3, engine.execInspects.Load(),
"the exit code is read only once the exec stops running")
return
case <-deadline:
t.Fatal("timed out waiting for exit")
}
}
}
func TestDockerTerminalWriteResizeAndPID(t *testing.T) {
engine := newFakeDockerEngine()
engine.execInspectPID = 4321
engine.terminalBlocks = true
docker := newTestDockerClient(t, engine)
session, err := docker.OpenTerminal(context.Background(), testHandle("c"),
RemoteTerminalOptions{})
require.NoError(t, err)
t.Cleanup(func() { _ = session.Close() })
require.Zero(t, session.PID(),
"ExecInspect's PID is a host PID; it must not reach the browser as a pty_id")
require.NoError(t, session.Write(context.Background(), []byte("ls\n")))
require.Equal(t, "ls\n", engine.execStdin.String())
require.NoError(t, session.Resize(context.Background(), 120, 30))
require.Len(t, engine.execResizes, 1)
require.Equal(t, uint(30), engine.execResizes[0].Height)
require.Equal(t, uint(120), engine.execResizes[0].Width)
// A zero dimension is the "browser has not measured yet" case; it must
// not reach the daemon.
require.NoError(t, session.Resize(context.Background(), 0, 0))
require.Len(t, engine.execResizes, 1)
}
// RemoteTerminalSession documents Close as safe to call more than once, and
// the bridge can reach it from several goroutines. A check-then-close probe
// on the teardown channel would panic here.
func TestDockerTerminalCloseIsIdempotentUnderConcurrency(t *testing.T) {
engine := newFakeDockerEngine()
engine.terminalBlocks = true
docker := newTestDockerClient(t, engine)
session, err := docker.OpenTerminal(context.Background(), testHandle("c"),
RemoteTerminalOptions{})
require.NoError(t, err)
drained := make(chan struct{})
go func() {
defer close(drained)
drainTerminalOutput(session)
}()
start := make(chan struct{})
var wg sync.WaitGroup
for i := 0; i < 64; i++ {
wg.Add(1)
go func() {
defer wg.Done()
<-start
_ = session.Close()
}()
}
close(start)
wg.Wait()
select {
case <-drained:
case <-time.After(3 * time.Second):
t.Fatal("Output channel never closed after Close")
}
}
// Closing a live terminal must terminate the shell: a Docker exec with a TTY
// survives the hijacked connection going away, so a bare disconnect would
// strand the shell (and its jobs) until the container is swept. Close has to
// issue a kill exec itself, matching the terminal's marker env.
func TestDockerTerminalCloseTerminatesLiveShell(t *testing.T) {
engine := newFakeDockerEngine()
engine.terminalBlocks = true
docker := newTestDockerClient(t, engine)
session, err := docker.OpenTerminal(context.Background(), testHandle("c"),
RemoteTerminalOptions{})
require.NoError(t, err)
// The terminal's own TTY exec, and nothing else yet.
require.Len(t, engine.execOptions, 1)
token := terminalMarkerToken(t, engine.execOptions[0])
go drainTerminalOutput(session)
require.NoError(t, session.Close())
require.Len(t, engine.execOptions, 2, "Close must create a kill exec")
kill := engine.execOptions[1]
require.False(t, kill.TTY)
require.Equal(t, DefaultSandboxExecUser, kill.User)
require.Equal(t, dockerTerminalKillCmd(token), kill.Cmd,
"the kill must carry the terminal's marker token")
require.Len(t, engine.execStarts, 1, "the kill exec must actually be started")
require.True(t, engine.execStarts[0].options.Detach,
"the kill must run detached so it outlives the request context")
}
// The kill matches on the marker env, not a PID: ExecInspect reports a host
// PID that is meaningless inside the container's PID namespace, so a kill that
// targeted it would silently do nothing (the original bug).
func TestDockerTerminalKillCmdTargetsMarkerEnv(t *testing.T) {
cmd := dockerTerminalKillCmd("deadbeef")
require.Equal(t, "/bin/sh", cmd[0])
require.Equal(t, "-c", cmd[1])
require.Equal(t, "academy-terminate", cmd[3])
require.Equal(t, "deadbeef", cmd[4], "the token travels as argv")
require.Contains(t, cmd[2], dockerTerminalIDEnv+"=$1",
"the script matches the marker env")
require.Contains(t, cmd[2], "kill -HUP $pids",
"closing must hang up like a terminal so nohup'd jobs survive")
require.Contains(t, cmd[2], "kill -CONT $pids",
"a stopped job only acts on the hangup once continued")
require.NotContains(t, cmd[2], "kill -9 $pids",
"SIGKILL on every carrier would also take out nohup'd jobs")
require.Contains(t, cmd[2], `[ "$4" = "$q" ] && kill -9`,
"only the session leader (the shell) is force-killed after the grace period")
require.Contains(t, cmd[2], "/proc/[0-9]*", "it must walk every process")
require.NotContains(t, cmd[2], "ExecInspect")
}
// drainTerminalOutput consumes a session's output until the channel closes, so
// the pump never stalls on a full buffer while a test drives Close.
func drainTerminalOutput(session RemoteTerminalSession) {
for event := range session.Output() {
_ = event
}
}
// terminalMarkerToken extracts the ACADEMY_TERMINAL_ID value the adapter set on
// a captured ExecCreate, so a test can predict the kill argv.
func terminalMarkerToken(t *testing.T, opts client.ExecCreateOptions) string {
t.Helper()
prefix := dockerTerminalIDEnv + "="
for _, entry := range opts.Env {
if strings.HasPrefix(entry, prefix) {
return strings.TrimPrefix(entry, prefix)
}
}
t.Fatalf("terminal exec is missing %s: %#v", dockerTerminalIDEnv, opts.Env)
return ""
}
// The marker must be present and unique so two concurrent terminals in one
// container do not kill each other.
func TestDockerOpenTerminalTagsEachSession(t *testing.T) {
engine := newFakeDockerEngine()
engine.execStdout = ""
docker := newTestDockerClient(t, engine)
first, err := docker.OpenTerminal(context.Background(), testHandle("c"), RemoteTerminalOptions{})
require.NoError(t, err)
t.Cleanup(func() { _ = first.Close() })
second, err := docker.OpenTerminal(context.Background(), testHandle("c"), RemoteTerminalOptions{})
require.NoError(t, err)
t.Cleanup(func() { _ = second.Close() })
require.Len(t, engine.execOptions, 2)
a := terminalMarkerToken(t, engine.execOptions[0])
b := terminalMarkerToken(t, engine.execOptions[1])
require.NotEmpty(t, a)
require.NotEqual(t, a, b, "each terminal needs its own marker")
}
// Cancelling the caller's context must end the session, exactly like an
// explicit Close. Nothing else in the adapter honours the context — the pump
// only reads the hijacked stream and the refresh rides a detached context — so
// without a watcher a cancelled context would leak the shell and pin the
// container (its marker stays fresh forever).
func TestDockerTerminalContextCancelEndsSession(t *testing.T) {
engine := newFakeDockerEngine()
engine.terminalBlocks = true
docker := newTestDockerClient(t, engine)
// Signal the terminate exec through a channel: the watcher runs it on its
// own goroutine, so reading the exec slices here would race.
killCreated := make(chan struct{})
var once sync.Once
engine.execCreateHook = func(opts client.ExecCreateOptions) {
if !opts.TTY {
once.Do(func() { close(killCreated) })
}
}
ctx, cancel := context.WithCancel(context.Background())
session, err := docker.OpenTerminal(ctx, testHandle("c"), RemoteTerminalOptions{})
require.NoError(t, err)
go drainTerminalOutput(session)
cancel()
select {
case <-session.(*dockerTerminalSession).closedCh:
case <-time.After(2 * time.Second):
t.Fatal("cancelling the context did not end the terminal session")
}
select {
case <-killCreated:
case <-time.After(2 * time.Second):
t.Fatal("cancelling the context did not run the terminate exec")
}
}
// A PTY never runs the exec wrapper that refreshes the idle-sweep activity
// marker, so the terminal has to do it itself or the container is reclaimed
// mid-use at its TTL.
func TestDockerTerminalRefreshesActivityMarker(t *testing.T) {
prev := terminalTTLRefreshMin
terminalTTLRefreshMin = 20 * time.Millisecond
t.Cleanup(func() { terminalTTLRefreshMin = prev })
engine := newFakeDockerEngine()
engine.terminalBlocks = true
docker := newTerminalTestClient(t, engine, 30*time.Minute)
// The refresh is a plain (non-TTY) exec; observe it through the hook so
// the background goroutine never races the test on the execOptions slice.
var once sync.Once
refreshed := make(chan struct{})
engine.execCreateHook = func(options client.ExecCreateOptions) {
if !options.TTY {
once.Do(func() { close(refreshed) })
}
}
session, err := docker.OpenTerminal(context.Background(), testHandle("c"),
RemoteTerminalOptions{})
require.NoError(t, err)
t.Cleanup(func() { _ = session.Close() })
select {
case <-refreshed:
case <-time.After(2 * time.Second):
t.Fatal("expected a marker-refresh exec while the terminal is open")
}
}
// OpenTerminal must fail with a classified error, not a panic, on a bad handle.
func TestDockerOpenTerminalRejectsEmptyHandle(t *testing.T) {
docker := newTestDockerClient(t, newFakeDockerEngine())
_, err := docker.OpenTerminal(context.Background(), nil, RemoteTerminalOptions{})
require.Error(t, err)
}
@@ -0,0 +1,260 @@
//go:build e2b_integration
// Conformance test for E2B-protocol control planes.
//
// Academy treats "E2B protocol" as the single integration contract for remote
// sandboxes, so the same suite must pass against every implementation of it:
// E2B Cloud, a self-hosted e2b-dev/infra, CubeSandbox's CubeAPI, or a
// container-backed gateway such as Agent-Sandbox. It drives the same public
// surface the agent runtime uses — session-scoped script execution, shell
// commands, attachment staging, artifact listing, teardown — rather than the
// individual client methods, so a backend that passes here is usable by the
// product and not merely reachable.
//
// Run with:
//
// E2B_INTEGRATION_API_URL=http://127.0.0.1:18080/e2b/v1 \
// E2B_INTEGRATION_API_KEY=<token> \
// E2B_INTEGRATION_TEMPLATE=code-interpreter \
// E2B_INTEGRATION_SANDBOX_DOMAIN=localhost \
// E2B_INTEGRATION_PROXY_URL=http://127.0.0.1:18080 \
// go test -tags=e2b_integration ./internal/sandbox \
// -run '^TestE2BCompatibleControlPlaneConformance' -count=1 -v -timeout=15m
//
// E2B_INTEGRATION_PROXY_URL is the data-plane gateway. Leave it empty for E2B
// Cloud, whose sandbox domain resolves through public DNS over TLS.
package sandbox
import (
"bytes"
"context"
"fmt"
"os"
"path"
"strings"
"testing"
"time"
"academy/internal/types"
)
const (
conformanceTenantID = 1
conformanceTTL = 10 * time.Minute
conformanceHTTPTimeut = 60 * time.Second
conformanceExecUser = "E2B_INTEGRATION_EXEC_USER"
)
func TestE2BCompatibleControlPlaneConformance(t *testing.T) {
cfg := e2bCompatibleConfig(t)
client, err := NewE2BRemoteClientWithPool(
cfg,
NewSandboxGatewayTransportPoolWithPolicy(nil, OutboundURLPolicy{AllowPrivate: true}),
)
if err != nil {
t.Fatalf("build E2B-protocol client: %v", err)
}
ctx, cancel := context.WithTimeout(
types.WithSandboxTenantID(context.Background(), conformanceTenantID),
12*time.Minute,
)
defer cancel()
if err := client.Health(ctx); err != nil {
t.Fatalf("control plane health: %v", err)
}
manager, err := NewSessionBoundManager(SessionBoundManagerConfig{
Config: cfg,
Client: client,
Store: NewMemorySessionSandboxBindingStore(),
Checker: PermissiveSessionExistenceChecker{},
ConfigID: "conformance",
SkipHealthProbe: true,
})
if err != nil {
t.Fatalf("NewSessionBoundManager: %v", err)
}
sessionID := fmt.Sprintf("conformance-%d", time.Now().UnixNano())
t.Cleanup(func() {
cleanupCtx, cleanupCancel := context.WithTimeout(
types.WithSandboxTenantID(context.Background(), conformanceTenantID),
2*time.Minute,
)
defer cleanupCancel()
if err := manager.DestroySession(cleanupCtx, sessionID); err != nil {
t.Errorf("DestroySession: %v", err)
}
})
// State is written under the artifact directory rather than an arbitrary
// path: that directory is the one Academy provisions and grants to the
// script account, so the assertion tests session persistence instead of a
// template's /workspace permissions.
counterPath := path.Join(SessionOutputRoot, "counter.txt")
t.Run("SessionScopedStatePersistsAcrossExecutions", func(t *testing.T) {
first := runConformanceScript(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 := runConformanceScript(t, ctx, manager, sessionID, fmt.Sprintf(`
with open(%q) as handle:
print('counter=' + handle.read())
`, counterPath))
if !second.IsSuccess() {
t.Fatalf("second execution failed: %#v", second)
}
if !strings.Contains(second.Stdout, "counter=1") {
t.Fatalf("session state did not persist across executions: stdout=%q stderr=%q",
second.Stdout, second.Stderr)
}
})
t.Run("ShellExecSharesTheSessionSandbox", func(t *testing.T) {
executor := manager.SessionShellExecutor()
if executor == nil {
t.Fatal("session shell executor is unavailable on a healthy remote 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 remote 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 := runConformanceScript(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
break
}
}
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 := runConformanceScriptWithTimeout(t, ctx, manager, sessionID, `
import time
time.sleep(30)
`, 5*time.Second)
if !result.Killed {
t.Fatalf("expected a killed result for an over-running script: %#v", result)
}
})
}
// runConformanceScript executes source as a session-scoped Python script,
// mirroring how the skills runtime invokes the sandbox.
func runConformanceScript(
t *testing.T,
ctx context.Context,
manager *SessionBoundManager,
sessionID string,
source string,
) *ExecuteResult {
t.Helper()
return runConformanceScriptWithTimeout(t, ctx, manager, sessionID, source, 2*time.Minute)
}
func runConformanceScriptWithTimeout(
t *testing.T,
ctx context.Context,
manager *SessionBoundManager,
sessionID string,
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 e2bCompatibleConfig(t *testing.T) *Config {
t.Helper()
apiKey := firstNonEmptyEnvironment("E2B_INTEGRATION_API_KEY", "E2B_API_KEY")
template := firstNonEmptyEnvironment("E2B_INTEGRATION_TEMPLATE", "E2B_TEMPLATE")
if apiKey == "" || template == "" {
t.Skip("E2B-protocol conformance requires an API key and a template")
}
cfg := DefaultConfig()
cfg.Type = SandboxTypeE2B
cfg.AllowPrivateEndpoints = true
cfg.E2BAPIKey = apiKey
cfg.E2BTemplate = template
cfg.E2BAPIURL = strings.TrimSpace(os.Getenv("E2B_INTEGRATION_API_URL"))
cfg.E2BSandboxDomain = strings.TrimSpace(os.Getenv("E2B_INTEGRATION_SANDBOX_DOMAIN"))
cfg.E2BProxyURL = strings.TrimSpace(os.Getenv("E2B_INTEGRATION_PROXY_URL"))
cfg.E2BSandboxTTL = conformanceTTL
cfg.E2BHTTPTimeout = conformanceHTTPTimeut
cfg.DefaultTimeout = 2 * time.Minute
return cfg
}
+151
View File
@@ -0,0 +1,151 @@
package sandbox
import (
"context"
"encoding/binary"
"io"
"net/http"
"net/http/httptest"
"net/url"
"testing"
"time"
"github.com/stretchr/testify/require"
)
type e2bTimeoutTestTransport struct{ target *url.URL }
func (t e2bTimeoutTestTransport) RoundTrip(req *http.Request) (*http.Response, error) {
r := req.Clone(req.Context())
r.URL.Scheme, r.URL.Host = t.target.Scheme, t.target.Host
return http.DefaultTransport.RoundTrip(r)
}
// Exercise the real SDK's command stream with a scaled-down HTTP budget.
// The successful command must outlive that budget, while execution deadlines
// and parent cancellation must still interrupt the same stream.
func TestE2BExecTimeoutBudgets(t *testing.T) {
for _, mode := range []string{"long_command", "execution_deadline", "parent_cancel"} {
t.Run(mode, func(t *testing.T) {
started := make(chan struct{})
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/sandboxes" {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusCreated)
_, _ = io.WriteString(w, `{"sandboxID":"test","envdAccessToken":"token"}`)
return
}
if r.URL.Path != "/process.Process/Start" {
http.NotFound(w, r)
return
}
w.Header().Set("Content-Type", "application/connect+proto")
writeFrame := func(payload []byte) {
header := make([]byte, 5)
binary.BigEndian.PutUint32(header[1:], uint32(len(payload)))
_, _ = w.Write(append(header, payload...))
w.(http.Flusher).Flush()
}
// StartResponse{event:{start:{pid:1}}}. The SDK's protobuf
// types are internal, so these small fixtures use wire bytes.
writeFrame([]byte{0x0a, 4, 0x0a, 2, 0x08, 1})
close(started)
select {
case <-time.After(300 * time.Millisecond):
// StartResponse{event:{end:{exited:true, exit_code:0}}}.
writeFrame([]byte{0x0a, 4, 0x1a, 2, 0x10, 1})
// Connect end-of-stream envelope with empty metadata.
_, _ = w.Write([]byte{2, 0, 0, 0, 2, '{', '}'})
case <-r.Context().Done():
}
}))
defer server.Close()
target, err := url.Parse(server.URL)
require.NoError(t, err)
client, err := newE2BRemoteClient(&Config{
E2BAPIKey: "test", E2BAPIURL: server.URL,
E2BHTTPTimeout: 100 * time.Millisecond,
}, e2bTimeoutTestTransport{target: target}, NewInboundTokenRegistry(), nil)
require.NoError(t, err)
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
handle, err := client.Create(ctx, RemoteCreateRequest{TemplateID: "test"})
require.NoError(t, err)
timeout := 2 * time.Second
if mode == "execution_deadline" {
timeout = 150 * time.Millisecond
}
if mode == "parent_cancel" {
go func() {
select {
case <-started:
cancel()
case <-ctx.Done():
}
}()
}
result, err := client.Exec(ctx, handle, RemoteExecRequest{Command: "test", Timeout: timeout})
switch mode {
case "long_command":
require.NoError(t, err)
require.False(t, result.Killed, "HTTP timeout must not truncate the command stream")
require.Zero(t, result.ExitCode)
case "execution_deadline":
require.NoError(t, err)
require.True(t, result.Killed)
case "parent_cancel":
require.Error(t, err)
}
})
}
}
func TestE2BRPCTimeoutBoundsOrdinaryResponseBodies(t *testing.T) {
for _, route := range []string{"/sandboxes", "/process.Process/List", "/filesystem.Filesystem/MakeDir"} {
t.Run(route, func(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
w.(http.Flusher).Flush()
<-r.Context().Done()
}))
defer server.Close()
client := &http.Client{Transport: &e2bRPCTimeoutTransport{
next: http.DefaultTransport, timeout: 50 * time.Millisecond,
}}
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
req, err := http.NewRequestWithContext(ctx, http.MethodGet, server.URL+route, nil)
require.NoError(t, err)
response, err := client.Do(req)
require.NoError(t, err)
defer response.Body.Close()
_, err = io.ReadAll(response.Body)
require.ErrorIs(t, err, context.DeadlineExceeded)
require.NoError(t, ctx.Err(), "ordinary RPC must expire before the parent budget")
})
}
}
func TestE2BFileTransferUsesCallerContext(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
w.(http.Flusher).Flush()
<-r.Context().Done()
}))
defer server.Close()
client := &http.Client{Transport: &e2bRPCTimeoutTransport{
next: http.DefaultTransport, timeout: 50 * time.Millisecond,
}}
ctx, cancel := context.WithTimeout(context.Background(), 300*time.Millisecond)
defer cancel()
req, err := http.NewRequestWithContext(ctx, http.MethodGet, server.URL+"/files", nil)
require.NoError(t, err)
started := time.Now()
response, err := client.Do(req)
require.NoError(t, err)
defer response.Body.Close()
_, err = io.ReadAll(response.Body)
require.ErrorIs(t, err, context.DeadlineExceeded)
require.Error(t, ctx.Err(), "file transfer must follow the caller deadline, not the RPC budget")
require.Greater(t, time.Since(started), 100*time.Millisecond)
}
+339
View File
@@ -0,0 +1,339 @@
//go:build e2b_integration
// E2B integration tests use a dedicated build tag so they can run independently
// of the legacy Cube integration suite, which currently has a separate
// newCubeClient compile blocker in this workspace.
//
// Run with:
//
// go test -tags=e2b_integration ./internal/sandbox \
// -run '^TestE2BIntegration' -count=1 -v -timeout=15m
package sandbox
import (
"bytes"
"context"
"fmt"
"os"
"strings"
"testing"
"time"
)
const (
e2bIntegrationTTL = 30 * time.Second
e2bIntegrationHTTPTimeout = 30 * time.Second
e2bIntegrationPauseTimeout = 3 * time.Minute
e2bIntegrationPollInterval = 5 * time.Second
)
func TestE2BIntegrationLifecycleParity(t *testing.T) {
cfg := e2bIntegrationConfig(t)
store := NewMemorySessionSandboxBindingStore()
key := SessionSandboxKey{
TenantID: 1,
SessionID: fmt.Sprintf("e2b-integration-%d", time.Now().UnixNano()),
}
createRequest := RemoteCreateRequest{
TemplateID: cfg.E2BTemplate,
Timeout: RemoteTimeoutPolicy{
Mode: RemoteTimeoutExplicit,
Value: e2bIntegrationTTL,
Action: RemoteOnTimeoutPause,
AutoResume: true,
},
}
firstClient := newE2BIntegrationClient(t, cfg)
firstLifecycle := newE2BIntegrationLifecycle(t, firstClient, store, createRequest)
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Minute)
defer cancel()
var sandboxID string
destroyed := false
t.Cleanup(func() {
if sandboxID == "" || destroyed {
return
}
cleanupCtx, cleanupCancel := context.WithTimeout(context.Background(), time.Minute)
defer cleanupCancel()
if err := firstClient.Delete(cleanupCtx, sandboxID); err != nil {
if CanReplaceRemoteBinding(err) {
t.Logf("best-effort cleanup found E2B sandbox %s already absent", sandboxID)
return
}
t.Errorf("best-effort cleanup failed for E2B sandbox %s", sandboxID)
return
}
t.Logf("best-effort cleanup deleted E2B sandbox %s", sandboxID)
})
firstHandle, err := firstLifecycle.Resolve(ctx, key)
if err != nil {
t.Fatalf("initial lifecycle Resolve: %v", err)
}
sandboxID = firstHandle.ID()
if sandboxID == "" {
t.Fatal("initial lifecycle Resolve returned an empty sandbox ID")
}
expectedMetadata := firstLifecycle.metadata(key)
if !metadataMatches(firstHandle.Metadata(), expectedMetadata) {
t.Fatalf("lifecycle-created sandbox handle omitted ownership metadata: got=%v want=%v",
firstHandle.Metadata(), expectedMetadata)
}
base := "/tmp/academy-e2b-integration"
path := base + "/state.txt"
payload := []byte("e2b lifecycle state persists\n")
if err := firstClient.MakeDir(ctx, firstHandle, base); err != nil {
t.Fatalf("MakeDir: %v", err)
}
if err := firstClient.WriteFile(ctx, firstHandle, path, payload); err != nil {
t.Fatalf("WriteFile: %v", err)
}
entries, err := firstClient.ListDir(ctx, firstHandle, base)
if err != nil {
t.Fatalf("ListDir: %v", err)
}
found := false
for _, entry := range entries {
if entry.Name == "state.txt" {
found = true
break
}
}
if !found {
t.Fatalf("ListDir did not return state.txt: %#v", entries)
}
stat, err := firstClient.Stat(ctx, firstHandle, path)
if err != nil {
t.Fatalf("Stat: %v", err)
}
if stat == nil || stat.Type != RemoteEntryFile || stat.Size != int64(len(payload)) {
t.Fatalf("Stat returned unexpected file metadata: %#v", stat)
}
content, err := firstClient.ReadFile(ctx, firstHandle, path)
if err != nil {
t.Fatalf("ReadFile: %v", err)
}
if !bytes.Equal(content, payload) {
t.Fatalf("ReadFile content mismatch: got=%q want=%q", content, payload)
}
waitForE2BSandboxPause(t, ctx, firstClient, sandboxID, expectedMetadata)
secondClient := newE2BIntegrationClient(t, cfg)
secondLifecycle := newE2BIntegrationLifecycle(t, secondClient, store, createRequest)
secondHandle, err := secondLifecycle.Resolve(ctx, key)
if err != nil {
t.Fatalf("Resolve after simulated process restart: %v", err)
}
if secondHandle.ID() != sandboxID {
t.Fatalf("Resolve after restart returned sandbox %s, want %s", secondHandle.ID(), sandboxID)
}
content, err = secondClient.ReadFile(ctx, secondHandle, path)
if err != nil {
t.Fatalf("ReadFile after automatic resume: %v", err)
}
if !bytes.Equal(content, payload) {
t.Fatalf("filesystem state did not survive pause/resume: got=%q want=%q", content, payload)
}
deleted, err := store.DeleteIfMatch(ctx, key, SandboxTypeE2B, sandboxID)
if err != nil {
t.Fatalf("delete binding while preserving remote sandbox: %v", err)
}
if !deleted {
t.Fatal("binding disappeared before metadata-recovery test")
}
thirdClient := newE2BIntegrationClient(t, cfg)
thirdLifecycle := newE2BIntegrationLifecycle(t, thirdClient, store, createRequest)
thirdHandle, err := thirdLifecycle.Resolve(ctx, key)
if err != nil {
t.Fatalf("Resolve after binding loss: %v", err)
}
if thirdHandle.ID() != sandboxID {
t.Fatalf("metadata recovery claimed sandbox %s, want original %s", thirdHandle.ID(), sandboxID)
}
candidates, err := thirdClient.List(ctx, RemoteListFilter{Metadata: expectedMetadata})
if err != nil {
t.Fatalf("List ownership metadata candidates: %v", err)
}
nonterminal := make([]RemoteSandboxSummary, 0, len(candidates))
for _, candidate := range candidates {
if candidate.State != RemoteStateTerminal {
nonterminal = append(nonterminal, candidate)
}
}
if len(nonterminal) != 1 || nonterminal[0].ID != sandboxID {
t.Fatalf("metadata recovery left non-unique candidates: got=%#v want only %s",
nonterminal, sandboxID)
}
if err := thirdClient.Remove(ctx, thirdHandle, path); err != nil {
t.Fatalf("Remove file: %v", err)
}
if err := thirdClient.Remove(ctx, thirdHandle, base); err != nil {
t.Fatalf("Remove directory: %v", err)
}
if err := thirdLifecycle.Destroy(ctx, key); err != nil {
t.Fatalf("lifecycle Destroy: %v", err)
}
binding, err := store.Get(ctx, key)
if err != nil {
t.Fatalf("read binding after lifecycle Destroy: %v", err)
}
if binding != nil {
t.Fatalf("lifecycle Destroy left binding behind: %#v", binding)
}
waitForE2BSandboxDeletion(t, ctx, thirdClient, sandboxID)
destroyed = true
}
func e2bIntegrationConfig(t *testing.T) *Config {
t.Helper()
apiKey := firstNonEmptyEnvironment(
"E2B_INTEGRATION_API_KEY",
"E2B_API_KEY",
)
template := firstNonEmptyEnvironment(
"E2B_INTEGRATION_TEMPLATE",
"E2B_TEMPLATE",
)
if apiKey == "" || template == "" {
t.Skip("E2B integration requires an API key and template")
}
cfg := DefaultConfig()
cfg.Type = SandboxTypeE2B
cfg.E2BAPIKey = apiKey
cfg.E2BAPIURL = strings.TrimSpace(os.Getenv("E2B_INTEGRATION_API_URL"))
cfg.E2BSandboxDomain = strings.TrimSpace(os.Getenv("E2B_INTEGRATION_SANDBOX_DOMAIN"))
cfg.E2BTemplate = template
cfg.E2BSandboxTTL = e2bIntegrationTTL
cfg.E2BHTTPTimeout = e2bIntegrationHTTPTimeout
return cfg
}
func firstNonEmptyEnvironment(names ...string) string {
for _, name := range names {
if value := strings.TrimSpace(os.Getenv(name)); value != "" {
return value
}
}
return ""
}
func newE2BIntegrationClient(t *testing.T, cfg *Config) *E2BRemoteClient {
t.Helper()
client, err := NewE2BRemoteClient(cfg)
if err != nil {
t.Fatalf("NewE2BRemoteClient: %v", err)
}
return client
}
func newE2BIntegrationLifecycle(
t *testing.T,
client *E2BRemoteClient,
store SessionSandboxBindingStore,
createRequest RemoteCreateRequest,
) *remoteSessionLifecycle {
t.Helper()
lifecycle, err := newRemoteSessionLifecycle(
client,
store,
PermissiveSessionExistenceChecker{},
createRequest,
time.Minute,
"",
nil,
)
if err != nil {
t.Fatalf("newRemoteSessionLifecycle: %v", err)
}
return lifecycle
}
func waitForE2BSandboxPause(
t *testing.T,
parent context.Context,
client *E2BRemoteClient,
sandboxID string,
expectedMetadata map[string]string,
) {
t.Helper()
ctx, cancel := context.WithTimeout(parent, e2bIntegrationPauseTimeout)
defer cancel()
ticker := time.NewTicker(e2bIntegrationPollInterval)
defer ticker.Stop()
var lastState RemoteSandboxState
var lastRawState string
for {
summary, err := client.Get(ctx, sandboxID)
if err != nil {
t.Fatalf("E2B control plane did not return the sandbox as paused with lifecycle "+
"metadata; Get stopped returning sandbox %s before the %s deadline: %v",
sandboxID, e2bIntegrationPauseTimeout, err)
}
if summary == nil {
t.Fatal("control-plane Get returned nil while waiting for pause")
}
lastState = summary.State
lastRawState = summary.RawState
if summary.State == RemoteStatePaused {
if !metadataMatches(summary.Metadata, expectedMetadata) {
t.Fatalf("paused sandbox omitted lifecycle metadata: got=%v want=%v",
summary.Metadata, expectedMetadata)
}
return
}
select {
case <-ctx.Done():
t.Fatalf("E2B control plane did not report paused sandbox with metadata within %s; "+
"last state=%s raw_state=%q", e2bIntegrationPauseTimeout, lastState, lastRawState)
case <-ticker.C:
}
}
}
func waitForE2BSandboxDeletion(
t *testing.T,
parent context.Context,
client *E2BRemoteClient,
sandboxID string,
) {
t.Helper()
const deletionTimeout = time.Minute
ctx, cancel := context.WithTimeout(parent, deletionTimeout)
defer cancel()
ticker := time.NewTicker(e2bIntegrationPollInterval)
defer ticker.Stop()
var lastState RemoteSandboxState
for {
summary, err := client.Get(ctx, sandboxID)
if IsRemoteNotFound(err) {
return
}
if err != nil {
t.Fatalf("Get while verifying lifecycle Destroy: %v", err)
}
if summary != nil {
lastState = summary.State
}
select {
case <-ctx.Done():
t.Fatalf("E2B sandbox %s remained visible for %s after lifecycle Destroy; "+
"last state=%s", sandboxID, deletionTimeout, lastState)
case <-ticker.C:
}
}
}
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+35
View File
@@ -0,0 +1,35 @@
package sandbox
import (
"context"
"net/http"
"time"
)
// Keep the HTTP budget on ordinary requests (including their response bodies).
// Start and Connect stream for the command's lifetime and are bounded by the
// SDK's execution context instead. Parent cancellation is preserved throughout.
type e2bRPCTimeoutTransport struct {
next http.RoundTripper
timeout time.Duration
}
func (t *e2bRPCTimeoutTransport) RoundTrip(req *http.Request) (*http.Response, error) {
if t.timeout <= 0 || req.URL.Path == "/process.Process/Start" || req.URL.Path == "/process.Process/Connect" || isFilesystemContentRPC(req.URL.Path) {
return t.next.RoundTrip(req)
}
ctx, cancel := context.WithTimeout(req.Context(), t.timeout)
response, err := t.next.RoundTrip(req.Clone(ctx))
if err != nil {
cancel()
return nil, err
}
response.Body = &cancelOnCloseBody{ReadCloser: response.Body, cancel: cancel}
return response, nil
}
func (t *e2bRPCTimeoutTransport) CloseIdleConnections() {
if closer, ok := t.next.(interface{ CloseIdleConnections() }); ok {
closer.CloseIdleConnections()
}
}
+208
View File
@@ -0,0 +1,208 @@
// Package sandbox: interactive terminal capability for the E2B adapter.
//
// go-e2b wraps envd's PTY service (sandbox.Pty). Output is delivered through
// a Wait-driven callback, so the adapter pumps it into a channel from a
// dedicated goroutine; input and resize are plain unary RPCs on the same
// service.
package sandbox
import (
"context"
"errors"
"strings"
"sync"
e2b "github.com/matiasinsaurralde/go-e2b"
)
// Compile-time proof that the E2B adapter serves the terminal capability.
var _ RemoteTerminalManager = (*E2BRemoteClient)(nil)
// OpenTerminal opens an interactive shell PTY inside the sandbox behind
// handle. The returned session keeps streaming until the shell exits, the
// context passed to OpenTerminal is cancelled (the session derives its own
// lifetime from it), or Close is called.
func (c *E2BRemoteClient) OpenTerminal(
ctx context.Context,
handle RemoteSandboxHandle,
opts RemoteTerminalOptions,
) (RemoteTerminalSession, error) {
if _, err := e2bHandleSandbox("OpenTerminal", handle); err != nil {
return nil, err
}
sandboxID := strings.TrimSpace(handle.ID())
// Reattach rather than reuse the handle's sandbox: the connect refreshes
// the sandbox lifetime exactly like RemoteSandboxClient.Connect does,
// which doubles as the activity signal for TTL-based reclamation. The
// client carries no HTTP-level timeout, and e2bRPCTimeoutTransport
// exempts the PTY's Start/Connect routes, so the stream is bounded by
// ptyCtx alone rather than by E2BHTTPTimeout.
timeoutSeconds, err := e2bTimeoutSeconds(RemoteTimeoutPolicy{Mode: RemoteTimeoutServerDefault}, c.timeout)
if err != nil {
return nil, normalizeE2BError("OpenTerminal", err)
}
sbx, err := c.client.Connect(ctx, sandboxID, timeoutSeconds)
if err != nil {
return nil, normalizeE2BError("OpenTerminal", err)
}
if sbx.TrafficAccessToken == "" {
sbx.TrafficAccessToken = handleTrafficAccessToken(handle)
}
c.inboundTokens.Put(sbx.ID, sbx.TrafficAccessToken)
// The terminal session — not the SDK's per-command timeout — owns the
// PTY lifetime: WithPtyTimeout(0) disables the context wrapping so the
// stream survives as long as ptyCtx below.
ptyOpts := []e2b.PtyOption{
e2b.WithPtyTimeout(0),
e2b.WithPtyCwd(terminalCwd(opts)),
e2b.WithPtyUser(terminalUser(opts)),
}
if envs := terminalEnvs(opts); len(envs) > 0 {
ptyOpts = append(ptyOpts, e2b.WithPtyEnv(envs))
}
ptyCtx, cancel := context.WithCancel(ctx)
cmdHandle, err := openE2BPty(ptyCtx, sbx, opts, ptyOpts)
if err != nil {
cancel()
return nil, normalizeE2BError("OpenTerminal", err)
}
session := &e2bTerminalSession{
sbx: sbx,
handle: cmdHandle,
pid: cmdHandle.PID(),
out: make(chan RemoteTerminalEvent, terminalOutputBuffer),
ctx: ptyCtx,
cancel: cancel,
closedCh: make(chan struct{}),
timeoutSeconds: timeoutSeconds,
}
// envd SendInput is a unary RPC. Waiting for it on the WebSocket read
// path makes typing feel one-RTT-per-key; E2B's data plane is far
// enough that that is noticeable. Queue and coalesce instead.
session.input = newPtyInputCoalescer(ptyCtx, session.closedCh, func(rctx context.Context, data []byte) error {
return session.sbx.Pty.SendInput(rctx, session.pid, data)
})
go session.pump()
if timeoutSeconds > 0 {
startTerminalTTLRefresh(ptyCtx, session.closedCh, c.timeout, func(rctx context.Context) error {
return session.sbx.SetTimeoutWithContext(rctx, session.timeoutSeconds)
})
}
return session, nil
}
func openE2BPty(
ctx context.Context,
sbx *e2b.Sandbox,
opts RemoteTerminalOptions,
ptyOpts []e2b.PtyOption,
) (*e2b.CommandHandle, error) {
if opts.AttachPID > 0 {
handle, err := sbx.Pty.Connect(ctx, opts.AttachPID, ptyOpts...)
if err == nil {
return handle, nil
}
}
return sbx.Pty.Create(ctx, terminalCols(opts), terminalRows(opts), ptyOpts...)
}
// e2bTerminalSession bridges one go-e2b PTY handle to the neutral
// RemoteTerminalSession contract.
type e2bTerminalSession struct {
sbx *e2b.Sandbox
handle *e2b.CommandHandle
pid uint32
out chan RemoteTerminalEvent
ctx context.Context
cancel context.CancelFunc
closedCh chan struct{}
closeOnce sync.Once
timeoutSeconds int
input *ptyInputCoalescer
}
// pump drains the PTY event stream. go-e2b dispatches output only while
// Wait runs, so the Wait call lives here for the whole session. The output
// channel closes exactly once, when pump returns.
func (s *e2bTerminalSession) pump() {
defer close(s.out)
result, err := s.handle.Wait(s.ctx, e2b.WithWaitOnPty(func(chunk []byte) {
s.emit(RemoteTerminalEvent{Data: chunk})
}))
// Close (or OpenTerminal-context cancellation) tears the stream down;
// that is teardown, not a terminal failure — report nothing further.
select {
case <-s.closedCh:
return
default:
}
if err != nil {
var exitErr *e2b.CommandExitError
if errors.As(err, &exitErr) {
// The shell exited with a non-zero status. That is still a
// normal terminal end from the consumer's point of view.
s.emit(RemoteTerminalEvent{Exited: true, ExitCode: exitErr.ExitCode})
return
}
s.emit(RemoteTerminalEvent{Err: normalizeE2BError("terminal stream", err)})
return
}
code := -1
if result != nil {
code = result.ExitCode
}
s.emit(RemoteTerminalEvent{Exited: true, ExitCode: code})
}
func (s *e2bTerminalSession) emit(event RemoteTerminalEvent) {
emitTerminalEvent(s.out, s.closedCh, event)
}
func (s *e2bTerminalSession) Output() <-chan RemoteTerminalEvent { return s.out }
func (s *e2bTerminalSession) PID() uint32 { return s.pid }
func (s *e2bTerminalSession) Write(ctx context.Context, data []byte) error {
if s.input == nil {
if len(data) == 0 {
return nil
}
if err := s.sbx.Pty.SendInput(ctx, s.pid, data); err != nil {
return normalizeE2BError("terminal input", err)
}
return nil
}
if err := s.input.Write(ctx, data); err != nil {
return normalizeE2BError("terminal input", err)
}
return nil
}
func (s *e2bTerminalSession) Resize(ctx context.Context, cols, rows uint32) error {
if cols == 0 || rows == 0 {
return nil
}
if err := s.sbx.Pty.Resize(ctx, s.pid, cols, rows); err != nil {
return normalizeE2BError("terminal resize", err)
}
return nil
}
// Close disconnects Academy from the PTY without killing the remote shell,
// leaving it reattachable via Pty.Connect. The pump goroutine observes the
// disconnect and closes the output channel silently.
func (s *e2bTerminalSession) Close() error {
s.closeOnce.Do(func() {
close(s.closedCh)
s.cancel()
})
return s.handle.Disconnect()
}
+145
View File
@@ -0,0 +1,145 @@
// Package sandbox: envd protocol compatibility for the E2B data plane.
//
// The sandbox-side daemon (envd) authenticates every data-plane call with HTTP
// Basic auth carrying the sandbox account name, and accepts file uploads only
// as multipart/form-data. github.com/matiasinsaurralde/go-e2b predates both:
// it sends the account in an X-User-ID header and POSTs file contents as a raw
// octet-stream body.
//
// E2B Cloud's own gateway is lenient enough to hide the difference, so the gap
// only surfaces against other implementations of the protocol — the very
// backends Academy wants to support without carrying one adapter per vendor.
// Rather than fork the SDK, this transport rewrites the two data-plane details
// on the way out:
//
// - it adds "Authorization: Basic base64(user:)" when the request carries no
// credentials of its own;
// - it re-wraps a non-multipart /files upload as multipart/form-data.
//
// Requests are recognised by path, not by host, so the shim works whether the
// data plane is reached directly or through a gateway (gateway_transport.go).
// Control-plane calls never use these paths and pass through untouched.
package sandbox
import (
"bytes"
"encoding/base64"
"fmt"
"io"
"mime/multipart"
"net/http"
"path"
"strings"
)
// envdFilesRoute is envd's upload/download endpoint.
const envdFilesRoute = "/files"
// envdUploadFormField is the multipart field name envd reads the payload from.
const envdUploadFormField = "file"
// NewEnvdCompatTransport wraps next so E2B data-plane requests satisfy the
// current envd contract. A blank user leaves authentication untouched.
func NewEnvdCompatTransport(next http.RoundTripper, user string) http.RoundTripper {
if next == nil {
next = http.DefaultTransport
}
return &envdCompatTransport{next: next, user: strings.TrimSpace(user)}
}
type envdCompatTransport struct {
next http.RoundTripper
user string
}
func (t *envdCompatTransport) RoundTrip(req *http.Request) (*http.Response, error) {
if !isEnvdDataPlaneRequest(req) {
return t.next.RoundTrip(req)
}
rewritten := req.Clone(req.Context())
if t.user != "" && rewritten.Header.Get("Authorization") == "" {
user := t.user
if req.URL.Path == envdFilesRoute || strings.HasPrefix(req.URL.Path, "/filesystem.Filesystem/") {
user = remoteFileUser(req.Context())
}
rewritten.Header.Set("Authorization", basicAuthorizationFor(user))
}
if err := rewriteEnvdUpload(rewritten); err != nil {
return nil, err
}
return t.next.RoundTrip(rewritten)
}
func (t *envdCompatTransport) CloseIdleConnections() {
if closer, ok := t.next.(interface{ CloseIdleConnections() }); ok {
closer.CloseIdleConnections()
}
}
// isEnvdDataPlaneRequest reports whether req addresses envd rather than the
// control plane. envd serves /files plus the ConnectRPC services generated
// from its proto package.
func isEnvdDataPlaneRequest(req *http.Request) bool {
if req == nil || req.URL == nil {
return false
}
requestPath := req.URL.Path
if requestPath == envdFilesRoute {
return true
}
return strings.HasPrefix(requestPath, "/filesystem.Filesystem/") ||
strings.HasPrefix(requestPath, "/process.Process/")
}
// basicAuthorizationFor builds envd's credential: the account name as the
// username with an empty password.
func basicAuthorizationFor(user string) string {
return "Basic " + base64.StdEncoding.EncodeToString([]byte(user+":"))
}
// rewriteEnvdUpload converts a raw-body upload into the multipart form envd
// expects. Uploads that already are multipart, and every non-upload request,
// are left alone.
func rewriteEnvdUpload(req *http.Request) error {
if req.Method != http.MethodPost || req.URL.Path != envdFilesRoute {
return nil
}
if strings.HasPrefix(req.Header.Get("Content-Type"), "multipart/") {
return nil
}
if req.Body == nil {
return nil
}
payload, err := io.ReadAll(req.Body)
_ = req.Body.Close()
if err != nil {
return fmt.Errorf("sandbox: read envd upload body: %w", err)
}
filename := path.Base(strings.TrimSpace(req.URL.Query().Get("path")))
if filename == "" || filename == "." || filename == "/" {
filename = envdUploadFormField
}
var form bytes.Buffer
writer := multipart.NewWriter(&form)
part, err := writer.CreateFormFile(envdUploadFormField, filename)
if err != nil {
return fmt.Errorf("sandbox: build envd upload form: %w", err)
}
if _, err := part.Write(payload); err != nil {
return fmt.Errorf("sandbox: write envd upload form: %w", err)
}
if err := writer.Close(); err != nil {
return fmt.Errorf("sandbox: close envd upload form: %w", err)
}
body := form.Bytes()
req.Header.Set("Content-Type", writer.FormDataContentType())
req.ContentLength = int64(len(body))
req.Body = io.NopCloser(bytes.NewReader(body))
req.GetBody = func() (io.ReadCloser, error) {
return io.NopCloser(bytes.NewReader(body)), nil
}
return nil
}
@@ -0,0 +1,163 @@
package sandbox
import (
"bytes"
"encoding/base64"
"io"
"mime"
"mime/multipart"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/stretchr/testify/require"
)
// recordingRoundTripper captures the request the shim produced.
type recordingRoundTripper struct {
request *http.Request
body []byte
}
func (r *recordingRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
r.request = req
if req.Body != nil {
body, err := io.ReadAll(req.Body)
if err != nil {
return nil, err
}
r.body = body
}
return &http.Response{
StatusCode: http.StatusOK,
Body: io.NopCloser(strings.NewReader("")),
Header: make(http.Header),
Request: req,
}, nil
}
func TestEnvdCompatTransportAuthenticatesDataPlaneCalls(t *testing.T) {
recorder := &recordingRoundTripper{}
transport := NewEnvdCompatTransport(recorder, DefaultSandboxExecUser)
request := httptest.NewRequest(
http.MethodPost,
"https://49983-sbx.example.com/filesystem.Filesystem/MakeDir",
strings.NewReader("{}"),
)
_, err := transport.RoundTrip(request)
require.NoError(t, err)
require.Equal(t,
"Basic "+base64.StdEncoding.EncodeToString([]byte(DefaultSandboxExecUser+":")),
recorder.request.Header.Get("Authorization"),
)
}
// A caller that already authenticated must win: the shim fills a gap, it does
// not override credentials.
func TestEnvdCompatTransportKeepsExistingAuthorization(t *testing.T) {
recorder := &recordingRoundTripper{}
transport := NewEnvdCompatTransport(recorder, "user")
request := httptest.NewRequest(
http.MethodGet,
"https://49983-sbx.example.com/files?path=/workspace/a.txt",
nil,
)
request.Header.Set("Authorization", "Basic preset")
_, err := transport.RoundTrip(request)
require.NoError(t, err)
require.Equal(t, "Basic preset", recorder.request.Header.Get("Authorization"))
}
// Control-plane traffic shares the same transport, so the shim must leave it
// untouched - an unexpected Authorization header there would replace the API
// key the SDK sends.
func TestEnvdCompatTransportIgnoresControlPlaneCalls(t *testing.T) {
recorder := &recordingRoundTripper{}
transport := NewEnvdCompatTransport(recorder, "user")
request := httptest.NewRequest(http.MethodGet, "https://api.e2b.app/v2/sandboxes", nil)
_, err := transport.RoundTrip(request)
require.NoError(t, err)
require.Empty(t, recorder.request.Header.Get("Authorization"))
}
func TestEnvdCompatTransportRewritesUploadAsMultipart(t *testing.T) {
recorder := &recordingRoundTripper{}
transport := NewEnvdCompatTransport(recorder, "user")
payload := []byte("print('hi')\n")
request := httptest.NewRequest(
http.MethodPost,
"https://49983-sbx.example.com/files?path=/workspace/script.py&username=user",
bytes.NewReader(payload),
)
request.Header.Set("Content-Type", "application/octet-stream")
_, err := transport.RoundTrip(request)
require.NoError(t, err)
contentType := recorder.request.Header.Get("Content-Type")
mediaType, params, err := mime.ParseMediaType(contentType)
require.NoError(t, err)
require.Equal(t, "multipart/form-data", mediaType)
require.EqualValues(t, len(recorder.body), recorder.request.ContentLength)
reader := multipart.NewReader(bytes.NewReader(recorder.body), params["boundary"])
part, err := reader.NextPart()
require.NoError(t, err)
require.Equal(t, envdUploadFormField, part.FormName())
require.Equal(t, "script.py", part.FileName())
content, err := io.ReadAll(part)
require.NoError(t, err)
require.Equal(t, payload, content)
}
// Uploads that already are multipart must pass through byte-for-byte.
func TestEnvdCompatTransportPreservesMultipartUploads(t *testing.T) {
recorder := &recordingRoundTripper{}
transport := NewEnvdCompatTransport(recorder, "user")
var form bytes.Buffer
writer := multipart.NewWriter(&form)
part, err := writer.CreateFormFile(envdUploadFormField, "already.txt")
require.NoError(t, err)
_, err = part.Write([]byte("body"))
require.NoError(t, err)
require.NoError(t, writer.Close())
original := form.Bytes()
request := httptest.NewRequest(
http.MethodPost,
"https://49983-sbx.example.com/files?path=/workspace/already.txt",
bytes.NewReader(original),
)
request.Header.Set("Content-Type", writer.FormDataContentType())
_, err = transport.RoundTrip(request)
require.NoError(t, err)
require.Equal(t, writer.FormDataContentType(), recorder.request.Header.Get("Content-Type"))
require.Equal(t, original, recorder.body)
}
// A download shares the /files route with uploads; only the POST body is
// rewritten.
func TestEnvdCompatTransportLeavesDownloadsAlone(t *testing.T) {
recorder := &recordingRoundTripper{}
transport := NewEnvdCompatTransport(recorder, "user")
request := httptest.NewRequest(
http.MethodGet,
"https://49983-sbx.example.com/files?path=/workspace/a.txt",
nil,
)
_, err := transport.RoundTrip(request)
require.NoError(t, err)
require.Empty(t, recorder.request.Header.Get("Content-Type"))
require.Empty(t, recorder.body)
}
+97
View File
@@ -0,0 +1,97 @@
package sandbox
import (
"context"
"io"
"net/http"
"strings"
"time"
)
// Only the server's skill installer may select the maintenance identity.
// Ordinary filesystem operations use the same account as shell/script exec.
type maintenanceFilesystemKey struct{}
func withMaintenanceFilesystem(ctx context.Context) context.Context {
return context.WithValue(ctx, maintenanceFilesystemKey{}, true)
}
func remoteFileUser(ctx context.Context) string {
if maintenance, _ := ctx.Value(maintenanceFilesystemKey{}).(bool); maintenance {
return "root"
}
return DefaultSandboxExecUser
}
// Cube's SDK hardcodes root for file calls and offers no file-user option.
// Scope this compatibility adapter to filesystem routes; process requests
// already carry their explicitly selected user, and control-plane auth must
// be preserved. Request-local context avoids shared-client identity races.
type cubeFilesystemTransport struct {
next http.RoundTripper
timeout time.Duration
}
func (t *cubeFilesystemTransport) RoundTrip(req *http.Request) (*http.Response, error) {
r := req.Clone(req.Context())
if r.URL.Path == envdFilesRoute || strings.HasPrefix(r.URL.Path, "/filesystem.Filesystem/") {
r.Header.Set("Authorization", basicAuthorizationFor(remoteFileUser(req.Context())))
}
// A client-wide HTTP timeout also aborts long-running command streams
// and large file bodies. Bound ordinary RPCs here; process calls and
// filesystem content transfers use the caller's execution context.
if t.timeout <= 0 || rpcUsesCallerDeadline(r.URL.Path) {
return t.next.RoundTrip(r)
}
ctx, cancel := context.WithTimeout(r.Context(), t.timeout)
response, err := t.next.RoundTrip(r.WithContext(ctx))
if err != nil {
cancel()
return nil, err
}
response.Body = &cancelOnCloseBody{ReadCloser: response.Body, cancel: cancel}
return response, nil
}
type cancelOnCloseBody struct {
io.ReadCloser
cancel context.CancelFunc
}
func (b *cancelOnCloseBody) Close() error {
defer b.cancel()
return b.ReadCloser.Close()
}
func rpcUsesCallerDeadline(path string) bool {
if strings.HasPrefix(path, "/process.Process/") {
return true
}
if isFilesystemContentRPC(path) {
return true
}
return isCubeSandboxSnapshotRPC(path)
}
// isCubeSandboxSnapshotRPC reports POST /sandboxes/{id}/snapshots. Cube pauses
// the live MicroVM and copies its disk; that exceeds CubeHTTPTimeout (30s).
func isCubeSandboxSnapshotRPC(path string) bool {
const prefix = "/sandboxes/"
const suffix = "/snapshots"
if !strings.HasPrefix(path, prefix) || !strings.HasSuffix(path, suffix) {
return false
}
id := strings.TrimSuffix(strings.TrimPrefix(path, prefix), suffix)
return id != "" && !strings.Contains(id, "/")
}
func isFilesystemContentRPC(path string) bool {
if path == envdFilesRoute {
return true
}
name, ok := strings.CutPrefix(path, "/filesystem.Filesystem/")
if !ok {
return false
}
return strings.HasPrefix(name, "Read") || strings.HasPrefix(name, "Write")
}
@@ -0,0 +1,115 @@
package sandbox
import (
"context"
"net/http"
"net/http/httptest"
"os"
"os/exec"
"path/filepath"
"testing"
"time"
"github.com/stretchr/testify/require"
)
func TestCubeFilesystemIdentityIsRequestScoped(t *testing.T) {
for _, route := range []string{"/files?path=/workspace/a", "/filesystem.Filesystem/MakeDir"} {
recorder := &recordingRoundTripper{}
transport := &cubeFilesystemTransport{next: recorder}
for _, maintenance := range []bool{false, true, false} {
ctx := context.Background()
user := DefaultSandboxExecUser
if maintenance {
ctx = withMaintenanceFilesystem(ctx)
user = "root"
}
req := httptest.NewRequest(http.MethodGet, "https://sandbox.example"+route, nil).WithContext(ctx)
req.Header.Set("Authorization", basicAuthorizationFor("root"))
_, err := transport.RoundTrip(req)
require.NoError(t, err)
require.Equal(t, basicAuthorizationFor(user), recorder.request.Header.Get("Authorization"))
require.Equal(t, basicAuthorizationFor("root"), req.Header.Get("Authorization"), "input request must not be mutated")
}
}
for _, route := range []string{"/sandboxes", "/process.Process/Start"} {
recorder := &recordingRoundTripper{}
req := httptest.NewRequest(http.MethodPost, "https://sandbox.example"+route, nil)
req.Header.Set("Authorization", "preserve-me")
_, err := (&cubeFilesystemTransport{next: recorder}).RoundTrip(req)
require.NoError(t, err)
require.Equal(t, "preserve-me", recorder.request.Header.Get("Authorization"))
}
}
func TestEnvdMaintenanceFilesystemIdentity(t *testing.T) {
recorder := &recordingRoundTripper{}
transport := NewEnvdCompatTransport(recorder, DefaultSandboxExecUser)
req := httptest.NewRequest(http.MethodGet, "https://sandbox.example/files", nil).
WithContext(withMaintenanceFilesystem(context.Background()))
_, err := transport.RoundTrip(req)
require.NoError(t, err)
require.Equal(t, basicAuthorizationFor("root"), recorder.request.Header.Get("Authorization"))
}
func TestWorkspaceBootstrapDoesNotRemoveOrMoveFiles(t *testing.T) {
root := t.TempDir()
blocked := filepath.Join(root, "existing-file")
require.NoError(t, os.WriteFile(blocked, []byte("keep this"), 0600))
cmd := exec.Command("/bin/sh", "-c", workspaceBootstrapCommand(blocked))
require.Error(t, cmd.Run())
content, err := os.ReadFile(blocked)
require.NoError(t, err)
require.Equal(t, "keep this", string(content))
link := filepath.Join(root, "link")
require.NoError(t, os.Symlink(root, link))
require.Error(t, exec.Command("/bin/sh", "-c", workspaceBootstrapCommand(link)).Run())
_, err = os.Lstat(link)
require.NoError(t, err)
valid := filepath.Join(root, "space ' quote", "nested")
require.NoError(t, exec.Command("/bin/sh", "-c", workspaceBootstrapCommand(valid)).Run())
info, err := os.Stat(valid)
require.NoError(t, err)
require.True(t, info.IsDir())
}
func TestFileTransferSkipsShortHTTPTimeout(t *testing.T) {
parent, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
assertBudget := func(t *testing.T, transport http.RoundTripper, route string, short bool) {
t.Helper()
recorder := &recordingRoundTripper{}
switch typed := transport.(type) {
case *cubeFilesystemTransport:
typed.next = recorder
case *e2bRPCTimeoutTransport:
typed.next = recorder
default:
t.Fatalf("unexpected transport %T", transport)
}
req := httptest.NewRequest(http.MethodGet, "https://sandbox.example"+route, nil).WithContext(parent)
_, err := transport.RoundTrip(req)
require.NoError(t, err)
deadline, ok := recorder.request.Context().Deadline()
require.True(t, ok)
remaining := time.Until(deadline)
if short {
require.Less(t, remaining, 200*time.Millisecond)
return
}
require.Greater(t, remaining, time.Second)
}
cube := &cubeFilesystemTransport{timeout: 50 * time.Millisecond}
e2b := &e2bRPCTimeoutTransport{timeout: 50 * time.Millisecond}
assertBudget(t, cube, "/files?path=/workspace/a", false)
assertBudget(t, cube, "/filesystem.Filesystem/WriteFile", false)
assertBudget(t, cube, "/filesystem.Filesystem/MakeDir", true)
assertBudget(t, cube, "/process.Process/Start", false)
assertBudget(t, cube, "/sandboxes/sbx-1/snapshots", false)
assertBudget(t, e2b, "/files", false)
assertBudget(t, e2b, "/filesystem.Filesystem/Read", false)
assertBudget(t, e2b, "/filesystem.Filesystem/MakeDir", true)
assertBudget(t, e2b, "/process.Process/List", true)
assertBudget(t, e2b, "/process.Process/Start", false)
}
+272
View File
@@ -0,0 +1,272 @@
// Package sandbox: connection pooling and data-plane routing for per-request
// remote clients.
//
// Named configs build a fresh client on every Resolve, so without an
// externally owned transport every request would open new TCP connections to
// both the control plane and the envd data plane.
//
// Remote backends speak two planes with different dialling rules:
//
// - control plane (Create/Connect/List) talks to the API URL directly;
// - data plane (exec, filesystem) addresses sandboxes as
// "49983-{id}.{domain}", which E2B Cloud resolves through public DNS and
// TLS. Self-hosted E2B-compatible control planes (CubeSandbox's CubeProxy,
// Agent-Sandbox's gateway, e2b-dev/infra's client proxy) instead front
// every sandbox with one gateway address and route on the Host header.
//
// Handing an SDK one http.Client for both planes drops that distinction, which
// only appears to work when DNS happens to resolve the sandbox domain to the
// gateway on the same port. This file keeps the two planes apart by routing per
// request: control traffic rides the process-wide transport shared by every
// backend, data traffic rides a transport cached per gateway endpoint so
// configs pointing at the same gateway share one pool.
//
// The gateway may also be plain HTTP. Both SDKs pin the data-plane scheme to
// https, so a http:// gateway URL additionally rewrites the request scheme
// rather than forcing operators to terminate TLS in front of a local cluster.
package sandbox
import (
"context"
"net"
"net/http"
"net/url"
"strconv"
"strings"
"sync"
"time"
)
// SandboxGatewayTransportPool owns the transports handed to per-request remote
// clients. One instance lives for the process; clients built from it come and
// go.
type SandboxGatewayTransportPool struct {
control http.RoundTripper
policy OutboundURLPolicy
inboundTokens *InboundTokenRegistry
// data maps a gateway "host:port" to the transport that dials it.
data sync.Map
}
// NewSandboxGatewayTransportPool returns a pool whose control plane rides
// control. A nil control transport installs a guarded one.
func NewSandboxGatewayTransportPool(control http.RoundTripper) *SandboxGatewayTransportPool {
return NewSandboxGatewayTransportPoolWithPolicy(control, DefaultOutboundURLPolicy())
}
func NewSandboxGatewayTransportPoolWithPolicy(
control http.RoundTripper,
policy OutboundURLPolicy,
) *SandboxGatewayTransportPool {
if control == nil {
control = NewGuardedTransportWithPolicy(policy)
}
return &SandboxGatewayTransportPool{
control: control,
policy: policy,
inboundTokens: NewInboundTokenRegistry(),
}
}
// InboundTokens is the registry the data-plane transport consults to attach a
// sandbox's inbound credential. Adapters register on create / connect.
func (p *SandboxGatewayTransportPool) InboundTokens() *InboundTokenRegistry {
return p.inboundTokens
}
// RoundTripperFor returns the transport a client built from cfg should use.
// Configs without a usable gateway URL keep every request on the control
// transport, matching the SDKs' behaviour when no gateway is configured.
func (p *SandboxGatewayTransportPool) RoundTripperFor(cfg *Config) http.RoundTripper {
gatewayURL, controlURL := gatewayEndpointFor(cfg)
split := &gatewaySplitTransport{
control: p.control,
controlHost: hostOfURL(controlURL),
inboundToken: p.inboundTokens,
}
if host, port, scheme, ok := parseProxyURL(gatewayURL); ok {
split.data = p.dataTransport(net.JoinHostPort(host, strconv.Itoa(port)))
split.dataScheme = scheme
}
return split
}
// attachInboundTokenTransport puts inbound-token injection on next. A pool
// RoundTripperFor result already injects from the same registry and is
// returned unchanged. nil next becomes the default transport so RoundTrip
// does not panic.
func attachInboundTokenTransport(
next http.RoundTripper,
tokens *InboundTokenRegistry,
) http.RoundTripper {
if tokens == nil {
return next
}
if split, ok := next.(*gatewaySplitTransport); ok && split.inboundToken == tokens {
return next
}
if next == nil {
next = http.DefaultTransport
}
return &gatewaySplitTransport{
control: next,
inboundToken: tokens,
}
}
// gatewayEndpointFor reads the active provider's gateway and control-plane
// endpoints. Reading them per provider (rather than merging both) keeps a stale
// sub-struct left behind by an earlier provider switch from routing today's
// traffic.
func gatewayEndpointFor(cfg *Config) (gatewayURL, controlURL string) {
if cfg == nil {
return "", ""
}
switch cfg.Type {
case SandboxTypeE2B:
return cfg.E2BProxyURL, cfg.E2BAPIURL
default:
return cfg.CubeProxyURL, cfg.CubeAPIURL
}
}
// hostOfURL returns raw's lowercased hostname without its port, or "" when raw
// is empty or unparseable.
func hostOfURL(raw string) string {
raw = strings.TrimSpace(raw)
if raw == "" {
return ""
}
parsed, err := url.Parse(raw)
if err != nil {
return ""
}
return strings.ToLower(parsed.Hostname())
}
// dataTransport returns the transport dialling target, creating it once.
func (p *SandboxGatewayTransportPool) dataTransport(target string) http.RoundTripper {
if existing, ok := p.data.Load(target); ok {
return existing.(http.RoundTripper)
}
actual, _ := p.data.LoadOrStore(target, newGatewayDataTransportWithPolicy(target, p.policy))
return actual.(http.RoundTripper)
}
// newGatewayDataTransportWithPolicy dials target regardless of the request's
// authority, preserving the gateway rewrite and the configured outbound guard.
func newGatewayDataTransportWithPolicy(target string, policy OutboundURLPolicy) *http.Transport {
// The same guarded dial as the websocket data plane: in whitelist-only
// mode a non-whitelisted gateway hostname is refused before this resolves
// it, and the policy's Control hook then judges the address (#3378). The
// SDK's authority is ignored — the gateway is addressed by `target`.
guardedDial := GuardedDialContext(policy)
return &http.Transport{
// The gateway is addressed directly; an ambient HTTP proxy would
// defeat the rewrite.
Proxy: nil,
DialContext: func(ctx context.Context, network, _ string) (net.Conn, error) {
return guardedDial(ctx, network, target)
},
MaxIdleConns: 100,
MaxIdleConnsPerHost: 4,
IdleConnTimeout: 90 * time.Second,
}
}
// gatewaySplitTransport routes a request to the control or the data transport
// by looking at the authority the SDK addressed.
type gatewaySplitTransport struct {
control http.RoundTripper
data http.RoundTripper
// controlHost is the API endpoint's hostname. It is an exclusion, not the
// routing rule: the rule is the sandbox authority shape, and this only
// covers an API host that happens to wear that shape.
controlHost string
inboundToken *InboundTokenRegistry
// dataScheme is the gateway's scheme. When it differs from the scheme the
// SDK hardcoded, data-plane requests are rewritten before dialling.
dataScheme string
}
func (t *gatewaySplitTransport) RoundTrip(req *http.Request) (*http.Response, error) {
req = t.withInboundToken(req)
if t.data == nil || !t.isDataPlane(req.URL.Hostname()) {
return t.control.RoundTrip(req)
}
return t.data.RoundTrip(t.applyGatewayScheme(req))
}
// withInboundToken attaches the sandbox's inbound credential when one is
// registered. It runs before the data/control split because a deployment
// without a gateway URL keeps sandbox traffic on the control transport, and
// those requests need the header just as much.
//
// An existing header wins: Cube's SDK sets it from the sandbox object, and
// overwriting that with our copy would turn a fresh token into a stale one.
func (t *gatewaySplitTransport) withInboundToken(req *http.Request) *http.Request {
if t.inboundToken == nil || req.Header.Get(InboundTokenHeader) != "" {
return req
}
sandboxID := sandboxIDFromDataPlaneHost(req.URL.Host)
if sandboxID == "" {
return req
}
token := t.inboundToken.Get(sandboxID)
if token == "" {
return req
}
// Clone rather than mutate: the caller owns req, and the SDK may retry it.
cloned := req.Clone(req.Context())
cloned.Header.Set(InboundTokenHeader, token)
return cloned
}
// applyGatewayScheme returns req addressed with the gateway's scheme. The
// sandbox authority is preserved so the gateway can still route on Host.
func (t *gatewaySplitTransport) applyGatewayScheme(req *http.Request) *http.Request {
if t.dataScheme == "" || t.dataScheme == req.URL.Scheme {
return req
}
rewritten := req.Clone(req.Context())
url := *req.URL
url.Scheme = t.dataScheme
rewritten.URL = &url
return rewritten
}
// isDataPlane reports whether host addresses a sandbox rather than the control
// plane, by the "<port>-<sandboxID>.<domain>" authority shape both SDKs
// generate — the same test withInboundToken already applies to the same
// request.
//
// It deliberately does NOT compare against the configured sandbox domain.
// That field is optional for E2B, and go-e2b's envdBaseURL prefers whatever
// domain the control plane reported over the client-wide one, so the authority
// actually dialled need not appear anywhere in the config. Matching on it
// meant a configured gateway was silently never used, and — because the check
// was a suffix match — that E2B's own defaults (api.e2b.app under sandbox
// domain e2b.app) sent every control-plane call to the gateway instead.
//
// The control host is excluded explicitly because the shape test alone would
// accept an API host like "8080-api.example.com".
func (t *gatewaySplitTransport) isDataPlane(host string) bool {
host = strings.ToLower(strings.TrimSpace(host))
if host == "" || (t.controlHost != "" && host == t.controlHost) {
return false
}
return sandboxIDFromDataPlaneHost(host) != ""
}
// CloseIdleConnections keeps the SDK's post-rollback reset meaningful. Only
// the data pool is dropped: the control transport is shared with every other
// tenant and every other backend, and one sandbox's restart is no reason to
// close it.
func (t *gatewaySplitTransport) CloseIdleConnections() {
if closer, ok := t.data.(interface{ CloseIdleConnections() }); ok {
closer.CloseIdleConnections()
}
}
+266
View File
@@ -0,0 +1,266 @@
package sandbox
import (
"context"
"net/http"
"net/http/httptest"
"sync"
"testing"
"time"
"github.com/stretchr/testify/require"
)
// countingRoundTripper records how many requests rode the control transport.
type countingRoundTripper struct {
next http.RoundTripper
mu sync.Mutex
hosts []string
}
func (c *countingRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
c.mu.Lock()
c.hosts = append(c.hosts, req.URL.Host)
c.mu.Unlock()
return c.next.RoundTrip(req)
}
func (c *countingRoundTripper) seen() []string {
c.mu.Lock()
defer c.mu.Unlock()
return append([]string(nil), c.hosts...)
}
// The data plane addresses sandboxes as "49983-{id}.{domain}" but must dial
// the configured proxy. Sharing one transport across both planes drops that
// rewrite, which is exactly the regression this guards: the proxy has to see
// the request, and it has to see the sandbox authority in the Host header.
func TestSandboxGatewayTransportPoolRoutesDataPlaneThroughProxy(t *testing.T) {
api := newCubeMockServer(t)
var mu sync.Mutex
var proxyHosts []string
proxy := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
mu.Lock()
proxyHosts = append(proxyHosts, r.Host)
mu.Unlock()
api.handle(w, r)
}))
t.Cleanup(proxy.Close)
cfg := testConfig(t, api)
cfg.AllowPrivateEndpoints = true
cfg.CubeProxyURL = proxy.URL
policy := OutboundURLPolicy{AllowPrivate: true}
control := &countingRoundTripper{next: NewGuardedTransportWithPolicy(policy)}
client, err := NewCubeRemoteClientWithPool(cfg, NewSandboxGatewayTransportPoolWithPolicy(control, policy))
require.NoError(t, err)
ctx := context.Background()
handle, err := client.Create(ctx, RemoteCreateRequest{
TemplateID: "template-a",
Timeout: RemoteTimeoutPolicy{
Mode: RemoteTimeoutExplicit,
Value: time.Minute,
Action: RemoteOnTimeoutKill,
},
})
require.NoError(t, err)
api.SetExecutor(func(string, string, []string) (string, string, int) {
return "ok", "", 0
})
result, err := client.Exec(ctx, handle, RemoteExecRequest{Command: "echo", Args: []string{"ok"}})
require.NoError(t, err)
require.Equal(t, 0, result.ExitCode)
mu.Lock()
gotProxyHosts := append([]string(nil), proxyHosts...)
mu.Unlock()
require.NotEmpty(t, gotProxyHosts, "data plane never reached the proxy")
require.Contains(t, gotProxyHosts[0], "49983-"+handle.ID()+".cube.app")
// Control-plane calls ride the shared transport; data-plane calls do not.
for _, host := range control.seen() {
require.NotContains(t, host, "cube.app")
}
require.NotEmpty(t, control.seen())
}
// Configs pointing at the same proxy must share one pool - otherwise building
// a client per request pools nothing.
func TestSandboxGatewayTransportPoolReusesTransportPerProxyEndpoint(t *testing.T) {
pool := NewSandboxGatewayTransportPoolWithPolicy(
NewGuardedTransportWithPolicy(OutboundURLPolicy{AllowPrivate: true}),
OutboundURLPolicy{AllowPrivate: true},
)
first := pool.RoundTripperFor(&Config{
CubeProxyURL: "http://127.0.0.1:8080",
CubeSandboxDomain: "cube.app",
}).(*gatewaySplitTransport)
second := pool.RoundTripperFor(&Config{
CubeProxyURL: "http://127.0.0.1:8080",
CubeSandboxDomain: "cube.app",
}).(*gatewaySplitTransport)
other := pool.RoundTripperFor(&Config{
CubeProxyURL: "http://127.0.0.1:9090",
CubeSandboxDomain: "cube.app",
}).(*gatewaySplitTransport)
require.Same(t, first.data, second.data)
require.NotSame(t, first.data, other.data)
require.Same(t, first.control, other.control)
}
// Without a usable proxy URL the SDK dials the sandbox authority directly, so
// the split transport must not invent a data plane.
func TestSandboxGatewayTransportPoolWithoutProxyKeepsEverythingOnControl(t *testing.T) {
pool := NewSandboxGatewayTransportPool(NewGuardedTransport())
split := pool.RoundTripperFor(&Config{CubeSandboxDomain: "cube.app"}).(*gatewaySplitTransport)
// A nil data transport is what sends sandbox authorities back to control.
require.Nil(t, split.data)
}
// A self-hosted E2B-compatible control plane fronts every sandbox with one
// gateway, so the E2B provider must read its own gateway fields - and a plain
// HTTP gateway has to survive the SDK pinning the data-plane scheme to https.
func TestSandboxGatewayTransportPoolRoutesE2BDataPlane(t *testing.T) {
pool := NewSandboxGatewayTransportPoolWithPolicy(
NewGuardedTransportWithPolicy(OutboundURLPolicy{AllowPrivate: true}),
OutboundURLPolicy{AllowPrivate: true},
)
split := pool.RoundTripperFor(&Config{
Type: SandboxTypeE2B,
E2BProxyURL: "http://127.0.0.1:18080",
E2BSandboxDomain: "localhost",
// Cube fields must be ignored for an E2B config.
CubeProxyURL: "http://127.0.0.1:9999",
CubeSandboxDomain: "cube.app",
}).(*gatewaySplitTransport)
require.NotNil(t, split.data)
require.Equal(t, "http", split.dataScheme)
require.True(t, split.isDataPlane("49983-sbx.localhost"))
// The Cube fields must not have been read. Asserting on the address the
// transport dials pins that directly; the previous version asserted that a
// cube.app authority was not data-plane traffic, which tested the domain
// matching that has since been removed rather than the field selection.
require.Same(t, split.data, pool.dataTransport("127.0.0.1:18080"))
require.NotSame(t, split.data, pool.dataTransport("127.0.0.1:9999"))
}
// The configured sandbox domain is not a reliable way to recognise data-plane
// traffic. sandbox_domain is optional for E2B (MissingRequiredFields does not
// demand it) and, more fundamentally, go-e2b's envdBaseURL prefers the domain
// the control plane reported over the client-wide one — so the authority the
// SDK actually dials can differ from anything in the config. Matching on it
// meant a configured gateway was silently never used.
func TestGatewaySplitTransportRoutesDataPlaneWithoutConfiguredDomain(t *testing.T) {
pool := NewSandboxGatewayTransportPoolWithPolicy(
NewGuardedTransportWithPolicy(OutboundURLPolicy{AllowPrivate: true}),
OutboundURLPolicy{AllowPrivate: true},
)
split := pool.RoundTripperFor(&Config{
Type: SandboxTypeE2B,
E2BProxyURL: "http://127.0.0.1:18080",
}).(*gatewaySplitTransport)
require.NotNil(t, split.data)
require.True(t, split.isDataPlane("49983-sbx-1.e2b.app"),
"an empty sandbox_domain must not disable the gateway")
}
// Same root cause, reachable even with the domain filled in: the control plane
// may report a domain the config never mentioned.
func TestGatewaySplitTransportRoutesDataPlaneOnServerReportedDomain(t *testing.T) {
split := &gatewaySplitTransport{
control: NewGuardedTransport(),
data: NewGuardedTransport(),
}
require.True(t, split.isDataPlane("49983-sbx-1.reported-by-server.example"))
}
// E2B's own defaults are api.e2b.app plus sandbox domain e2b.app, so suffix
// matching classified every control-plane call as data-plane traffic and dialled
// it at the gateway — sending X-API-Key to the wrong endpoint, and downgrading
// it to plaintext when the gateway is http://.
func TestGatewaySplitTransportKeepsControlHostOnControlTransport(t *testing.T) {
pool := NewSandboxGatewayTransportPoolWithPolicy(
NewGuardedTransportWithPolicy(OutboundURLPolicy{AllowPrivate: true}),
OutboundURLPolicy{AllowPrivate: true},
)
split := pool.RoundTripperFor(&Config{
Type: SandboxTypeE2B,
E2BAPIURL: "https://api.mydomain.com",
E2BSandboxDomain: "mydomain.com",
E2BProxyURL: "http://127.0.0.1:18080",
}).(*gatewaySplitTransport)
require.False(t, split.isDataPlane("api.mydomain.com"))
require.True(t, split.isDataPlane("49983-sbx-1.mydomain.com"))
}
// An API host that happens to wear the data-plane shape is why the control host
// is excluded explicitly rather than left to the shape test.
func TestGatewaySplitTransportExcludesControlHostShapedLikeSandbox(t *testing.T) {
pool := NewSandboxGatewayTransportPoolWithPolicy(
NewGuardedTransportWithPolicy(OutboundURLPolicy{AllowPrivate: true}),
OutboundURLPolicy{AllowPrivate: true},
)
split := pool.RoundTripperFor(&Config{
Type: SandboxTypeE2B,
E2BAPIURL: "https://8080-api.mydomain.com",
E2BSandboxDomain: "mydomain.com",
E2BProxyURL: "http://127.0.0.1:18080",
}).(*gatewaySplitTransport)
require.False(t, split.isDataPlane("8080-api.mydomain.com"))
}
func TestGatewaySplitTransportAppliesGatewayScheme(t *testing.T) {
recorder := &recordingRoundTripper{}
split := &gatewaySplitTransport{
control: &recordingRoundTripper{},
data: recorder,
dataScheme: "http",
}
request := httptest.NewRequest(http.MethodGet, "https://49983-sbx.localhost/files", nil)
_, err := split.RoundTrip(request)
require.NoError(t, err)
require.Equal(t, "http", recorder.request.URL.Scheme)
// The sandbox authority is what the gateway routes on; it must survive.
require.Equal(t, "49983-sbx.localhost", recorder.request.URL.Host)
require.Equal(t, "https", request.URL.Scheme, "the caller's request must not be mutated")
}
func TestGatewaySplitTransportClassifiesAuthorities(t *testing.T) {
split := &gatewaySplitTransport{
control: NewGuardedTransport(),
data: NewGuardedTransport(),
controlHost: "api.cube.app",
}
require.True(t, split.isDataPlane("49983-abc.cube.app"))
require.True(t, split.isDataPlane("49983-ABC.Cube.App"))
require.True(t, split.isDataPlane("49983-abc.cube.app:443"),
"an explicit port must not change the classification")
require.False(t, split.isDataPlane("api.cube.app"))
require.False(t, split.isDataPlane("api.example.com"))
// Nothing that lacks the "<port>-<id>" first label is data-plane traffic.
require.False(t, split.isDataPlane("evilcube.app"))
require.False(t, split.isDataPlane("cube.app"))
require.False(t, split.isDataPlane("no-digits.cube.app"))
require.False(t, split.isDataPlane(""))
}
@@ -0,0 +1,91 @@
// Inbound traffic-token registry.
//
// Cube and E2B sandboxes only accept requests carrying their per-sandbox
// traffic token. Cube's SDK attaches that header
// itself once Sandbox.TrafficAccessToken is set, but go-e2b stores the token
// and never sends it — so for E2B the header has to be added by the one
// component Academy owns on that path: the data-plane RoundTripper.
//
// This registry is the lookup that makes it possible. It is process-local and
// lost on restart, which is fine: the first reconnect after a restart carries
// the token up from the session binding and re-registers it.
package sandbox
import (
"strconv"
"strings"
"sync"
)
// InboundTokenHeader is the header both providers accept. Cube additionally
// accepts "cube-traffic-access-token"; sending the E2B spelling covers both.
const InboundTokenHeader = "e2b-traffic-access-token"
// InboundTokenRegistry maps a sandbox ID to its inbound credential.
type InboundTokenRegistry struct {
tokens sync.Map // sandboxID -> string
}
// NewInboundTokenRegistry returns an empty registry.
func NewInboundTokenRegistry() *InboundTokenRegistry {
return &InboundTokenRegistry{}
}
// Put records the token for sandboxID. An empty token is not stored
// (Docker, or a handle that omitted the credential).
func (r *InboundTokenRegistry) Put(sandboxID, token string) {
if r == nil || sandboxID == "" || token == "" {
return
}
r.tokens.Store(strings.ToLower(sandboxID), token)
}
// Get returns the token for sandboxID, or "" when none is known.
func (r *InboundTokenRegistry) Get(sandboxID string) string {
if r == nil || sandboxID == "" {
return ""
}
if value, ok := r.tokens.Load(strings.ToLower(sandboxID)); ok {
return value.(string)
}
return ""
}
// Delete forgets sandboxID. Called when the sandbox is destroyed.
func (r *InboundTokenRegistry) Delete(sandboxID string) {
if r == nil || sandboxID == "" {
return
}
r.tokens.Delete(strings.ToLower(sandboxID))
}
// sandboxIDFromDataPlaneHost extracts the sandbox ID from an envd authority of
// the form "<port>-<sandboxID>.<domain>", or "" when host is not one.
//
// Matching on this shape rather than on the configured sandbox domain is
// deliberate: an E2B Cloud deployment may leave sandbox_domain empty and let
// the SDK resolve its own default, and a domain-based check would then never
// fire. The registry lookup is the real authority — only Cube/E2B sandboxes
// whose token Academy recorded are in it.
func sandboxIDFromDataPlaneHost(host string) string {
host = strings.ToLower(strings.TrimSpace(host))
if host == "" {
return ""
}
if idx := strings.LastIndex(host, ":"); idx != -1 && !strings.Contains(host[idx:], "]") {
host = host[:idx]
}
label, _, found := strings.Cut(host, ".")
if !found {
return ""
}
port, sandboxID, found := strings.Cut(label, "-")
if !found || sandboxID == "" {
return ""
}
if _, err := strconv.Atoi(port); err != nil {
return ""
}
return sandboxID
}
@@ -0,0 +1,171 @@
package sandbox
import (
"net/http"
"net/http/httptest"
"testing"
"github.com/stretchr/testify/require"
)
func TestSandboxIDFromDataPlaneHost(t *testing.T) {
// envd is addressed as "<port>-<sandboxID>.<domain>".
require.Equal(t, "sb-123", sandboxIDFromDataPlaneHost("49983-sb-123.cube.app"))
require.Equal(t, "i9x8", sandboxIDFromDataPlaneHost("80-i9x8.e2b.app"))
require.Equal(t, "sb-1", sandboxIDFromDataPlaneHost("49983-sb-1.gateway.internal:8443"))
// Control-plane and malformed authorities carry no sandbox.
require.Empty(t, sandboxIDFromDataPlaneHost("api.e2b.app"))
require.Empty(t, sandboxIDFromDataPlaneHost("notaport-sb-1.cube.app"))
require.Empty(t, sandboxIDFromDataPlaneHost("49983-.cube.app"))
require.Empty(t, sandboxIDFromDataPlaneHost(""))
}
func TestInboundTokenRegistryLifecycle(t *testing.T) {
registry := NewInboundTokenRegistry()
require.Empty(t, registry.Get("sb-1"))
registry.Put("sb-1", "token-1")
require.Equal(t, "token-1", registry.Get("sb-1"))
// An empty token means "inbound is open"; storing it would be noise.
registry.Put("sb-1", "")
require.Equal(t, "token-1", registry.Get("sb-1"))
registry.Delete("sb-1")
require.Empty(t, registry.Get("sb-1"))
}
func TestInboundTokenRegistryNormalizesSandboxIDCase(t *testing.T) {
registry := NewInboundTokenRegistry()
registry.Put("Sb-MiXeD", "token-1")
require.Equal(t, "token-1", registry.Get("Sb-MiXeD"))
sandboxID := sandboxIDFromDataPlaneHost("49983-SB-MIXED.e2b.app")
require.Equal(t, "sb-mixed", sandboxID)
require.Equal(t, "token-1", registry.Get(sandboxID))
registry.Delete("SB-MIXED")
require.Empty(t, registry.Get("sb-mixed"))
}
func TestGatewayTransportInjectsInboundToken(t *testing.T) {
var gotToken string
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
gotToken = r.Header.Get("e2b-traffic-access-token")
w.WriteHeader(http.StatusOK)
}))
defer server.Close()
pool := NewSandboxGatewayTransportPoolWithPolicy(
server.Client().Transport,
OutboundURLPolicy{AllowPrivate: true},
)
pool.InboundTokens().Put("sb-1", "token-1")
cfg := DefaultConfig()
cfg.Type = SandboxTypeE2B
cfg.E2BProxyURL = server.URL
cfg.E2BSandboxDomain = "e2b.app"
client := &http.Client{Transport: pool.RoundTripperFor(cfg)}
req, err := http.NewRequest(http.MethodGet, server.URL, nil)
require.NoError(t, err)
req.Host = "49983-sb-1.e2b.app"
req.URL.Host = "49983-sb-1.e2b.app"
_, err = client.Transport.RoundTrip(req)
require.NoError(t, err)
require.Equal(t, "token-1", gotToken,
"go-e2b never sends this header, so the transport has to")
}
func TestGatewayTransportLeavesUnknownSandboxAlone(t *testing.T) {
pool := NewSandboxGatewayTransportPool(nil)
recorder := &roundTripRecorder{}
transport := &gatewaySplitTransport{
control: recorder,
inboundToken: pool.InboundTokens(),
}
req, err := http.NewRequest(http.MethodGet, "https://49983-sb-unknown.e2b.app/", nil)
require.NoError(t, err)
_, err = transport.RoundTrip(req)
require.NoError(t, err)
require.Empty(t, recorder.lastHeader)
require.False(t, recorder.lastHeaderPresent)
}
func TestGatewayTransportInjectsInboundTokenOnControlPath(t *testing.T) {
recorder := &roundTripRecorder{}
pool := NewSandboxGatewayTransportPool(recorder)
pool.InboundTokens().Put("sb-1", "token-1")
cfg := DefaultConfig()
cfg.Type = SandboxTypeE2B
cfg.E2BSandboxDomain = "e2b.app"
transport := pool.RoundTripperFor(cfg)
req, err := http.NewRequest(http.MethodGet, "https://49983-sb-1.e2b.app/", nil)
require.NoError(t, err)
_, err = transport.RoundTrip(req)
require.NoError(t, err)
require.Equal(t, "token-1", recorder.lastHeader)
}
// Cube's SDK sets the header itself; the transport must not clobber it.
func TestGatewayTransportDoesNotOverwriteExistingToken(t *testing.T) {
pool := NewSandboxGatewayTransportPool(nil)
pool.InboundTokens().Put("sb-1", "registry-token")
recorder := &roundTripRecorder{}
transport := &gatewaySplitTransport{
control: recorder,
inboundToken: pool.InboundTokens(),
}
req, err := http.NewRequest(http.MethodGet, "https://49983-sb-1.cube.app/", nil)
require.NoError(t, err)
req.Header.Set("e2b-traffic-access-token", "sdk-token")
_, err = transport.RoundTrip(req)
require.NoError(t, err)
require.Equal(t, "sdk-token", recorder.lastHeader)
}
func TestAttachInboundTokenTransportInjectsWithoutPool(t *testing.T) {
recorder := &roundTripRecorder{}
registry := NewInboundTokenRegistry()
registry.Put("sb-1", "token-1")
transport := attachInboundTokenTransport(recorder, registry)
req, err := http.NewRequest(http.MethodGet, "https://49983-sb-1.e2b.app/envd", nil)
require.NoError(t, err)
_, err = transport.RoundTrip(req)
require.NoError(t, err)
require.Equal(t, "token-1", recorder.lastHeader,
"NewE2BRemoteClient / WithTransport must still inject without a gateway pool")
}
func TestAttachInboundTokenTransportDoesNotDoubleWrapPoolSplit(t *testing.T) {
pool := NewSandboxGatewayTransportPool(http.DefaultTransport)
cfg := DefaultConfig()
cfg.Type = SandboxTypeE2B
split := pool.RoundTripperFor(cfg)
require.Same(t, split, attachInboundTokenTransport(split, pool.InboundTokens()),
"a pool split already injects from this registry")
}
// roundTripRecorder stands in for the control transport and remembers what
// header the request carried by the time it got there.
type roundTripRecorder struct {
lastHeader string
lastHeaderPresent bool
}
func (r *roundTripRecorder) RoundTrip(req *http.Request) (*http.Response, error) {
r.lastHeader = req.Header.Get(InboundTokenHeader)
_, r.lastHeaderPresent = req.Header[http.CanonicalHeaderKey(InboundTokenHeader)]
return &http.Response{
StatusCode: http.StatusOK,
Body: http.NoBody,
Header: make(http.Header),
Request: req,
}, nil
}
+102
View File
@@ -0,0 +1,102 @@
package sandbox
import (
"context"
"fmt"
"strings"
"time"
)
// RemoteSandboxKeepAliver refreshes a sandbox's provider idle timer.
// Background work runs outside chat turns, so nothing else tells the provider
// the sandbox is still in use. Cube and E2B move their timeout to ttl from
// now; Docker runs a no-op exec, which refreshes the activity marker its idle
// sweeper reads.
type RemoteSandboxKeepAliver interface {
KeepAlive(ctx context.Context, handle RemoteSandboxHandle, ttl time.Duration) error
}
// keepAliverFrom narrows client to keep-alive. It looks through the Langfuse
// decorator rather than having the decorator forward: every client
// NewSessionBoundManager holds is wrapped, and a forwarding method would make
// a client without the capability look like it has one.
func keepAliverFrom(client RemoteSandboxClient) (RemoteSandboxKeepAliver, bool) {
switch c := client.(type) {
case nil:
return nil, false
case *langfuseRemoteClient:
return keepAliverFrom(c.inner)
case *langfuseSnapshotClient:
return keepAliverFrom(c.inner)
}
keeper, ok := client.(RemoteSandboxKeepAliver)
return keeper, ok
}
var (
_ RemoteSandboxKeepAliver = (*CubeRemoteClient)(nil)
_ RemoteSandboxKeepAliver = (*E2BRemoteClient)(nil)
_ RemoteSandboxKeepAliver = (*DockerRemoteClient)(nil)
)
// keepAliveRefreshDivisor sets how often a caller refreshes: every TTL/3
// (shared design §5), so two missed refreshes still land before expiry.
const keepAliveRefreshDivisor = 3
// KeepAliveSession refreshes the provider idle timer of the sandbox bound to
// sessionID and returns how long the caller may wait before the next refresh.
// It is lookup-only: it never provisions, never rebuilds and never connects to
// anything but the bound sandbox, so a session with nothing bound, or a
// provider with nothing to refresh, returns (0, nil).
func (m *SessionBoundManager) KeepAliveSession(ctx context.Context, sessionID string) (time.Duration, error) {
return m.keepAliveSession(ctx, sessionID, "")
}
// KeepAliveSessionExpected is KeepAliveSession for callers that selected a
// specific sandbox. Lookup is only against expectedSandboxID: a missing
// binding or a different sandbox returns (0, nil) and never allocates.
func (m *SessionBoundManager) KeepAliveSessionExpected(
ctx context.Context, sessionID, expectedSandboxID string,
) (time.Duration, error) {
return m.keepAliveSession(ctx, sessionID, expectedSandboxID)
}
func (m *SessionBoundManager) keepAliveSession(
ctx context.Context, sessionID, expectedSandboxID string,
) (time.Duration, error) {
if err := m.requireRemoteBackend(); err != nil {
return 0, err
}
keeper, ok := keepAliverFrom(m.client)
if !ok {
return 0, nil
}
req, err := buildSessionCreateRequest(m.client.Provider(), m.config)
if err != nil {
return 0, err
}
ttl := req.Timeout.Value
if ttl <= 0 {
return 0, nil
}
sc, err := m.scope(ctx, sessionID)
if err != nil {
return 0, err
}
handle, found, err := m.lookupSessionHandleForKey(ctx, sc.machine(), expectedSandboxID)
if err != nil {
// A mismatched expected id is "not this sandbox", not a failure to refresh
// and not a reason to allocate a replacement.
if expectedSandboxID != "" && strings.Contains(err.Error(), "bound sandbox changed") {
return 0, nil
}
return 0, err
}
if !found {
return 0, nil
}
if err := keeper.KeepAlive(ctx, handle, ttl); err != nil {
return 0, fmt.Errorf("sandbox: keep session sandbox alive: %w", err)
}
return ttl / keepAliveRefreshDivisor, nil
}
+244
View File
@@ -0,0 +1,244 @@
package sandbox
import (
"context"
"errors"
"sync"
"testing"
"time"
"github.com/stretchr/testify/require"
"academy/internal/types"
)
type keepAliveCall struct {
sandboxID string
ttl time.Duration
}
// keepAliveFakeClient adds the keep-alive capability to the shared fake.
type keepAliveFakeClient struct {
*fakeRemoteClient
keepMu sync.Mutex
keepCalls []keepAliveCall
keepErr error
}
func (c *keepAliveFakeClient) KeepAlive(_ context.Context, handle RemoteSandboxHandle, ttl time.Duration) error {
c.keepMu.Lock()
defer c.keepMu.Unlock()
id := ""
if handle != nil {
id = handle.ID()
}
c.keepCalls = append(c.keepCalls, keepAliveCall{sandboxID: id, ttl: ttl})
return c.keepErr
}
func (c *keepAliveFakeClient) calls() []keepAliveCall {
c.keepMu.Lock()
defer c.keepMu.Unlock()
return append([]keepAliveCall(nil), c.keepCalls...)
}
func pausingCreateRequest() RemoteCreateRequest {
return RemoteCreateRequest{
TemplateID: "template-a",
Timeout: RemoteTimeoutPolicy{
Mode: RemoteTimeoutExplicit, Value: 15 * time.Minute,
Action: RemoteOnTimeoutPause, AutoResume: true,
},
}
}
func TestCubeKeepAliveRefreshesTimeout(t *testing.T) {
mock := newCubeMockServer(t)
client := newTestCubeRemoteClient(t, mock)
handle, err := client.Create(context.Background(), pausingCreateRequest())
require.NoError(t, err)
before := mock.timeoutPOSTs.Load()
require.NoError(t, client.KeepAlive(context.Background(), handle, 30*time.Minute))
require.Equal(t, before+1, mock.timeoutPOSTs.Load())
}
func TestE2BKeepAliveRefreshesTimeout(t *testing.T) {
mock := newE2BMockServer(t)
client := newTestE2BRemoteClient(t, mock)
handle, err := client.Create(context.Background(), pausingCreateRequest())
require.NoError(t, err)
before := mock.timeoutPOSTs.Load()
require.NoError(t, client.KeepAlive(context.Background(), handle, 5*time.Minute))
require.Equal(t, before+1, mock.timeoutPOSTs.Load())
}
func TestDockerKeepAliveRunsANoOpExecThatTouchesTheActivityMarker(t *testing.T) {
engine := newFakeDockerEngine()
docker := newTestDockerClient(t, engine)
require.NoError(t, docker.KeepAlive(context.Background(), testHandle("container-1"), time.Minute))
require.Len(t, engine.execOptions, 1)
cmd := engine.execOptions[0].Cmd
require.Contains(t, cmd[2], dockerActivityMarker)
require.Equal(t, []string{"academy-exec", "true"}, cmd[3:])
}
func TestKeepAliverFromSeesThroughLangfuse(t *testing.T) {
inner := &keepAliveFakeClient{fakeRemoteClient: newFakeRemoteClient(SandboxTypeCube)}
keeper, ok := keepAliverFrom(wrapLangfuseRemoteClient(inner))
require.True(t, ok)
require.NoError(t, keeper.KeepAlive(context.Background(), nil, time.Minute))
require.Equal(t, []keepAliveCall{{ttl: time.Minute}}, inner.calls())
}
func TestKeepAliverFromRejectsClientWithoutTheCapability(t *testing.T) {
_, ok := keepAliverFrom(wrapLangfuseRemoteClient(newFakeRemoteClient(SandboxTypeCube)))
require.False(t, ok, "wrapping must not invent keep-alive support")
_, ok = keepAliverFrom(nil)
require.False(t, ok)
}
const keepAliveTestTTL = 12 * time.Minute
func newKeepAliveTestManager(t *testing.T, client RemoteSandboxClient) *SessionBoundManager {
t.Helper()
cfg := DefaultConfig()
cfg.CubeTemplate = "tpl-test"
cfg.CubeSandboxTTL = keepAliveTestTTL
mgr, err := NewSessionBoundManager(SessionBoundManagerConfig{
Config: cfg,
Client: client,
Store: NewMemorySessionSandboxBindingStore(),
Checker: &fakeSessionExistenceChecker{exists: true},
SkipHealthProbe: true,
})
require.NoError(t, err)
return mgr
}
func keepAliveTestCtx() context.Context {
return context.WithValue(context.Background(), types.TenantIDContextKey, uint64(7))
}
func bindKeepAliveTestSession(t *testing.T, mgr *SessionBoundManager, sessionID string) string {
t.Helper()
ctx := keepAliveTestCtx()
_, err := mgr.Execute(ctx, &ExecuteConfig{
SessionID: sessionID, SkipValidation: true, ScriptContent: "print('ok')\n", Script: "hello.py",
})
require.NoError(t, err)
id, ok := mgr.BoundSandboxID(ctx, sessionID)
require.True(t, ok)
return id
}
func TestKeepAliveSessionRefreshesTheBoundSandbox(t *testing.T) {
client := &keepAliveFakeClient{fakeRemoteClient: newFakeRemoteClient(SandboxTypeCube)}
mgr := newKeepAliveTestManager(t, client)
sandboxID := bindKeepAliveTestSession(t, mgr, "s1")
next, err := mgr.KeepAliveSession(keepAliveTestCtx(), "s1")
require.NoError(t, err)
require.Equal(t, keepAliveTestTTL/3, next)
require.Equal(t, []keepAliveCall{{sandboxID: sandboxID, ttl: keepAliveTestTTL}}, client.calls())
}
func TestKeepAliveSessionNeverProvisions(t *testing.T) {
client := &keepAliveFakeClient{fakeRemoteClient: newFakeRemoteClient(SandboxTypeCube)}
mgr := newKeepAliveTestManager(t, client)
next, err := mgr.KeepAliveSession(keepAliveTestCtx(), "unbound")
require.NoError(t, err)
require.Zero(t, next)
require.Empty(t, client.calls())
creates, _, _, _, _ := client.counts()
require.Zero(t, creates, "keep-alive must never create a sandbox")
}
func TestKeepAliveSessionWithoutProviderSupportIsNoOp(t *testing.T) {
client := newFakeRemoteClient(SandboxTypeCube)
mgr := newKeepAliveTestManager(t, client)
bindKeepAliveTestSession(t, mgr, "s1")
_, connectsBefore, _, _, _ := client.counts()
next, err := mgr.KeepAliveSession(keepAliveTestCtx(), "s1")
require.NoError(t, err)
require.Zero(t, next)
_, connectsAfter, _, _, _ := client.counts()
require.Equal(t, connectsBefore, connectsAfter, "nothing to refresh, so nothing to connect to")
}
func TestKeepAliveSessionExpectedRefreshesOnlyTheMatchingSandbox(t *testing.T) {
client := &keepAliveFakeClient{fakeRemoteClient: newFakeRemoteClient(SandboxTypeCube)}
mgr := newKeepAliveTestManager(t, client)
sandboxID := bindKeepAliveTestSession(t, mgr, "s1")
next, err := mgr.KeepAliveSessionExpected(keepAliveTestCtx(), "s1", sandboxID)
require.NoError(t, err)
require.Equal(t, keepAliveTestTTL/3, next)
require.Equal(t, []keepAliveCall{{sandboxID: sandboxID, ttl: keepAliveTestTTL}}, client.calls())
}
func TestKeepAliveSessionExpectedDoesNotRefreshADifferentSandbox(t *testing.T) {
client := &keepAliveFakeClient{fakeRemoteClient: newFakeRemoteClient(SandboxTypeCube)}
mgr := newKeepAliveTestManager(t, client)
bindKeepAliveTestSession(t, mgr, "s1")
next, err := mgr.KeepAliveSessionExpected(keepAliveTestCtx(), "s1", "sbx-other")
require.NoError(t, err)
require.Zero(t, next)
require.Empty(t, client.calls(), "a different sandbox is not refreshed and not replaced")
}
func TestKeepAliveSessionRefreshesSharedUserMachine(t *testing.T) {
for _, expected := range []bool{false, true} {
t.Run(map[bool]string{false: "session", true: "expected"}[expected], func(t *testing.T) {
h := newUserManagerHarness(t, userAssignmentFor(userSessionA))
ctx := ownerCtx()
_, err := h.mgr.ExecShellCommand(ctx, userSessionA, "true", "", time.Second, nil)
require.NoError(t, err)
id, found := h.mgr.BoundSandboxID(ctx, userSessionA)
require.True(t, found)
keeper := &keepAliveFakeClient{fakeRemoteClient: h.client}
h.mgr.client = wrapLangfuseRemoteClient(keeper)
creates, _, _, _, _ := keeper.counts()
var next time.Duration
if expected {
next, err = h.mgr.KeepAliveSessionExpected(ctx, userSessionA, id)
} else {
next, err = h.mgr.KeepAliveSession(ctx, userSessionA)
}
require.NoError(t, err)
require.Positive(t, next)
require.Equal(t, []keepAliveCall{{sandboxID: id, ttl: next * keepAliveRefreshDivisor}}, keeper.calls())
after, _, _, _, _ := keeper.counts()
require.Equal(t, creates, after, "keeping a shared machine alive must not create a session sandbox")
next, err = h.mgr.KeepAliveSessionExpected(ctx, userSessionA, "another-machine")
require.NoError(t, err)
require.Zero(t, next)
require.Len(t, keeper.calls(), 1, "a mismatched shared binding must not be refreshed")
})
}
}
func TestKeepAliveSessionReportsProviderFailure(t *testing.T) {
client := &keepAliveFakeClient{fakeRemoteClient: newFakeRemoteClient(SandboxTypeCube)}
client.keepErr = errors.New("provider down")
mgr := newKeepAliveTestManager(t, client)
bindKeepAliveTestSession(t, mgr, "s1")
next, err := mgr.KeepAliveSession(keepAliveTestCtx(), "s1")
require.ErrorContains(t, err, "provider down")
require.Zero(t, next)
}
+390
View File
@@ -0,0 +1,390 @@
package sandbox
import (
"context"
"unicode/utf8"
"academy/internal/tracing/langfuse"
"github.com/gorilla/websocket"
)
const sandboxSpanPreviewRunes = 256
// wrapLangfuseRemoteClient records provider-neutral sandbox RPCs as Langfuse
// spans (sandbox.exec / sandbox.connect / …) so LiteFuse shows a product-level
// tree instead of a pile of Docker Engine HTTP calls parented to whatever
// agent.round happened to be recording. No-op when Langfuse is disabled or
// the caller has no parent trace.
//
// Snapshot capability is forwarded: wrapping must not hide RemoteSnapshotManager
// from SnapshotManagerFrom, and CreateForkSnapshot must still reach Docker's
// fork namespace.
func wrapLangfuseRemoteClient(inner RemoteSandboxClient) RemoteSandboxClient {
if inner == nil {
return nil
}
if _, ok := inner.(*langfuseRemoteClient); ok {
return inner
}
if _, ok := inner.(*langfuseSnapshotClient); ok {
return inner
}
wrapped := langfuseRemoteClient{inner: inner}
if _, ok := inner.(RemoteSnapshotManager); ok {
return &langfuseSnapshotClient{langfuseRemoteClient: wrapped}
}
return &wrapped
}
type langfuseRemoteClient struct {
inner RemoteSandboxClient
}
func (c *langfuseRemoteClient) Provider() RemoteProvider { return c.inner.Provider() }
func (c *langfuseRemoteClient) Capabilities() RemoteSandboxCapabilities {
return c.inner.Capabilities()
}
func (c *langfuseRemoteClient) Health(ctx context.Context) error {
return c.inner.Health(ctx)
}
func (c *langfuseRemoteClient) Create(
ctx context.Context, req RemoteCreateRequest,
) (RemoteSandboxHandle, error) {
ctx, span := startSandboxSpan(ctx, "sandbox.create", map[string]interface{}{
"template_id": req.TemplateID,
}, nil)
handle, err := c.inner.Create(ctx, req)
span.Finish(sandboxHandleOut(handle), nil, err)
return handle, err
}
func (c *langfuseRemoteClient) Connect(
ctx context.Context, req RemoteConnectRequest,
) (RemoteSandboxHandle, error) {
ctx, span := startSandboxSpan(ctx, "sandbox.connect", map[string]interface{}{
"sandbox_id": req.SandboxID,
}, nil)
handle, err := c.inner.Connect(ctx, req)
span.Finish(sandboxHandleOut(handle), nil, err)
return handle, err
}
func (c *langfuseRemoteClient) ConnectSession(
ctx context.Context, req RemoteConnectRequest,
) (RemoteSandboxHandle, error) {
ctx, span := startSandboxSpan(ctx, "sandbox.connect", map[string]interface{}{
"sandbox_id": req.SandboxID,
"check_state": true,
}, nil)
handle, err := connectRemoteSession(ctx, c.inner, req)
span.Finish(sandboxHandleOut(handle), nil, err)
return handle, err
}
func (c *langfuseRemoteClient) Get(
ctx context.Context, sandboxID string,
) (*RemoteSandboxSummary, error) {
return c.inner.Get(ctx, sandboxID)
}
func (c *langfuseRemoteClient) List(
ctx context.Context, filter RemoteListFilter,
) ([]RemoteSandboxSummary, error) {
return c.inner.List(ctx, filter)
}
func (c *langfuseRemoteClient) Delete(ctx context.Context, sandboxID string) error {
ctx, span := startSandboxSpan(ctx, "sandbox.delete", map[string]interface{}{
"sandbox_id": sandboxID,
}, nil)
err := c.inner.Delete(ctx, sandboxID)
span.Finish(nil, nil, err)
return err
}
func (c *langfuseRemoteClient) Exec(
ctx context.Context,
handle RemoteSandboxHandle,
req RemoteExecRequest,
) (*RemoteExecResult, error) {
ctx, span := startSandboxSpan(ctx, "sandbox.exec", map[string]interface{}{
"command": truncateSandboxPreview(req.Command),
"shell": req.Shell,
"work_dir": req.WorkDir,
"user": req.User,
"timeout_ms": req.Timeout.Milliseconds(),
}, sandboxHandleMeta(handle))
result, err := c.inner.Exec(ctx, handle, req)
out := map[string]interface{}{}
if result != nil {
out["exit_code"] = result.ExitCode
out["killed"] = result.Killed
out["duration_ms"] = result.Duration.Milliseconds()
out["stdout_bytes"] = len(result.Stdout)
out["stderr_bytes"] = len(result.Stderr)
}
span.Finish(out, nil, err)
return result, err
}
func (c *langfuseRemoteClient) WriteFile(
ctx context.Context, handle RemoteSandboxHandle, path string, content []byte,
) error {
ctx, span := startSandboxSpan(ctx, "sandbox.write_file", map[string]interface{}{
"path": path,
"bytes": len(content),
}, sandboxHandleMeta(handle))
err := c.inner.WriteFile(ctx, handle, path, content)
span.Finish(nil, nil, err)
return err
}
func (c *langfuseRemoteClient) ReadFile(
ctx context.Context, handle RemoteSandboxHandle, path string,
) ([]byte, error) {
ctx, span := startSandboxSpan(ctx, "sandbox.read_file", map[string]interface{}{
"path": path,
}, sandboxHandleMeta(handle))
data, err := c.inner.ReadFile(ctx, handle, path)
span.Finish(map[string]interface{}{"bytes": len(data)}, nil, err)
return data, err
}
func (c *langfuseRemoteClient) ListDir(
ctx context.Context, handle RemoteSandboxHandle, path string,
) ([]RemoteDirEntry, error) {
ctx, span := startSandboxSpan(ctx, "sandbox.list_dir", map[string]interface{}{
"path": path,
}, sandboxHandleMeta(handle))
entries, err := c.inner.ListDir(ctx, handle, path)
span.Finish(map[string]interface{}{"entries": len(entries)}, nil, err)
return entries, err
}
func (c *langfuseRemoteClient) MakeDir(
ctx context.Context, handle RemoteSandboxHandle, path string,
) error {
ctx, span := startSandboxSpan(ctx, "sandbox.make_dir", map[string]interface{}{
"path": path,
}, sandboxHandleMeta(handle))
err := c.inner.MakeDir(ctx, handle, path)
span.Finish(nil, nil, err)
return err
}
func (c *langfuseRemoteClient) Remove(
ctx context.Context, handle RemoteSandboxHandle, path string,
) error {
ctx, span := startSandboxSpan(ctx, "sandbox.remove", map[string]interface{}{
"path": path,
}, sandboxHandleMeta(handle))
err := c.inner.Remove(ctx, handle, path)
span.Finish(nil, nil, err)
return err
}
func (c *langfuseRemoteClient) Stat(
ctx context.Context, handle RemoteSandboxHandle, path string,
) (*RemoteStatEntry, error) {
ctx, span := startSandboxSpan(ctx, "sandbox.stat", map[string]interface{}{
"path": path,
}, sandboxHandleMeta(handle))
stat, err := c.inner.Stat(ctx, handle, path)
span.Finish(nil, nil, err)
return stat, err
}
type langfuseSnapshotClient struct {
langfuseRemoteClient
}
func (c *langfuseSnapshotClient) CreateSnapshot(
ctx context.Context, sandboxID string, name string,
) (RemoteSnapshotRef, error) {
inner, ok := c.inner.(RemoteSnapshotManager)
if !ok {
return RemoteSnapshotRef{}, &RemoteError{
Kind: RemoteErrorKindUnsupported,
Op: "CreateSnapshot",
Message: "inner client has no snapshot manager",
}
}
ctx, span := startSandboxSpan(ctx, "sandbox.create_snapshot", map[string]interface{}{
"sandbox_id": sandboxID,
"name": name,
}, nil)
ref, err := inner.CreateSnapshot(ctx, sandboxID, name)
span.Finish(map[string]interface{}{"snapshot_id": ref.ID}, nil, err)
return ref, err
}
func (c *langfuseSnapshotClient) CreateForkSnapshot(
ctx context.Context, sandboxID string, name string,
) (RemoteSnapshotRef, error) {
if creator, ok := c.inner.(forkSnapshotCreator); ok {
ctx, span := startSandboxSpan(ctx, "sandbox.create_fork_snapshot", map[string]interface{}{
"sandbox_id": sandboxID,
"name": name,
}, nil)
ref, err := creator.CreateForkSnapshot(ctx, sandboxID, name)
span.Finish(map[string]interface{}{"snapshot_id": ref.ID}, nil, err)
return ref, err
}
inner, ok := c.inner.(RemoteSnapshotManager)
if !ok {
return RemoteSnapshotRef{}, &RemoteError{
Kind: RemoteErrorKindUnsupported,
Op: "CreateForkSnapshot",
Message: "inner client has no snapshot manager",
}
}
return inner.CreateSnapshot(ctx, sandboxID, name)
}
func (c *langfuseSnapshotClient) DeleteSnapshot(ctx context.Context, snapshotID string) error {
inner, ok := c.inner.(RemoteSnapshotManager)
if !ok {
return nil
}
ctx, span := startSandboxSpan(ctx, "sandbox.delete_snapshot", map[string]interface{}{
"snapshot_id": snapshotID,
}, nil)
err := inner.DeleteSnapshot(ctx, snapshotID)
out, spanErr := snapshotDeleteSpanResult(err)
span.Finish(out, nil, spanErr)
return err
}
// snapshotDeleteSpanResult keeps an in-use Conflict off the ERROR status.
// Session sandboxes pause against the template they booted from, so the skill
// reaper hitting this every few minutes is expected retry, not a fault.
func snapshotDeleteSpanResult(err error) (map[string]interface{}, error) {
if !IsRemoteConflict(err) {
return nil, err
}
return map[string]interface{}{
"deferred": true,
"reason": "in_use",
}, nil
}
func (c *langfuseSnapshotClient) ListSnapshots(
ctx context.Context, sandboxID string,
) ([]RemoteSnapshotRef, error) {
inner, ok := c.inner.(RemoteSnapshotManager)
if !ok {
return nil, nil
}
return inner.ListSnapshots(ctx, sandboxID)
}
func startSandboxSpan(
ctx context.Context,
name string,
input, extraMeta map[string]interface{},
) (context.Context, *langfuse.Span) {
return langfuse.GetManager().StartChildSpan(ctx, langfuse.SpanOptions{
Name: name,
Input: input,
Metadata: extraMeta,
})
}
func sandboxHandleMeta(handle RemoteSandboxHandle) map[string]interface{} {
if handle == nil {
return nil
}
return map[string]interface{}{
"sandbox_id": handle.ID(),
"provider": string(handle.Provider()),
}
}
func sandboxHandleOut(handle RemoteSandboxHandle) map[string]interface{} {
if handle == nil {
return nil
}
return map[string]interface{}{"sandbox_id": handle.ID()}
}
func truncateSandboxPreview(s string) string {
if s == "" || utf8.RuneCountInString(s) <= sandboxSpanPreviewRunes {
return s
}
runes := []rune(s)
return string(runes[:sandboxSpanPreviewRunes]) + "…"
}
// OpenTerminal forwards the interactive-terminal capability so wrapping does
// not hide RemoteTerminalManager from TerminalManagerFrom.
//
// It lives on the base decorator (not on a dedicated one like
// langfuseSnapshotClient) so *every* wrapping shape exposes the capability:
// langfuseSnapshotClient embeds this type, so it inherits the method.
// Whether a backend actually supports terminals stays delegated to the inner
// client's SupportsTerminals flag, which the *From helpers check.
func (c *langfuseRemoteClient) OpenTerminal(
ctx context.Context,
handle RemoteSandboxHandle,
opts RemoteTerminalOptions,
) (RemoteTerminalSession, error) {
inner, ok := c.inner.(RemoteTerminalManager)
if !ok {
return nil, &RemoteError{
Kind: RemoteErrorKindUnsupported,
Op: "OpenTerminal",
Message: "inner client has no terminal manager",
}
}
ctx, span := startSandboxSpan(ctx, "sandbox.open_terminal", sandboxHandleOut(handle), nil)
session, err := inner.OpenTerminal(ctx, handle, opts)
span.Finish(sandboxHandleOut(handle), nil, err)
return session, err
}
// DialDesktop forwards the desktop capability so wrapping does not hide
// RemoteDesktopManager from DesktopManagerFrom.
//
// It lives on the base decorator (not on a dedicated one like
// langfuseSnapshotClient) so *every* wrapping shape exposes the capability:
// langfuseSnapshotClient embeds this type, so it inherits the method.
// Whether a backend actually supports desktops stays delegated to the inner
// client's SupportsDesktop flag, which the *From helpers check.
func (c *langfuseRemoteClient) DialDesktop(
ctx context.Context,
handle RemoteSandboxHandle,
opts RemoteDesktopOptions,
) (*websocket.Conn, error) {
inner, ok := c.inner.(RemoteDesktopManager)
if !ok {
return nil, &RemoteError{
Kind: RemoteErrorKindUnsupported,
Op: "DialDesktop",
Message: "inner client has no desktop manager",
}
}
ctx, span := startSandboxSpan(ctx, "sandbox.dial_desktop", sandboxHandleOut(handle), nil)
conn, err := inner.DialDesktop(ctx, handle, opts)
span.Finish(sandboxHandleOut(handle), nil, err)
return conn, err
}
func (c *langfuseRemoteClient) StartDesktopTTLRefresh(ctx context.Context, handle RemoteSandboxHandle) {
inner, ok := c.inner.(RemoteDesktopTTLRefresher)
if !ok {
return
}
inner.StartDesktopTTLRefresh(ctx, handle)
}
var (
_ RemoteSandboxClient = (*langfuseRemoteClient)(nil)
_ RemoteSnapshotManager = (*langfuseSnapshotClient)(nil)
_ forkSnapshotCreator = (*langfuseSnapshotClient)(nil)
_ RemoteTerminalManager = (*langfuseRemoteClient)(nil)
_ RemoteDesktopManager = (*langfuseRemoteClient)(nil)
_ RemoteDesktopTTLRefresher = (*langfuseRemoteClient)(nil)
)
+163
View File
@@ -0,0 +1,163 @@
package sandbox
import (
"context"
"strings"
"testing"
"unicode/utf8"
"github.com/stretchr/testify/require"
)
func TestWrapLangfuseRemoteClientPreservesSnapshotCapability(t *testing.T) {
inner := newFakeRemoteClient(SandboxTypeCube)
inner.capabilities.SupportsSnapshots = true
wrapped := wrapLangfuseRemoteClient(inner)
mgr, ok := SnapshotManagerFrom(wrapped)
require.True(t, ok, "wrapping must not hide RemoteSnapshotManager from SnapshotManagerFrom")
require.NotNil(t, mgr)
ref, err := mgr.CreateSnapshot(context.Background(), "sb-1", "snap-1")
require.NoError(t, err)
require.NotEmpty(t, ref.ID)
}
func TestWrapLangfuseRemoteClientPreservesForkSnapshotCapability(t *testing.T) {
inner := newFakeRemoteClient(SandboxTypeCube)
inner.capabilities.SupportsSnapshots = true
client := &recordingForkSnapshotClient{fakeRemoteClient: inner}
wrapped := wrapLangfuseRemoteClient(client)
creator, ok := wrapped.(forkSnapshotCreator)
require.True(t, ok, "wrapping must not hide CreateForkSnapshot")
ref, err := creator.CreateForkSnapshot(context.Background(), "sb-1", "fork-1")
require.NoError(t, err)
require.Equal(t, "fork-sb-1", ref.ID)
require.Equal(t, 1, client.forkCalls)
}
func TestWrapLangfuseRemoteClientDoesNotInventSnapshotSupport(t *testing.T) {
inner := &noSnapshotClient{}
wrapped := wrapLangfuseRemoteClient(inner)
mgr, ok := SnapshotManagerFrom(wrapped)
require.False(t, ok)
require.Nil(t, mgr)
}
func TestWrapLangfuseRemoteClientIdempotent(t *testing.T) {
inner := newFakeRemoteClient(SandboxTypeDocker)
once := wrapLangfuseRemoteClient(inner)
twice := wrapLangfuseRemoteClient(once)
require.Equal(t, once, twice)
}
func TestWrapLangfuseRemoteClientExecForwards(t *testing.T) {
inner := newFakeRemoteClient(SandboxTypeDocker)
handle, err := inner.Create(context.Background(), RemoteCreateRequest{TemplateID: "tpl"})
require.NoError(t, err)
wrapped := wrapLangfuseRemoteClient(inner)
result, err := wrapped.Exec(context.Background(), handle, RemoteExecRequest{
Command: "echo hi",
Shell: true,
})
require.NoError(t, err)
require.NotNil(t, result)
require.Len(t, inner.execRequests, 1)
require.Equal(t, "echo hi", inner.execRequests[0].Command)
}
func TestWrapLangfuseRemoteClientPreservesTerminalCapability(t *testing.T) {
inner := &terminalFakeClient{fakeRemoteClient: newFakeRemoteClient(SandboxTypeCube)}
inner.capabilities.SupportsTerminals = true
wrapped := wrapLangfuseRemoteClient(inner)
mgr, ok := TerminalManagerFrom(wrapped)
require.True(t, ok, "wrapping must not hide RemoteTerminalManager from TerminalManagerFrom")
require.NotNil(t, mgr)
session, err := mgr.OpenTerminal(context.Background(), nil, RemoteTerminalOptions{Cols: 80, Rows: 24})
require.NoError(t, err)
require.NotNil(t, session)
}
func TestWrapLangfuseRemoteClientPreservesDesktopCapability(t *testing.T) {
inner := &desktopFakeClient{fakeRemoteClient: newFakeRemoteClient(SandboxTypeCube)}
inner.capabilities.SupportsDesktop = true
wrapped := wrapLangfuseRemoteClient(inner)
mgr, ok := DesktopManagerFrom(wrapped)
require.True(t, ok, "wrapping must not hide RemoteDesktopManager from DesktopManagerFrom")
require.NotNil(t, mgr)
_, err := mgr.DialDesktop(context.Background(), nil, RemoteDesktopOptions{})
require.NoError(t, err)
require.True(t, inner.dialed, "the decorator must delegate, not short-circuit")
}
func TestWrapLangfuseRemoteClientPreservesDesktopTTLRefresh(t *testing.T) {
inner := &desktopFakeClient{fakeRemoteClient: newFakeRemoteClient(SandboxTypeCube)}
inner.capabilities.SupportsTimeoutRefresh = true
wrapped := wrapLangfuseRemoteClient(inner)
refresher, ok := DesktopTTLRefresherFrom(wrapped)
require.True(t, ok, "wrapping must not hide RemoteDesktopTTLRefresher")
refresher.StartDesktopTTLRefresh(context.Background(), nil)
require.Equal(t, 1, inner.ttlStarted)
}
func TestWrapLangfuseRemoteClientDoesNotInventTerminalSupport(t *testing.T) {
// The fake advertises no terminal support; wrapping must not fake it.
inner := newFakeRemoteClient(SandboxTypeDocker)
wrapped := wrapLangfuseRemoteClient(inner)
mgr, ok := TerminalManagerFrom(wrapped)
require.False(t, ok)
require.Nil(t, mgr)
}
// terminalFakeClient adds the optional terminal capability to the shared fake
// so wrapper tests can assert capability forwarding.
type terminalFakeClient struct {
*fakeRemoteClient
}
func (c *terminalFakeClient) OpenTerminal(
_ context.Context, _ RemoteSandboxHandle, _ RemoteTerminalOptions,
) (RemoteTerminalSession, error) {
return &terminalFakeSession{}, nil
}
type terminalFakeSession struct{}
func (s *terminalFakeSession) Output() <-chan RemoteTerminalEvent { return nil }
func (s *terminalFakeSession) PID() uint32 { return 1 }
func (s *terminalFakeSession) Write(context.Context, []byte) error { return nil }
func (s *terminalFakeSession) Resize(context.Context, uint32, uint32) error {
return nil
}
func (s *terminalFakeSession) Close() error { return nil }
func TestTruncateSandboxPreview(t *testing.T) {
require.Equal(t, "short", truncateSandboxPreview("short"))
long := strings.Repeat("x", sandboxSpanPreviewRunes+8)
got := truncateSandboxPreview(long)
require.True(t, strings.HasSuffix(got, "…"))
require.Equal(t, sandboxSpanPreviewRunes+1, utf8.RuneCountInString(got))
}
func TestSnapshotDeleteSpanResultDefersConflict(t *testing.T) {
out, spanErr := snapshotDeleteSpanResult(NewRemoteError(
SandboxTypeE2B, "DeleteSnapshot", RemoteErrorKindConflict,
"paused sandboxes using it", nil,
))
require.NoError(t, spanErr, "in-use must not mark the Langfuse span ERROR")
require.Equal(t, true, out["deferred"])
require.Equal(t, "in_use", out["reason"])
boom := NewRemoteError(SandboxTypeE2B, "DeleteSnapshot", RemoteErrorKindInternal, "boom", nil)
out, spanErr = snapshotDeleteSpanResult(boom)
require.Equal(t, boom, spanErr)
require.Nil(t, out)
}
+283
View File
@@ -0,0 +1,283 @@
package sandbox
import (
"context"
"fmt"
"log"
"os"
"sync"
)
// DefaultManager implements the Manager interface
// It handles sandbox selection and fallback logic
type DefaultManager struct {
config *Config
sandbox Sandbox
validator *ScriptValidator
mu sync.RWMutex
}
// NewManager creates a new sandbox manager with the given configuration
func NewManager(config *Config) (Manager, error) {
if config == nil {
config = DefaultConfig()
}
if err := ValidateConfig(config); err != nil {
return nil, fmt.Errorf("invalid sandbox config: %w", err)
}
manager := &DefaultManager{
config: config,
validator: NewScriptValidator(),
}
// Initialize the appropriate sandbox
if err := manager.initializeSandbox(context.Background()); err != nil {
return nil, err
}
return manager, nil
}
// initializeSandbox creates and configures the sandbox based on configuration
func (m *DefaultManager) initializeSandbox(ctx context.Context) error {
switch m.config.Type {
case SandboxTypeDisabled:
m.sandbox = &disabledSandbox{}
return nil
case SandboxTypeCube, SandboxTypeE2B, SandboxTypeDocker:
// Session-scoped remote backends are only reachable through
// SessionBoundManager, which owns the authoritative binding.
// DefaultManager exposes stateless semantics that cannot preserve
// per-session state, so we refuse the construction and let
// NewManagerFromType route the caller to NewSessionBoundManager.
return fmt.Errorf(
"sandbox: %s backend must be constructed via NewSessionBoundManager",
m.config.Type,
)
default:
return fmt.Errorf("unknown sandbox type: %s", m.config.Type)
}
}
// Execute runs a script using the configured sandbox
// It performs security validation before execution to prevent prompt injection attacks
func (m *DefaultManager) Execute(ctx context.Context, config *ExecuteConfig) (*ExecuteResult, error) {
m.mu.RLock()
sandbox := m.sandbox
m.mu.RUnlock()
if sandbox == nil {
return nil, ErrSandboxDisabled
}
// Check if sandbox is disabled - return early without validation
if sandbox.Type() == SandboxTypeDisabled {
return nil, ErrSandboxDisabled
}
effective := config
if config != nil && len(m.config.EnvVars) > 0 {
copy := *config
copy.Env = cloneMetadata(m.config.EnvVars)
for key, value := range config.Env {
copy.Env[key] = value
}
effective = &copy
}
// Perform security validation unless explicitly skipped
if effective != nil && !effective.SkipValidation {
if err := runScriptValidation(m.validator, effective); err != nil {
log.Printf("[sandbox] Security validation failed: %v", err)
return &ExecuteResult{
ExitCode: -1,
Error: err.Error(),
Stderr: fmt.Sprintf("Security validation failed: %v", err),
}, ErrSecurityViolation
}
}
return sandbox.Execute(ctx, effective)
}
// runScriptValidation is the package-level helper that DefaultManager and
// SessionBoundManager share for pre-execution security checks. Extracting
// it avoids duplicating the same script/args/stdin validation logic across
// two Manager implementations while keeping the ScriptValidator private to
// the manager that owns it.
func runScriptValidation(validator *ScriptValidator, config *ExecuteConfig) error {
if validator == nil || config == nil {
return nil
}
// Get script content for validation
scriptContent := config.ScriptContent
if scriptContent == "" && config.Script != "" {
content, err := os.ReadFile(config.Script)
if err != nil {
return fmt.Errorf("failed to read script for validation: %w", err)
}
scriptContent = string(content)
}
// Validate script content
if scriptContent != "" {
result := validator.ValidateScript(scriptContent)
if !result.Valid {
for _, verr := range result.Errors {
log.Printf("[sandbox] Validation error: %s", verr.Error())
}
if len(result.Errors) > 0 {
return result.Errors[0]
}
return ErrSecurityViolation
}
}
// Validate arguments
if len(config.Args) > 0 {
result := validator.ValidateArgs(config.Args)
if !result.Valid {
for _, verr := range result.Errors {
log.Printf("[sandbox] Arg validation error: %s", verr.Error())
}
if len(result.Errors) > 0 {
return result.Errors[0]
}
return ErrArgInjection
}
}
// Validate stdin
if config.Stdin != "" {
result := validator.ValidateStdin(config.Stdin)
if !result.Valid {
for _, verr := range result.Errors {
log.Printf("[sandbox] Stdin validation error: %s", verr.Error())
}
if len(result.Errors) > 0 {
return result.Errors[0]
}
return ErrStdinInjection
}
}
return nil
}
// Cleanup releases all sandbox resources
func (m *DefaultManager) Cleanup(ctx context.Context) error {
m.mu.RLock()
sandbox := m.sandbox
m.mu.RUnlock()
if sandbox != nil {
return sandbox.Cleanup(ctx)
}
return nil
}
// GetSandbox returns the active sandbox
func (m *DefaultManager) GetSandbox() Sandbox {
m.mu.RLock()
defer m.mu.RUnlock()
return m.sandbox
}
// GetType returns the current sandbox type
func (m *DefaultManager) GetType() SandboxType {
m.mu.RLock()
defer m.mu.RUnlock()
if m.sandbox != nil {
return m.sandbox.Type()
}
return SandboxTypeDisabled
}
// disabledSandbox is a no-op sandbox that rejects all execution requests
type disabledSandbox struct{}
func (s *disabledSandbox) Execute(ctx context.Context, config *ExecuteConfig) (*ExecuteResult, error) {
return nil, ErrSandboxDisabled
}
func (s *disabledSandbox) Cleanup(ctx context.Context) error {
return nil
}
func (s *disabledSandbox) Type() SandboxType {
return SandboxTypeDisabled
}
func (s *disabledSandbox) IsAvailable(ctx context.Context) bool {
return false
}
// NewManagerFromType creates a sandbox manager with the specified type.
// dockerImage is optional; if empty, the default image is used.
//
// Session-scoped backends (Cube, E2B, Docker) route to SessionBoundManager,
// which keeps one persistent sandbox per SessionID; Disabled routes to
// DefaultManager. Both satisfy Manager.
func NewManagerFromType(sandboxType string, dockerImage string) (Manager, error) {
var sType SandboxType
switch sandboxType {
case "docker":
sType = SandboxTypeDocker
case "cube":
sType = SandboxTypeCube
case "e2b":
sType = SandboxTypeE2B
case "disabled", "":
sType = SandboxTypeDisabled
default:
return nil, fmt.Errorf("unknown sandbox type: %s", sandboxType)
}
config := DefaultConfig()
config.Type = sType
if dockerImage != "" {
config.DockerImage = dockerImage
}
var client RemoteSandboxClient
var err error
switch sType {
case SandboxTypeCube:
if client, err = NewCubeRemoteClient(config); err != nil {
return nil, fmt.Errorf("sandbox: build Cube client: %w", err)
}
case SandboxTypeE2B:
if client, err = NewE2BRemoteClient(config); err != nil {
return nil, fmt.Errorf("sandbox: build E2B client: %w", err)
}
case SandboxTypeDocker:
applyDockerRuntimeDefaults(config)
if client, err = NewDockerRemoteClient(config); err != nil {
return nil, fmt.Errorf("sandbox: build Docker client: %w", err)
}
}
if client == nil {
return NewManager(config)
}
return NewSessionBoundManager(SessionBoundManagerConfig{
Config: config,
Client: client,
Store: NewMemorySessionSandboxBindingStore(),
Checker: PermissiveSessionExistenceChecker{},
})
}
// NewDisabledManager creates a manager that rejects all execution requests
func NewDisabledManager() Manager {
return &DefaultManager{
config: DefaultConfig(),
sandbox: &disabledSandbox{},
validator: NewScriptValidator(),
}
}
+38
View File
@@ -0,0 +1,38 @@
package sandbox
import (
"path"
"strings"
)
// makeDirTree creates dir and every missing parent by calling mkdir once per
// path component. envd's MakeDir is not mkdir -p; Cube and E2B adapters wrap it
// with this instead of a single RPC so host-skill staging under
// /workspace/.skills/<name>/<revision>/... can create its tree.
func makeDirTree(dir string, mkdir func(path string) error) error {
dir = path.Clean(strings.TrimSpace(dir))
if dir == "" || dir == "." || dir == "/" {
return nil
}
var current string
if path.IsAbs(dir) {
current = "/"
dir = strings.TrimPrefix(dir, "/")
}
for _, part := range strings.Split(dir, "/") {
if part == "" || part == "." {
continue
}
if current == "/" {
current = "/" + part
} else if current == "" {
current = part
} else {
current += "/" + part
}
if err := ignoreExistingDir(mkdir(current)); err != nil {
return err
}
}
return nil
}
+46
View File
@@ -0,0 +1,46 @@
package sandbox
import (
"errors"
"path"
"testing"
"github.com/stretchr/testify/require"
)
func TestMakeDirTreeCreatesEachParentAndTreatsExistsAsSuccess(t *testing.T) {
var created []string
existing := map[string]bool{"/workspace": true}
err := makeDirTree("/workspace/.skills/host-probe/abc123/scripts", func(dir string) error {
if existing[dir] {
return NewRemoteError(SandboxTypeCube, "MakeDir", RemoteErrorKindInternal,
"failed to make dir "+dir+": directory already exists: "+dir, nil)
}
if dir != "/workspace" && !existing[path.Dir(dir)] {
return errors.New("parent missing: " + dir)
}
existing[dir] = true
created = append(created, dir)
return nil
})
require.NoError(t, err)
require.Equal(t, []string{
"/workspace/.skills",
"/workspace/.skills/host-probe",
"/workspace/.skills/host-probe/abc123",
"/workspace/.skills/host-probe/abc123/scripts",
}, created)
}
func TestMakeDirTreeStopsWhenALevelFails(t *testing.T) {
var created []string
err := makeDirTree("/workspace/.skills/name", func(dir string) error {
created = append(created, dir)
if dir == "/workspace/.skills" {
return errors.New("permission denied")
}
return nil
})
require.EqualError(t, err, "permission denied")
require.Equal(t, []string{"/workspace", "/workspace/.skills"}, created)
}
+90
View File
@@ -0,0 +1,90 @@
// Package sandbox: orphan sandbox reconciliation.
//
// Session sandboxes are created with onTimeout=pause + autoResume (see
// buildSessionCreateRequest), so the provider TTL PAUSES them rather than
// destroying them. When a binding is replaced — the CAS that happens when a
// workspace switches provider — or lost (Redis TTL, process restart), the old
// sandbox ID disappears from our records while the sandbox itself lingers in a
// paused state, consuming snapshot storage and money.
//
// Neither existing cleanup path covers that: session deletion works from a
// live binding, and the lifecycle's orphan cleanup is lazy, triggering only
// when someone touches the binding that has already been overwritten.
//
// This reconciliation loop closes the gap by enumerating the provider's
// sandboxes via the tenant metadata every sandbox is tagged with, comparing
// against the authoritative bindings, and deleting what is unbound. Paused
// sandboxes MUST be included: they are precisely the leaked ones.
package sandbox
import (
"context"
"fmt"
"time"
)
// orphanReaperClient is the narrow slice of RemoteSandboxClient the reaper
// needs, declared separately so tests can supply a small fake.
type orphanReaperClient interface {
List(ctx context.Context, filter RemoteListFilter) ([]RemoteSandboxSummary, error)
Delete(ctx context.Context, sandboxID string) error
}
// OrphanReaperDeps configures one reconciliation pass for a single tenant.
type OrphanReaperDeps struct {
Client orphanReaperClient
// BoundIDs is the set of sandbox IDs the binding store still considers
// owned. Anything outside this set is a deletion candidate.
BoundIDs map[string]struct{}
TenantID uint64
// ConfigID scopes the sweep to one sandbox config. Empty means the
// deployment default config. Sweeping by tenant alone would delete
// sandboxes belonging to a sibling config on the same provider account.
ConfigID string
// Grace protects freshly created sandboxes that may not be bound yet.
// Pass 0 when reaping deliberately (e.g. before a backend switch), where
// every sandbox on the old backend is known to be abandoned.
Grace time.Duration
Now func() time.Time
}
// ReapOrphanSandboxes deletes unbound sandboxes for one tenant and reports how
// many were removed.
func ReapOrphanSandboxes(ctx context.Context, deps OrphanReaperDeps) (int, error) {
if deps.Client == nil {
return 0, fmt.Errorf("sandbox: orphan reaper requires a client")
}
now := deps.Now
if now == nil {
now = time.Now
}
summaries, err := deps.Client.List(ctx, configSandboxFilter(deps.TenantID, deps.ConfigID))
if err != nil {
return 0, fmt.Errorf(
"sandbox: list workspace %d config %q sandboxes: %w",
deps.TenantID, NormalizeConfigID(deps.ConfigID), err)
}
cutoff := now().Add(-deps.Grace)
deleted := 0
for _, summary := range summaries {
if _, bound := deps.BoundIDs[summary.ID]; bound {
continue
}
if deps.Grace > 0 && !summary.StartedAt.IsZero() && summary.StartedAt.After(cutoff) {
continue
}
if err := deps.Client.Delete(ctx, summary.ID); err != nil {
// Keep going: one undeletable sandbox must not abort the sweep.
continue
}
deleted++
}
return deleted, nil
}
+113
View File
@@ -0,0 +1,113 @@
package sandbox
import (
"context"
"testing"
"time"
"github.com/stretchr/testify/require"
)
type fakeReaperClient struct {
summaries []RemoteSandboxSummary
states []RemoteSandboxState
deleted []string
}
func (f *fakeReaperClient) List(
_ context.Context, filter RemoteListFilter,
) ([]RemoteSandboxSummary, error) {
f.states = filter.States
return f.summaries, nil
}
func (f *fakeReaperClient) Delete(_ context.Context, id string) error {
f.deleted = append(f.deleted, id)
return nil
}
// Paused sandboxes are the whole point: onTimeout=pause means the provider TTL
// never reclaims them, so a sweep that only looked at running ones would miss
// every leaked instance.
func TestReapOrphanSandboxesDeletesUnboundIncludingPaused(t *testing.T) {
now := time.Now()
client := &fakeReaperClient{summaries: []RemoteSandboxSummary{
{ID: "sbx-bound", State: RemoteStateRunning, StartedAt: now.Add(-2 * time.Hour)},
{ID: "sbx-orphan-running", State: RemoteStateRunning, StartedAt: now.Add(-2 * time.Hour)},
{ID: "sbx-orphan-paused", State: RemoteStatePaused, StartedAt: now.Add(-2 * time.Hour)},
// Inside the grace window: may still be mid-creation and unbound.
{ID: "sbx-fresh", State: RemoteStateRunning, StartedAt: now.Add(-1 * time.Minute)},
}}
deleted, err := ReapOrphanSandboxes(context.Background(), OrphanReaperDeps{
Client: client,
BoundIDs: map[string]struct{}{"sbx-bound": {}},
TenantID: 7,
Grace: 30 * time.Minute,
Now: func() time.Time { return now },
})
require.NoError(t, err)
require.Equal(t, 2, deleted)
require.ElementsMatch(t,
[]string{"sbx-orphan-running", "sbx-orphan-paused"}, client.deleted)
require.Contains(t, client.states, RemoteStatePaused,
"the listing filter must include paused sandboxes")
}
func TestReapOrphanSandboxesKeepsBoundSandboxes(t *testing.T) {
now := time.Now()
client := &fakeReaperClient{summaries: []RemoteSandboxSummary{
{ID: "sbx-a", State: RemoteStatePaused, StartedAt: now.Add(-5 * time.Hour)},
}}
deleted, err := ReapOrphanSandboxes(context.Background(), OrphanReaperDeps{
Client: client,
BoundIDs: map[string]struct{}{"sbx-a": {}},
TenantID: 7,
Grace: time.Minute,
Now: func() time.Time { return now },
})
require.NoError(t, err)
require.Zero(t, deleted)
require.Empty(t, client.deleted)
}
// Grace=0 is the backend-switch case: everything on the old backend is known to
// be abandoned, so even a just-created sandbox must be reaped.
func TestReapOrphanSandboxesZeroGraceIgnoresAge(t *testing.T) {
now := time.Now()
client := &fakeReaperClient{summaries: []RemoteSandboxSummary{
{ID: "sbx-fresh", State: RemoteStateRunning, StartedAt: now},
}}
deleted, err := ReapOrphanSandboxes(context.Background(), OrphanReaperDeps{
Client: client,
TenantID: 7,
Grace: 0,
Now: func() time.Time { return now },
})
require.NoError(t, err)
require.Equal(t, 1, deleted)
}
// The reaper must not reach across configs, even when both live on the same
// provider account.
func TestReapOrphanSandboxesScopesToConfig(t *testing.T) {
client := &fakeConfigSandboxClient{inventory: []RemoteSandboxSummary{
summary("sb-a", "7", "cfg-a"),
summary("sb-b", "7", "cfg-b"),
}}
deleted, err := ReapOrphanSandboxes(context.Background(), OrphanReaperDeps{
Client: client,
TenantID: 7,
ConfigID: "cfg-a",
BoundIDs: map[string]struct{}{},
})
require.NoError(t, err)
require.Equal(t, 1, deleted)
require.Equal(t, []string{"sb-a"}, client.deleted)
}
+96
View File
@@ -0,0 +1,96 @@
package sandbox
import (
"context"
"errors"
"time"
)
const (
ptyInputCoalesceMax = 4096
ptyInputQueueDepth = 64
)
var errPtyInputClosed = errors.New("terminal input closed")
// ptyInputCoalescer turns many small Write calls into fewer send() RPCs,
// and never blocks Write on the RPC itself (unless the queue is full).
//
// The first queued chunk is sent immediately. Further keystrokes that arrive
// while that RPC is in flight are drained and sent as one follow-up, so burst
// typing shares RPCs without a Nagle-style pause on the first character.
type ptyInputCoalescer struct {
send func(context.Context, []byte) error
ch chan []byte
done <-chan struct{}
ctx context.Context
}
func newPtyInputCoalescer(
ctx context.Context,
done <-chan struct{},
send func(context.Context, []byte) error,
) *ptyInputCoalescer {
c := &ptyInputCoalescer{
send: send,
ch: make(chan []byte, ptyInputQueueDepth),
done: done,
ctx: ctx,
}
go c.loop()
return c
}
func (c *ptyInputCoalescer) Write(ctx context.Context, data []byte) error {
if len(data) == 0 {
return nil
}
chunk := append([]byte(nil), data...)
select {
case <-c.done:
return errPtyInputClosed
case <-ctx.Done():
return ctx.Err()
case c.ch <- chunk:
return nil
}
}
func (c *ptyInputCoalescer) loop() {
for {
select {
case <-c.done:
return
case first := <-c.ch:
buf := append([]byte(nil), first...)
buf = c.drain(buf)
c.flush(buf)
}
}
}
func (c *ptyInputCoalescer) drain(buf []byte) []byte {
for len(buf) < ptyInputCoalesceMax {
select {
case more := <-c.ch:
buf = append(buf, more...)
default:
return buf
}
}
return buf
}
func (c *ptyInputCoalescer) flush(buf []byte) {
if len(buf) == 0 || c.send == nil {
return
}
select {
case <-c.done:
return
default:
}
rctx, cancel := context.WithTimeout(c.ctx, 5*time.Second)
_ = c.send(rctx, buf)
cancel()
}
@@ -0,0 +1,70 @@
package sandbox
import (
"context"
"sync"
"testing"
"time"
"github.com/stretchr/testify/require"
)
func TestPtyInputCoalescerWriteDoesNotWaitForSendRTT(t *testing.T) {
var mu sync.Mutex
var got []byte
var calls int
closed := make(chan struct{})
t.Cleanup(func() { close(closed) })
c := newPtyInputCoalescer(context.Background(), closed, func(_ context.Context, data []byte) error {
time.Sleep(40 * time.Millisecond)
mu.Lock()
calls++
got = append(got, data...)
mu.Unlock()
return nil
})
ctx := context.Background()
start := time.Now()
for _, b := range []byte("hello") {
require.NoError(t, c.Write(ctx, []byte{b}))
}
require.Less(t, time.Since(start), 25*time.Millisecond,
"Write must enqueue instead of waiting for each SendInput round-trip")
require.Eventually(t, func() bool {
mu.Lock()
defer mu.Unlock()
return string(got) == "hello"
}, time.Second, 5*time.Millisecond)
mu.Lock()
n := calls
mu.Unlock()
require.Less(t, n, 5, "burst keystrokes should share SendInput RPCs, got %d", n)
}
func TestPtyInputCoalescerSendsFirstChunkWithoutWaiting(t *testing.T) {
started := make(chan struct{})
closed := make(chan struct{})
t.Cleanup(func() { close(closed) })
c := newPtyInputCoalescer(context.Background(), closed, func(_ context.Context, _ []byte) error {
select {
case <-started:
default:
close(started)
}
time.Sleep(50 * time.Millisecond)
return nil
})
require.NoError(t, c.Write(context.Background(), []byte("x")))
select {
case <-started:
case <-time.After(20 * time.Millisecond):
t.Fatal("first keystroke must start SendInput immediately, not after a coalesce timer")
}
}
+583
View File
@@ -0,0 +1,583 @@
// Package sandbox: provider-neutral remote sandbox contract.
//
// This file introduces the RemoteSandboxClient interface and the neutral
// data-transfer types that SessionBoundManager depends on. Concrete backends
// (Cube, E2B, Docker) each provide an implementation
// in a separate adapter file.
//
// The interface is deliberately minimal: it covers only the operations
// SessionBoundManager and RemoteSandbox use in production today. Optional
// provider capabilities (pause/resume, timeout refresh, metadata recovery,
// etc.) are exposed as RemoteSandboxCapabilities so higher layers can degrade
// gracefully instead of relying on backend-specific type assertions.
package sandbox
import (
"context"
"time"
"academy/internal/types"
)
// RemoteProvider identifies a remote sandbox backend. Values match the
// stored SandboxType strings so wiring/logging stays uniform.
type RemoteProvider = SandboxType
// RemoteSandboxHandle is an opaque, provider-issued reference to a live
// sandbox. Adapters may wrap their SDK-specific object (e.g.
// *cubesandbox.Sandbox, *e2b.Sandbox) inside the concrete handle type; the
// manager only reads the stable identifiers exposed here.
type RemoteSandboxHandle interface {
// ID returns the provider-scoped sandbox identifier.
ID() string
// Provider returns the backend that issued this handle.
Provider() RemoteProvider
// Metadata returns the metadata originally recorded with the sandbox on
// creation, when the provider preserves it. Returns nil when the provider
// does not support metadata recovery.
Metadata() map[string]string
}
// RemoteConnectRequest re-attaches to an existing sandbox. TrafficAccessToken
// is the inbound credential recovered from the session binding; adapters apply
// it when the provider's connect response omits it, which is the normal case
// because the token is only ever issued at create time.
type RemoteConnectRequest struct {
SandboxID string
TrafficAccessToken string
}
// RemoteSessionConnector connects and checks lifecycle state using the same
// provider handle. It avoids Get (which itself connects on Cube/E2B) followed
// by another Connect. Terminal/missing sandboxes must return classified errors;
// transient failures must never authorize replacement of a session's sandbox.
type RemoteSessionConnector interface {
ConnectSession(context.Context, RemoteConnectRequest) (RemoteSandboxHandle, error)
}
// RemoteTimeoutMode describes how the remote provider should treat the
// requested idle timeout.
type RemoteTimeoutMode string
const (
// RemoteTimeoutServerDefault leaves the timeout unspecified so the
// provider applies its configured default.
RemoteTimeoutServerDefault RemoteTimeoutMode = "server"
// RemoteTimeoutExplicit uses RemoteTimeoutPolicy.Value verbatim. A zero
// value asks for immediate on-timeout action; a negative value asks for
// "never" when the provider supports it (adapters return
// RemoteErrorKindUnsupported otherwise).
RemoteTimeoutExplicit RemoteTimeoutMode = "explicit"
)
// RemoteTimeoutAction is the provider-side action taken when idle timeout
// elapses.
type RemoteTimeoutAction string
const (
// RemoteOnTimeoutPause pauses the sandbox and preserves its filesystem
// state so it can be resumed later.
RemoteOnTimeoutPause RemoteTimeoutAction = "pause"
// RemoteOnTimeoutKill destroys the sandbox and releases all resources.
RemoteOnTimeoutKill RemoteTimeoutAction = "kill"
)
// RemoteTimeoutPolicy is the provider-neutral timeout configuration.
type RemoteTimeoutPolicy struct {
Mode RemoteTimeoutMode
Value time.Duration
Action RemoteTimeoutAction
// AutoResume asks the provider to resume a paused sandbox on the next
// Connect. Adapters that cannot honour this must return
// RemoteErrorKindUnsupported at Create time.
AutoResume bool
}
// RemoteVolumeMount describes a volume to mount into the sandbox at creation
// time. Both Cube and E2B support named-volume mounts, making this a
// provider-neutral concept. Each entry references a pre-created volume by
// Name and the sandbox-internal Path at which it should appear.
type RemoteVolumeMount struct {
// Name identifies the volume. Required.
Name string
// Path is the mount point inside the sandbox. Required.
Path string
}
// RemoteCreateRequest holds the neutral parameters for spawning a new sandbox.
type RemoteCreateRequest struct {
// TemplateID references the pre-baked sandbox template. Required.
TemplateID string
// FromSnapshot is set when TemplateID is a skill or fork snapshot rather
// than a base template. Aliyun Agent Sandbox rejects create-from-snapshot
// requests that resend env vars or function-config overrides.
FromSnapshot bool
// Timeout controls the idle-timeout policy.
Timeout RemoteTimeoutPolicy
// Metadata is a small key/value bag the provider stores alongside the
// sandbox. Academy uses this to recover ownership of stray sandboxes
// after a restart. Adapters that cannot persist metadata return
// RemoteErrorKindUnsupported when non-empty metadata is supplied.
Metadata map[string]string
// EnvVars is baked into the sandbox at creation time. Optional.
EnvVars map[string]string
// Network is the neutral outbound-network policy for the new sandbox.
// A zero-value policy asks the adapter to apply the provider's default
// behaviour (see RemoteNetworkPolicy for the exact semantics).
Network RemoteNetworkPolicy
// VolumeMounts specifies volumes to mount into the sandbox at creation
// time. Optional. When non-empty, the adapter maps each entry to the
// provider-native volume mount API (e2b.VolumeMount for E2B, etc.).
VolumeMounts []RemoteVolumeMount
}
// RemoteNetworkPolicy is the provider-neutral outbound-network policy for a
// new sandbox. The fields both Cube and E2B accept are shared; the two L7
// extensions they do not share are carried here as separate slices rather
// than merged, because their shapes have nothing in common. Each adapter
// consumes its own and ignores the other's. Extensions with no admin-facing
// surface yet (egress proxies, masked host names) still stay in the adapters.
//
// Field semantics match the underlying providers:
//
// - AllowInternetAccess: top-level egress switch. Both adapters materialise
// nil as true rather than leaving it unset, because the provider default
// is the template's rather than the protocol's. ResolveEffectiveConfig
// always fills it, so nil reaches an adapter only from a hand-built
// Config. When false the sandbox has no default egress; specific hosts
// must appear in AllowOut.
// - AllowPublicTraffic: whether the sandbox is reachable from the public
// internet by URL. ResolveEffectiveConfig always sets this to false
// (credential required). nil reaches an adapter only from a hand-built
// Config and is materialised as false there too. true is leftover for
// tests; production create never sends it.
// - AllowOut / DenyOut: CIDR blocks or domain names. Cube treats these as
// L3/L4 filters; E2B applies domain-level filtering only on HTTP(S).
// Both providers require that specific domain allow-lists be paired
// with a deny-all; types.ValidateSandboxNetworkPolicy enforces that at
// save time, so the adapters never see the provider-native error.
type RemoteNetworkPolicy struct {
AllowInternetAccess *bool
AllowPublicTraffic *bool
AllowOut []string
DenyOut []string
// CubeRules / E2BHostRules are the provider-specific L7 extensions. Each
// adapter consumes its own and ignores the other's, so this type stays a
// superset rather than a lowest common denominator.
CubeRules []RemoteCubeEgressRule
E2BHostRules []RemoteE2BHostRule
}
// DeniesEgressByDefault reports whether outbound traffic falls back to deny,
// leaving only AllowOut (and L7 rule targets) reachable.
//
// It accepts both spellings the drawer and the validator accept: the top-level
// switch turned off, or a deny-all entry in DenyOut. A caller that checks only
// AllowInternetAccess misreads a strict-but-valid config as an open one, which
// is how the deep connectivity check came to report a correct deny-all policy
// as a hard egress failure.
func (p RemoteNetworkPolicy) DeniesEgressByDefault() bool {
if p.AllowInternetAccess != nil && !*p.AllowInternetAccess {
return true
}
return types.DenyOutCoversAllIPv4(p.DenyOut)
}
// RemoteInboundTokenCarrier is implemented by handles whose provider issues
// a per-sandbox inbound traffic token. Cube and E2B always do; Docker does
// not. It is an optional capability in the same spirit as RemoteSnapshotManager.
type RemoteInboundTokenCarrier interface {
TrafficAccessToken() string
}
// InboundTokenOf returns the inbound credential a handle carries, or "" when
// the provider has none. Callers persist it so a later reconnect can restore
// it.
func InboundTokenOf(handle RemoteSandboxHandle) string {
carrier, ok := handle.(RemoteInboundTokenCarrier)
if !ok {
return ""
}
return carrier.TrafficAccessToken()
}
// RemoteCubeEgressRule is one CubeEgress L7 rule in neutral form. Allow is
// phrased positively here even though the stored config says Deny: adapters
// map onto provider payloads whose field is also an allow flag, and having
// the negation happen exactly once (in ResolveEffectiveConfig) is what keeps
// a double negative from creeping in.
type RemoteCubeEgressRule struct {
Name string
Scheme string
SNI string
Host string
Methods []string
Path string
Allow bool
Audit string
Inject []RemoteHeaderInject
}
// RemoteHeaderInject is one credential header injected by the egress proxy.
// Format defaults to "${SECRET}" provider-side when empty.
type RemoteHeaderInject struct {
Header string
Secret string
Format string
}
// RemoteE2BHostRule is one E2B per-host request transform.
type RemoteE2BHostRule struct {
Host string
Headers map[string]string
}
// RemoteSandboxSummary is the neutral view of a sandbox listing / probe.
type RemoteSandboxSummary struct {
// ID is the provider-scoped sandbox identifier.
ID string
// TemplateID is the template the sandbox was created from.
TemplateID string
// State is the normalized lifecycle state. See RemoteSandboxState.
State RemoteSandboxState
// RawState is the provider-native state string, retained for diagnostics
// only. SessionBoundManager must not branch on RawState.
RawState string
// Metadata is the sandbox metadata bag. May be nil when the provider does
// not support metadata.
Metadata map[string]string
// StartedAt records when the sandbox was created; zero value when the
// provider does not report it.
StartedAt time.Time
// EndAt records when the sandbox was terminated; zero when unknown or
// still running.
EndAt time.Time
}
// RemoteSandboxState is the coordinator-facing lifecycle state.
type RemoteSandboxState string
const (
// RemoteStateRunning: sandbox is up and reachable.
RemoteStateRunning RemoteSandboxState = "running"
// RemoteStatePaused: sandbox is paused; resumable.
RemoteStatePaused RemoteSandboxState = "paused"
// RemoteStateTransitioning: sandbox is in a transient lifecycle state
// (pausing, resuming, provisioning, ...). Treated as "still owned" by
// SessionBoundManager but not immediately usable.
RemoteStateTransitioning RemoteSandboxState = "transitioning"
// RemoteStateTerminal: sandbox is gone. Bindings referencing this state
// can be replaced.
RemoteStateTerminal RemoteSandboxState = "terminal"
// RemoteStateUnknown: adapter could not classify the raw state. Treated
// as transient (do not replace the binding).
RemoteStateUnknown RemoteSandboxState = "unknown"
)
// RemoteListFilter narrows a List call. Empty fields mean "no filter".
type RemoteListFilter struct {
// Metadata: only return sandboxes whose metadata contains all these
// key/value pairs. Adapters that cannot filter server-side may filter
// client-side and MUST return the same set.
Metadata map[string]string
// States restricts the response to the given normalized states. Empty
// means "any state".
States []RemoteSandboxState
}
// RemoteExecRequest describes a single command invocation. See the
// RemoteSandboxClient.Exec contract for how Shell interacts with Args.
type RemoteExecRequest struct {
// OnOutput receives stdout/stderr chunks while the command runs. It is an
// observation hook only; callers must not retain the supplied bytes.
OnOutput func(stream string, chunk []byte) `json:"-"`
// Command is the executable name (Shell=false) or the shell expression
// (Shell=true).
Command string
// Args are argv[1:] when Shell=false; must be empty when Shell=true.
Args []string
// Shell selects between direct exec (false) and shell interpretation
// (true). RemoteSandboxClient implementations must reject requests that
// combine Shell=true with a non-empty Args.
Shell bool
// Stdin is written to the process before it starts reading.
Stdin string
// Env is merged into the process environment.
Env map[string]string
// WorkDir is the process working directory. Empty means "provider
// default".
WorkDir string
// User is the OS user the process runs as. Empty means "provider
// default". Both backends support selecting it (E2B WithUser, Cube
// CommandOptions.User).
//
// The default is root: each chat session owns its own sandbox
// (one-session-one-sandbox, single tenant), so there is no shared-volume
// tenant boundary inside a sandbox for file-mode isolation to defend.
// Cross-tenant and host isolation live at the container boundary, not in
// the exec account. Callers that still rely on in-container filesystem
// permissions should not treat mode bits as a root isolation boundary.
// Enforce read-only access at the mount level instead.
User string
// Timeout bounds a single exec call. Zero means "use provider default".
Timeout time.Duration
}
// DefaultSandboxExecUser is the account Academy runs sandboxed scripts as.
// It is root: every chat session gets its own sandbox, so the in-container
// account is not a tenant boundary and root is the least surprising default
// for an agent that installs packages and writes wherever it needs. The
// adapters resolve an empty request user to this constant, independent of
// the image USER. The image retains a "user" compatibility account for
// E2B/Cube tooling that explicitly selects it.
const DefaultSandboxExecUser = "root"
// RemoteExecResult is the neutral shape returned by Exec.
type RemoteExecResult struct {
Stdout string
Stderr string
ExitCode int
Duration time.Duration
Killed bool
}
// RemoteDirEntry describes one entry inside a directory listing.
type RemoteDirEntry struct {
Name string
Path string
Type RemoteDirEntryType
Size int64
ModTime time.Time
}
// RemoteDirEntryType is the coordinator-facing entry kind.
type RemoteDirEntryType string
const (
RemoteEntryFile RemoteDirEntryType = "file"
RemoteEntryDir RemoteDirEntryType = "dir"
// RemoteEntryOther covers symlinks, sockets, devices, etc. Academy
// artifact code treats these as opaque and skips them.
RemoteEntryOther RemoteDirEntryType = "other"
)
// RemoteStatEntry is the neutral shape returned by Stat.
type RemoteStatEntry struct {
Path string
Type RemoteDirEntryType
Size int64
ModTime time.Time
}
// RemoteSandboxCapabilities advertises which optional operations a client
// supports natively. SessionBoundManager reads this to skip provider-specific
// paths (e.g. metadata-based recovery) on backends that do not support them.
//
// Missing metadata/list capabilities use less-optimal but correct behaviour
// (rely on the binding store instead of scanning provider metadata).
// SupportsReconnect is required for persistent session lifecycle management.
type RemoteSandboxCapabilities struct {
// SupportsReconnect is true when Connect can recover an operable handle
// from a provider-scoped sandbox ID after a Academy process restart.
SupportsReconnect bool
// SupportsMetadata is true when Create+List preserve the Metadata bag,
// enabling orphan-sandbox recovery after a Academy restart.
SupportsMetadata bool
// SupportsListSandboxes is true when List enumerates existing sandboxes
// (independent of metadata support).
SupportsListSandboxes bool
// SupportsPauseResume signals that idle sandboxes can be paused and
// resumed instead of destroyed. Purely informational for now; the
// current SessionBoundManager does not itself pause/resume.
SupportsPauseResume bool
// SupportsTimeoutRefresh indicates the provider can extend a sandbox's
// idle timeout after creation. Informational.
SupportsTimeoutRefresh bool
// SupportsFilesystemEnumeration is true when the provider implements
// ListDir, MakeDir, Stat, and Remove. SessionBoundManager only
// advertises the SessionFileStore capability when this is true — the
// application layer then knows to deregister list/read/attachment
// staging tools that would otherwise fail at request time.
SupportsFilesystemEnumeration bool
// SupportsSnapshots reports whether the provider can snapshot a running
// sandbox into a reusable image. Snapshot IDs double as template IDs on
// Cube, E2B, and Docker, which is what makes skill images work.
SupportsSnapshots bool
// SupportsVolumes is true when the provider can mount a named volume into
// a sandbox at creation time (RemoteCreateRequest.VolumeMounts). Callers
// use this to tell an operator up front that a backend cannot serve
// volume-based features, instead of failing later at first use.
SupportsVolumes bool
// SupportsTerminals is true when the provider can open interactive PTYs
// inside a running sandbox (RemoteTerminalManager). Callers use this to
// reject terminal features with an unsupported-backend error instead of
// failing after the WebSocket is upgraded.
SupportsTerminals bool
// SupportsDesktop is true when the provider can relay a WebSocket to a
// non-envd data-plane port inside the sandbox, which is what the VNC
// desktop needs (websockify on 6080). It is separate from
// SupportsTerminals: the terminal rides envd's PTY service, the desktop
// rides a raw port through the gateway. Docker is false — not because it
// cannot, but because it is not scheduled.
SupportsDesktop bool
}
// RemoteSandboxClient is the contract SessionBoundManager talks to. All
// backends (Cube, E2B, ...) must satisfy this interface via a thin adapter.
//
// Concurrency: implementations MUST be safe for concurrent use.
//
// Cancellation: every method must honour ctx.Done. Cancellation returns a
// RemoteError whose Kind is RemoteErrorKindTimeout when the deadline elapsed
// server-side, or the wrapped ctx.Err() otherwise.
type RemoteSandboxClient interface {
// Provider identifies the backend. Used by the binding schema to detect
// provider mismatches after a mode switch.
Provider() RemoteProvider
// Capabilities returns the static capability set of this client. It is
// safe to call before Health succeeds.
Capabilities() RemoteSandboxCapabilities
// Health probes the provider's control plane. Returns nil when reachable.
Health(ctx context.Context) error
// --- lifecycle ---
// Create spawns a new sandbox and returns an opaque handle. The handle
// is owned by the caller; Delete must eventually be called.
Create(ctx context.Context, req RemoteCreateRequest) (RemoteSandboxHandle, error)
// Connect re-attaches to an already-running sandbox. Adapters that
// cannot support reconnect must return RemoteErrorKindUnsupported here
// and set SupportsReconnect=false.
Connect(ctx context.Context, req RemoteConnectRequest) (RemoteSandboxHandle, error)
// Get fetches a single sandbox summary by ID. Returns nil summary and
// RemoteErrorKindNotFound when the sandbox is gone.
Get(ctx context.Context, sandboxID string) (*RemoteSandboxSummary, error)
// List enumerates sandboxes visible to this client, optionally filtered.
List(ctx context.Context, filter RemoteListFilter) ([]RemoteSandboxSummary, error)
// Delete destroys a sandbox. Deleting a non-existent sandbox returns
// RemoteErrorKindNotFound; callers typically treat that as success.
Delete(ctx context.Context, sandboxID string) error
// --- execution ---
// Exec runs one command inside the sandbox. See RemoteExecRequest for
// the Shell/Args contract.
Exec(ctx context.Context, handle RemoteSandboxHandle, req RemoteExecRequest) (*RemoteExecResult, error)
// --- filesystem ---
WriteFile(ctx context.Context, handle RemoteSandboxHandle, path string, content []byte) error
ReadFile(ctx context.Context, handle RemoteSandboxHandle, path string) ([]byte, error)
ListDir(ctx context.Context, handle RemoteSandboxHandle, path string) ([]RemoteDirEntry, error)
// MakeDir creates path, including parents. A directory that already
// exists is success: envd's MakeDir is not mkdir -p, and adapters must
// hide that so writing a second file into the same folder (or seeding
// SKILL.md after resetSkillDir) does not fail.
MakeDir(ctx context.Context, handle RemoteSandboxHandle, path string) error
Remove(ctx context.Context, handle RemoteSandboxHandle, path string) error
Stat(ctx context.Context, handle RemoteSandboxHandle, path string) (*RemoteStatEntry, error)
}
// cloneMetadata returns a shallow copy of source. Nil input returns nil so
// callers can distinguish "explicitly empty" from "not set".
func cloneMetadata(source map[string]string) map[string]string {
if source == nil {
return nil
}
result := make(map[string]string, len(source))
for key, value := range source {
result[key] = value
}
return result
}
// RemoteSnapshotRef identifies one provider-side snapshot. ID can be passed
// straight back as RemoteCreateRequest.TemplateID: Cube and E2B store
// snapshots as templates, and Docker stores them as local image tags.
type RemoteSnapshotRef struct {
ID string
Names []string
}
// RemoteSnapshotManager is an optional capability used only by the skill
// install/remove paths. Session execution never touches it.
type RemoteSnapshotManager interface {
// CreateSnapshot snapshots a running sandbox. An empty name lets the
// provider generate one. The provider pauses the sandbox while the
// snapshot is taken.
CreateSnapshot(ctx context.Context, sandboxID string, name string) (RemoteSnapshotRef, error)
// DeleteSnapshot removes a snapshot. A missing snapshot is NOT an error:
// both SDKs treat delete as idempotent and so must every adapter.
DeleteSnapshot(ctx context.Context, snapshotID string) error
// ListSnapshots lists snapshots. An empty sandboxID lists all of them.
ListSnapshots(ctx context.Context, sandboxID string) ([]RemoteSnapshotRef, error)
}
// SnapshotManagerFrom narrows a client to its snapshot capability. It returns
// false for providers that cannot snapshot, so callers can fall back to the
// base template instead of failing.
//
// Both signals must agree: the type assertion finds the methods, and
// SupportsSnapshots is the advertised capability. A wrapper that happens to
// embed snapshot methods must not be treated as snapshot-capable when the
// flag is off.
func SnapshotManagerFrom(client RemoteSandboxClient) (RemoteSnapshotManager, bool) {
if client == nil {
return nil, false
}
mgr, ok := client.(RemoteSnapshotManager)
if !ok {
return nil, false
}
if !client.Capabilities().SupportsSnapshots {
return nil, false
}
return mgr, true
}
+121
View File
@@ -0,0 +1,121 @@
package sandbox
import (
"context"
"testing"
"time"
)
type contractHandle struct {
id string
provider RemoteProvider
metadata map[string]string
}
func (h *contractHandle) ID() string { return h.id }
func (h *contractHandle) Provider() RemoteProvider { return h.provider }
func (h *contractHandle) Metadata() map[string]string { return h.metadata }
type contractClient struct {
provider RemoteProvider
capabilities RemoteSandboxCapabilities
}
func (c *contractClient) Provider() RemoteProvider { return c.provider }
func (c *contractClient) Capabilities() RemoteSandboxCapabilities {
return c.capabilities
}
func (c *contractClient) Health(context.Context) error { return nil }
func (c *contractClient) Create(_ context.Context, req RemoteCreateRequest) (RemoteSandboxHandle, error) {
return &contractHandle{id: "sandbox-1", provider: c.provider, metadata: req.Metadata}, nil
}
func (c *contractClient) Connect(context.Context, RemoteConnectRequest) (RemoteSandboxHandle, error) {
return &contractHandle{id: "sandbox-1", provider: c.provider}, nil
}
func (c *contractClient) Get(context.Context, string) (*RemoteSandboxSummary, error) {
return &RemoteSandboxSummary{ID: "sandbox-1", State: RemoteStateRunning}, nil
}
func (c *contractClient) List(context.Context, RemoteListFilter) ([]RemoteSandboxSummary, error) {
return []RemoteSandboxSummary{{ID: "sandbox-1", State: RemoteStateRunning}}, nil
}
func (c *contractClient) Delete(context.Context, string) error { return nil }
func (c *contractClient) Exec(
context.Context,
RemoteSandboxHandle,
RemoteExecRequest,
) (*RemoteExecResult, error) {
return &RemoteExecResult{ExitCode: 0}, nil
}
func (c *contractClient) WriteFile(context.Context, RemoteSandboxHandle, string, []byte) error {
return nil
}
func (c *contractClient) ReadFile(context.Context, RemoteSandboxHandle, string) ([]byte, error) {
return []byte("content"), nil
}
func (c *contractClient) ListDir(context.Context, RemoteSandboxHandle, string) ([]RemoteDirEntry, error) {
return []RemoteDirEntry{{Name: "file", Type: RemoteEntryFile}}, nil
}
func (c *contractClient) MakeDir(context.Context, RemoteSandboxHandle, string) error {
return nil
}
func (c *contractClient) Remove(context.Context, RemoteSandboxHandle, string) error {
return nil
}
func (c *contractClient) Stat(context.Context, RemoteSandboxHandle, string) (*RemoteStatEntry, error) {
return &RemoteStatEntry{Path: "/workspace/file", Type: RemoteEntryFile}, nil
}
var _ RemoteSandboxClient = (*contractClient)(nil)
func TestRemoteClientContractExposesProviderAndReconnectCapability(t *testing.T) {
t.Parallel()
client := &contractClient{
provider: SandboxTypeE2B,
capabilities: RemoteSandboxCapabilities{
SupportsReconnect: true,
},
}
if got := client.Provider(); got != SandboxTypeE2B {
t.Fatalf("Provider() = %q, want %q", got, SandboxTypeE2B)
}
if !client.Capabilities().SupportsReconnect {
t.Fatal("reconnect capability must be explicit")
}
}
func TestRemoteTypesRepresentProviderNeutralSemantics(t *testing.T) {
t.Parallel()
timeout := RemoteTimeoutPolicy{
Mode: RemoteTimeoutExplicit,
Value: 15 * time.Minute,
Action: RemoteOnTimeoutPause,
AutoResume: true,
}
if timeout.Mode != RemoteTimeoutExplicit || timeout.Action != RemoteOnTimeoutPause {
t.Fatalf("unexpected timeout policy: %+v", timeout)
}
direct := RemoteExecRequest{Command: "python3", Args: []string{"-V"}}
if direct.Shell || len(direct.Args) != 1 {
t.Fatalf("direct execution lost argv semantics: %+v", direct)
}
shell := RemoteExecRequest{Command: "printf '%s' ok", Shell: true}
if !shell.Shell || len(shell.Args) != 0 {
t.Fatalf("shell execution representation is ambiguous: %+v", shell)
}
states := []RemoteSandboxState{
RemoteStateRunning,
RemoteStatePaused,
RemoteStateTransitioning,
RemoteStateTerminal,
RemoteStateUnknown,
}
if got, want := len(states), 5; got != want {
t.Fatalf("normalized state count = %d, want %d", got, want)
}
}
+290
View File
@@ -0,0 +1,290 @@
// Package sandbox: provider-neutral error contract for RemoteSandboxClient.
//
// Adapters normalize provider-native errors (HTTP status codes, SDK error
// types, gRPC codes) into RemoteError with a stable Kind so SessionBoundManager
// can make lifecycle decisions without knowing which backend is in use.
//
// Rule of thumb for adapters:
//
// - NotFound / Terminal → binding may be replaced
// - Timeout / Unavailable / Capacity / Conflict / Authentication → PRESERVE binding
// - InvalidRequest / Unsupported → surface to caller; do not touch binding
// - Internal → last resort; preserve binding (default-preserve on ambiguity)
//
// The original cause is always retained via errors.Unwrap so callers can
// still inspect provider-specific detail when logging.
package sandbox
import (
"errors"
"fmt"
"net/http"
"strings"
)
// RemoteErrorKind is the stable, provider-neutral classification of a
// RemoteSandboxClient failure.
type RemoteErrorKind string
const (
// RemoteErrorKindNotFound: sandbox / file / path does not exist.
RemoteErrorKindNotFound RemoteErrorKind = "not_found"
// RemoteErrorKindTerminal: sandbox is permanently gone (killed,
// crashed, terminated). Semantically equivalent to NotFound for
// lifecycle purposes but distinct for observability.
RemoteErrorKindTerminal RemoteErrorKind = "terminal"
// RemoteErrorKindAuthentication: bad credentials, expired token, etc.
RemoteErrorKindAuthentication RemoteErrorKind = "authentication"
// RemoteErrorKindInvalidRequest: caller-side error (bad template ID,
// bad path, oversized payload). Not retryable.
RemoteErrorKindInvalidRequest RemoteErrorKind = "invalid_request"
// RemoteErrorKindUnsupported: provider does not implement the requested
// capability (e.g. metadata, "never" timeout).
RemoteErrorKindUnsupported RemoteErrorKind = "unsupported"
// RemoteErrorKindConflict: concurrent modification (e.g. sandbox state
// changed under us, template being built).
RemoteErrorKindConflict RemoteErrorKind = "conflict"
// RemoteErrorKindCapacity: quota / rate-limit / out-of-capacity.
RemoteErrorKindCapacity RemoteErrorKind = "capacity"
// RemoteErrorKindTimeout: request exceeded its deadline before the
// provider responded. Distinct from execution timeout, which is a
// normal RemoteExecResult with Killed=true.
RemoteErrorKindTimeout RemoteErrorKind = "timeout"
// RemoteErrorKindUnavailable: transient provider outage (5xx, network
// error, control-plane unreachable).
RemoteErrorKindUnavailable RemoteErrorKind = "unavailable"
// RemoteErrorKindInternal: catch-all for unclassified failures.
// Adapters SHOULD narrow this to a more specific kind when possible.
RemoteErrorKindInternal RemoteErrorKind = "internal"
)
// RemoteError is the wire-agnostic error type returned by every
// RemoteSandboxClient method.
type RemoteError struct {
// Kind classifies the failure for coordinator decisions.
Kind RemoteErrorKind
// Provider identifies which backend produced the error, for logging.
Provider RemoteProvider
// Op names the RemoteSandboxClient operation (e.g. "Create", "Exec").
Op string
// Message is a human-readable summary. Provider-specific status codes
// or SDK error strings belong here.
Message string
// StatusCode is the provider's HTTP status when the failure came from an
// HTTP response, or 0 when it did not. Kind deliberately collapses statuses
// that call for the same lifecycle decision, so diagnostics that must tell
// those statuses apart read this instead of re-parsing Message.
StatusCode int
// Cause is the original provider-side error, retained for
// errors.Unwrap so callers can still errors.Is / errors.As it.
Cause error
}
// Error implements the error interface.
func (e *RemoteError) Error() string {
if e == nil {
return "<nil remote error>"
}
prov := string(e.Provider)
if prov == "" {
prov = "remote"
}
if e.Message == "" && e.Cause != nil {
return fmt.Sprintf("%s %s: %s: %v", prov, e.Op, e.Kind, e.Cause)
}
if e.Cause != nil {
return fmt.Sprintf("%s %s: %s: %s: %v", prov, e.Op, e.Kind, e.Message, e.Cause)
}
return fmt.Sprintf("%s %s: %s: %s", prov, e.Op, e.Kind, e.Message)
}
// Unwrap exposes the wrapped provider-native error for errors.Is / errors.As.
func (e *RemoteError) Unwrap() error {
if e == nil {
return nil
}
return e.Cause
}
// NewRemoteError builds a RemoteError. Convenience for adapters.
func NewRemoteError(provider RemoteProvider, op string, kind RemoteErrorKind, message string, cause error) *RemoteError {
return &RemoteError{
Kind: kind,
Provider: provider,
Op: op,
Message: message,
Cause: cause,
}
}
// RemoteErrorDiagnostics formats err for logs. When err wraps a RemoteError
// it includes kind, op, HTTP status, and message without re-parsing text.
func RemoteErrorDiagnostics(err error) string {
if err == nil {
return ""
}
var re *RemoteError
if !errors.As(err, &re) {
return err.Error()
}
parts := []string{string(re.Kind)}
if re.Op != "" {
parts = append(parts, "op="+re.Op)
}
if re.StatusCode != 0 {
parts = append(parts, fmt.Sprintf("http=%d", re.StatusCode))
}
if re.Message != "" {
parts = append(parts, re.Message)
}
return strings.Join(parts, " ")
}
// remoteKind extracts the Kind from err, or "" when err is not a
// *RemoteError. Wraps errors.As so callers can pass any error value.
func remoteKind(err error) RemoteErrorKind {
if err == nil {
return ""
}
var re *RemoteError
if errors.As(err, &re) {
return re.Kind
}
return ""
}
// IsRemoteNotFound reports whether err classifies as sandbox / path not found.
// Both NotFound and Terminal are treated as "gone" for coordinator decisions.
func IsRemoteNotFound(err error) bool {
switch remoteKind(err) {
case RemoteErrorKindNotFound, RemoteErrorKindTerminal:
return true
default:
return false
}
}
// IsRemoteInvalidRequest reports whether err classifies as a caller-side
// error (bad template, oversized payload, malformed path, etc.).
func IsRemoteInvalidRequest(err error) bool {
return remoteKind(err) == RemoteErrorKindInvalidRequest
}
// IsRemoteConflict reports whether the provider refused the call because the
// resource is busy (concurrent mutation, snapshot still referenced, …).
func IsRemoteConflict(err error) bool {
return remoteKind(err) == RemoteErrorKindConflict
}
// snapshotDeleteKind reclassifies a snapshot/template delete that failed
// because sandboxes still reference it. E2B returns that as HTTP 400
// invalid_request; it is Conflict: the caller did nothing wrong and should
// retry after those sandboxes (typically paused) go away.
func snapshotDeleteKind(op string, kind RemoteErrorKind, message string) RemoteErrorKind {
if op != "DeleteSnapshot" && op != "DeleteTemplate" {
return kind
}
if kind == RemoteErrorKindConflict || snapshotInUseBySandboxes(message) {
return RemoteErrorKindConflict
}
return kind
}
func snapshotInUseBySandboxes(message string) bool {
msg := strings.ToLower(message)
if strings.Contains(msg, "paused sandbox") {
return true
}
if strings.Contains(msg, "sandboxes using") {
return true
}
if strings.Contains(msg, "cannot delete template") && strings.Contains(msg, "using it") {
return true
}
// Cube CoW: HTTP 500 / 130409 while source + child sandboxes still reference the snapshot.
if strings.Contains(msg, "runtime ref") {
return true
}
return strings.Contains(msg, "130409")
}
// IsRemoteDirAlreadyExists reports whether MakeDir failed because the
// directory is already present. Cube's envd MakeDir is not mkdir -p: a
// directory created by a previous call (or by a shell `mkdir -p` in
// resetSkillDir) comes back as an internal error instead of success, and
// seeding SKILL.md would otherwise abort on a directory it is supposed to
// write into.
func IsRemoteDirAlreadyExists(err error) bool {
if err == nil {
return false
}
msg := strings.ToLower(err.Error())
if strings.Contains(msg, "directory already exists") {
return true
}
return remoteKind(err) == RemoteErrorKindConflict && strings.Contains(msg, "already exists")
}
// ignoreExistingDir turns an exist-ok MakeDir failure into success so callers
// can treat MakeDir as mkdir -p.
func ignoreExistingDir(err error) error {
if IsRemoteDirAlreadyExists(err) {
return nil
}
return err
}
// CanReplaceRemoteBinding reports whether the error proves that the bound
// remote sandbox is permanently gone. This is intentionally allow-list based:
// unknown and newly introduced errors preserve bindings by default.
func CanReplaceRemoteBinding(err error) bool {
switch remoteKind(err) {
case RemoteErrorKindNotFound, RemoteErrorKindTerminal:
return true
default:
return false
}
}
// httpErrorKind maps an HTTP status code to a RemoteErrorKind. It is shared
// by all remote sandbox adapter backends (Cube, E2B).
func httpErrorKind(op string, status int) RemoteErrorKind {
switch status {
case http.StatusBadRequest, http.StatusUnprocessableEntity:
return RemoteErrorKindInvalidRequest
case http.StatusUnauthorized, http.StatusForbidden:
return RemoteErrorKindAuthentication
case http.StatusNotFound:
if op == "Create" {
return RemoteErrorKindInvalidRequest
}
return RemoteErrorKindNotFound
case http.StatusRequestTimeout, http.StatusGatewayTimeout:
return RemoteErrorKindTimeout
case http.StatusConflict:
return RemoteErrorKindConflict
case http.StatusGone:
return RemoteErrorKindTerminal
case http.StatusTooManyRequests, http.StatusInsufficientStorage:
return RemoteErrorKindCapacity
default:
if status >= 500 {
return RemoteErrorKindUnavailable
}
return RemoteErrorKindInternal
}
}
+272
View File
@@ -0,0 +1,272 @@
package sandbox
import (
"errors"
"fmt"
"testing"
)
func TestRemoteBindingDecision(t *testing.T) {
t.Parallel()
tests := []struct {
name string
err error
replace bool
preserve bool
}{
{name: "nil", err: nil},
{
name: "not found",
err: NewRemoteError(SandboxTypeCube, "Get", RemoteErrorKindNotFound, "gone", nil),
replace: true,
preserve: false,
},
{
name: "terminal",
err: NewRemoteError(SandboxTypeCube, "Get", RemoteErrorKindTerminal, "terminated", nil),
replace: true,
preserve: false,
},
{
name: "authentication",
err: NewRemoteError(SandboxTypeCube, "Connect", RemoteErrorKindAuthentication, "denied", nil),
preserve: true,
},
{
name: "invalid request",
err: NewRemoteError(SandboxTypeCube, "Create", RemoteErrorKindInvalidRequest, "bad template", nil),
preserve: true,
},
{
name: "unsupported",
err: NewRemoteError(SandboxTypeCube, "Connect", RemoteErrorKindUnsupported, "no reconnect", nil),
preserve: true,
},
{
name: "conflict",
err: NewRemoteError(SandboxTypeCube, "Delete", RemoteErrorKindConflict, "busy", nil),
preserve: true,
},
{
name: "capacity",
err: NewRemoteError(SandboxTypeCube, "Create", RemoteErrorKindCapacity, "full", nil),
preserve: true,
},
{
name: "timeout",
err: NewRemoteError(SandboxTypeCube, "Get", RemoteErrorKindTimeout, "deadline", nil),
preserve: true,
},
{
name: "unavailable",
err: NewRemoteError(SandboxTypeCube, "Health", RemoteErrorKindUnavailable, "offline", nil),
preserve: true,
},
{
name: "internal",
err: NewRemoteError(SandboxTypeCube, "List", RemoteErrorKindInternal, "unknown", nil),
preserve: true,
},
{
name: "wrapped terminal",
err: fmt.Errorf("probe failed: %w", NewRemoteError(SandboxTypeCube, "Get", RemoteErrorKindTerminal, "dead", nil)),
replace: true,
preserve: false,
},
{
name: "unclassified defaults to preserve",
err: errors.New("provider returned an unknown error"),
preserve: true,
},
}
for _, tt := range tests {
tt := tt
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
if got := CanReplaceRemoteBinding(tt.err); got != tt.replace {
t.Fatalf("CanReplaceRemoteBinding() = %v, want %v", got, tt.replace)
}
})
}
}
func TestRemoteErrorRetainsCause(t *testing.T) {
t.Parallel()
cause := errors.New("connection reset")
err := NewRemoteError(
SandboxTypeCube,
"Connect",
RemoteErrorKindUnavailable,
"control plane unavailable",
cause,
)
if !errors.Is(err, cause) {
t.Fatal("RemoteError must retain its provider-native cause")
}
if got, want := err.Error(), "cube Connect: unavailable: control plane unavailable: connection reset"; got != want {
t.Fatalf("Error() = %q, want %q", got, want)
}
}
func TestRemoteErrorDiagnostics(t *testing.T) {
t.Parallel()
remote := NewRemoteError(
SandboxTypeCube, "Exec", RemoteErrorKindAuthentication,
"HTTP 403", errors.New("forbidden"),
)
remote.StatusCode = 403
got := RemoteErrorDiagnostics(remote)
if got != "authentication op=Exec http=403 HTTP 403" {
t.Fatalf("RemoteErrorDiagnostics() = %q", got)
}
if RemoteErrorDiagnostics(errors.New("plain")) != "plain" {
t.Fatal("expected plain error text")
}
}
func TestIsRemoteDirAlreadyExists(t *testing.T) {
t.Parallel()
cubeSeedErr := NewRemoteError(
SandboxTypeCube, "MakeDir", RemoteErrorKindInternal,
"failed to make dir /opt/academy/tenant/skills/sk-1: directory already exists: /opt/academy/tenant/skills/sk-1",
nil,
)
tests := []struct {
name string
err error
want bool
}{
{name: "nil", err: nil, want: false},
{name: "cube envd already exists", err: cubeSeedErr, want: true},
{
name: "wrapped cube error",
err: fmt.Errorf("sandbox: create install directory: %w", cubeSeedErr),
want: true,
},
{
name: "e2b conflict already exists",
err: NewRemoteError(
SandboxTypeE2B, "MakeDir", RemoteErrorKindConflict, "already exists", nil,
),
want: true,
},
{
name: "unrelated internal",
err: NewRemoteError(SandboxTypeCube, "MakeDir", RemoteErrorKindInternal, "disk full", nil),
want: false,
},
{
name: "conflict without already exists",
err: NewRemoteError(SandboxTypeCube, "Delete", RemoteErrorKindConflict, "busy", nil),
want: false,
},
}
for _, tt := range tests {
tt := tt
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
if got := IsRemoteDirAlreadyExists(tt.err); got != tt.want {
t.Fatalf("IsRemoteDirAlreadyExists() = %v, want %v", got, tt.want)
}
})
}
}
func TestIsRemoteConflict(t *testing.T) {
t.Parallel()
if IsRemoteConflict(nil) {
t.Fatal("nil is not a conflict")
}
conflict := NewRemoteError(SandboxTypeE2B, "DeleteSnapshot", RemoteErrorKindConflict, "busy", nil)
if !IsRemoteConflict(conflict) {
t.Fatal("Conflict kind must match")
}
invalid := NewRemoteError(
SandboxTypeE2B, "DeleteSnapshot", RemoteErrorKindInvalidRequest, "bad id", nil,
)
if IsRemoteConflict(invalid) {
t.Fatal("InvalidRequest must not match")
}
}
func TestSnapshotDeleteKindPromotesInUseToConflict(t *testing.T) {
t.Parallel()
inUse := "cannot delete template 'upfvuzpq0q6foo1mkpbkl' because there are paused sandboxes using it"
jsonBody := `e2b: status 400: {"code":400,"message":"` + inUse + `"}`
tests := []struct {
name string
op string
kind RemoteErrorKind
msg string
want RemoteErrorKind
}{
{
name: "e2b paused sandboxes 400",
op: "DeleteSnapshot",
kind: RemoteErrorKindInvalidRequest,
msg: inUse,
want: RemoteErrorKindConflict,
},
{
name: "json-wrapped e2b 400",
op: "DeleteSnapshot",
kind: RemoteErrorKindInvalidRequest,
msg: jsonBody,
want: RemoteErrorKindConflict,
},
{
name: "cube delete template",
op: "DeleteTemplate",
kind: RemoteErrorKindInvalidRequest,
msg: "cannot delete template x because there are sandboxes using it",
want: RemoteErrorKindConflict,
},
{
name: "cube 130409 runtime refs as 500",
op: "DeleteSnapshot",
kind: RemoteErrorKindInternal,
msg: "unavailable: CubeMaster returned error code 130409: template attempt is already in progress: " +
"snapshot snap-6a6707d7b51246c68ad643ee still has 2 active runtime ref(s): a@host, b@host (HTTP 500)",
want: RemoteErrorKindConflict,
},
{
name: "already conflict stays conflict",
op: "DeleteSnapshot",
kind: RemoteErrorKindConflict,
msg: "image is in use",
want: RemoteErrorKindConflict,
},
{
name: "generic 400 stays invalid",
op: "DeleteSnapshot",
kind: RemoteErrorKindInvalidRequest,
msg: "invalid snapshot id",
want: RemoteErrorKindInvalidRequest,
},
{
name: "other ops are unchanged",
op: "Create",
kind: RemoteErrorKindInvalidRequest,
msg: inUse,
want: RemoteErrorKindInvalidRequest,
},
}
for _, tt := range tests {
tt := tt
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
if got := snapshotDeleteKind(tt.op, tt.kind, tt.msg); got != tt.want {
t.Fatalf("snapshotDeleteKind() = %q, want %q", got, tt.want)
}
})
}
}
+618
View File
@@ -0,0 +1,618 @@
package sandbox
import (
"context"
"fmt"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/stretchr/testify/require"
)
type fakeRemoteHandle struct {
id string
provider RemoteProvider
metadata map[string]string
trafficAccessToken string
}
func (h *fakeRemoteHandle) ID() string { return h.id }
func (h *fakeRemoteHandle) Provider() RemoteProvider { return h.provider }
func (h *fakeRemoteHandle) Metadata() map[string]string {
return cloneStringMap(h.metadata)
}
func (h *fakeRemoteHandle) TrafficAccessToken() string { return h.trafficAccessToken }
// fakeTokenlessHandle models Docker, whose handle deliberately does not
// implement RemoteInboundTokenCarrier because the backend has no inbound
// credential at all. InboundTokenOf therefore returns "" for a reason that is
// not "the credential was lost".
type fakeTokenlessHandle struct {
id string
provider RemoteProvider
metadata map[string]string
}
func (h *fakeTokenlessHandle) ID() string { return h.id }
func (h *fakeTokenlessHandle) Provider() RemoteProvider { return h.provider }
func (h *fakeTokenlessHandle) Metadata() map[string]string {
return cloneStringMap(h.metadata)
}
type fakeRemoteRecord struct {
id string
templateID string
state RemoteSandboxState
rawState string
metadata map[string]string
startedAt time.Time
}
type fakeRemoteWriteFile struct {
path string
content []byte
}
type fakeRemoteClient struct {
mu sync.Mutex
provider RemoteProvider
capabilities RemoteSandboxCapabilities
nextID int
sandboxes map[string]*fakeRemoteRecord
createCount int
connectIDs []string
connects []RemoteConnectRequest
getIDs []string
deleteIDs []string
listCount int
lastCreateRequest RemoteCreateRequest
lastCreatedID string
trafficAccessToken string
// reissuesTokenOnConnect models a provider that hands the inbound token
// back on reconnect. E2B and Cube issue it only at create time, so the
// default false is the realistic behaviour.
reissuesTokenOnConnect bool
// connectTrafficToken, when set, is returned on Connect even if the
// request already carried a token — the provider-wins case.
connectTrafficToken string
// omitsInboundTokenCarrier makes handles skip
// RemoteInboundTokenCarrier, the way Docker's do.
omitsInboundTokenCarrier bool
createErr error
connectErrs map[string]error
getErrs map[string]error
deleteErrs map[string]error
listErr error
createHook func(context.Context, RemoteCreateRequest) error
afterCreate func(RemoteSandboxHandle)
deleteHook func(context.Context, string) error
execHook func(RemoteExecRequest) (*RemoteExecResult, error)
makeDirPaths []string
failMakeDirIfExists bool
vanishOnFirstMakeDir bool
missingPathMakeDir bool
execRequests []RemoteExecRequest
writeFiles []fakeRemoteWriteFile
// snapshots maps snapshotID -> source sandboxID.
snapshots map[string]string
snapshotSeq int
// ptyClosed is set when a fake PTY opened on this client is closed.
ptyClosed atomic.Bool
// terminalOptions records OpenTerminal arguments so tests can see the
// options the manager actually passed through.
terminalOptions []RemoteTerminalOptions
// openTerminalHook, when set, runs instead of opening immediately. It
// sees the context the manager passed, so a test can block the dial
// until that context is cancelled.
openTerminalHook func(context.Context) error
}
func newFakeRemoteClient(provider RemoteProvider) *fakeRemoteClient {
client := &fakeRemoteClient{
provider: provider,
capabilities: RemoteSandboxCapabilities{
SupportsReconnect: true,
SupportsMetadata: true,
SupportsListSandboxes: true,
SupportsFilesystemEnumeration: true,
},
sandboxes: make(map[string]*fakeRemoteRecord),
connectErrs: make(map[string]error),
getErrs: make(map[string]error),
deleteErrs: make(map[string]error),
}
// Cube and E2B issue the inbound token at create. DefaultConfig closes
// public inbound, so a tokenless fake would fail createAndBind the same
// way a real provider that omitted the token does. Tests that want that
// failure must clear trafficAccessToken explicitly.
if provider == RemoteProvider(SandboxTypeCube) || provider == RemoteProvider(SandboxTypeE2B) {
client.trafficAccessToken = "test-inbound-token"
}
return client
}
func TestFakeRemoteClientConnectRestoresRequestedTrafficToken(t *testing.T) {
client := newFakeRemoteClient(RemoteProvider(SandboxTypeCube))
client.trafficAccessToken = "provider-issued-token"
created, err := client.Create(context.Background(), RemoteCreateRequest{})
require.NoError(t, err)
require.Equal(t, "provider-issued-token", InboundTokenOf(created))
reconnected, err := client.Connect(context.Background(), RemoteConnectRequest{
SandboxID: created.ID(),
})
require.NoError(t, err)
require.Empty(t, InboundTokenOf(reconnected))
reconnected, err = client.Connect(context.Background(), RemoteConnectRequest{
SandboxID: created.ID(),
TrafficAccessToken: "restored-token",
})
require.NoError(t, err)
require.Equal(t, "restored-token", InboundTokenOf(reconnected))
}
func (c *fakeRemoteClient) Provider() RemoteProvider { return c.provider }
func (c *fakeRemoteClient) Capabilities() RemoteSandboxCapabilities {
return c.capabilities
}
func (c *fakeRemoteClient) Health(context.Context) error { return nil }
func (c *fakeRemoteClient) Create(
ctx context.Context,
req RemoteCreateRequest,
) (RemoteSandboxHandle, error) {
c.mu.Lock()
c.createCount++
err := c.createErr
hook := c.createHook
c.mu.Unlock()
if err != nil {
return nil, err
}
if hook != nil {
if err := hook(ctx, req); err != nil {
return nil, err
}
}
if err := ctx.Err(); err != nil {
return nil, err
}
c.mu.Lock()
c.nextID++
id := fmt.Sprintf("%s-%d", c.provider, c.nextID)
c.lastCreateRequest = req
c.lastCreatedID = id
record := &fakeRemoteRecord{
id: id,
templateID: req.TemplateID,
state: RemoteStateRunning,
rawState: string(RemoteStateRunning),
metadata: cloneStringMap(req.Metadata),
startedAt: time.Now().UTC(),
}
c.sandboxes[id] = record
handle := c.handle(record, c.trafficAccessToken)
afterCreate := c.afterCreate
c.mu.Unlock()
if afterCreate != nil {
afterCreate(handle)
}
return handle, nil
}
func (c *fakeRemoteClient) Connect(
ctx context.Context,
request RemoteConnectRequest,
) (RemoteSandboxHandle, error) {
if err := ctx.Err(); err != nil {
return nil, err
}
sandboxID := request.SandboxID
c.mu.Lock()
defer c.mu.Unlock()
c.connectIDs = append(c.connectIDs, sandboxID)
c.connects = append(c.connects, request)
if err := c.connectErrs[sandboxID]; err != nil {
return nil, err
}
record := c.sandboxes[sandboxID]
if record == nil || record.state == RemoteStateTerminal {
return nil, NewRemoteError(
c.provider,
"Connect",
RemoteErrorKindNotFound,
"sandbox not found",
nil,
)
}
token := request.TrafficAccessToken
if c.connectTrafficToken != "" {
token = c.connectTrafficToken
} else if token == "" && c.reissuesTokenOnConnect {
token = c.trafficAccessToken
}
return c.handle(record, token), nil
}
func (c *fakeRemoteClient) Get(
ctx context.Context,
sandboxID string,
) (*RemoteSandboxSummary, error) {
if err := ctx.Err(); err != nil {
return nil, err
}
c.mu.Lock()
defer c.mu.Unlock()
c.getIDs = append(c.getIDs, sandboxID)
if err := c.getErrs[sandboxID]; err != nil {
return nil, err
}
record := c.sandboxes[sandboxID]
if record == nil {
return nil, NewRemoteError(
c.provider,
"Get",
RemoteErrorKindNotFound,
"sandbox not found",
nil,
)
}
return c.summary(record), nil
}
func (c *fakeRemoteClient) List(
ctx context.Context,
filter RemoteListFilter,
) ([]RemoteSandboxSummary, error) {
if err := ctx.Err(); err != nil {
return nil, err
}
c.mu.Lock()
defer c.mu.Unlock()
c.listCount++
if c.listErr != nil {
return nil, c.listErr
}
result := make([]RemoteSandboxSummary, 0)
for _, record := range c.sandboxes {
if !metadataContains(record.metadata, filter.Metadata) ||
!stateMatches(record.state, filter.States) {
continue
}
result = append(result, *c.summary(record))
}
return result, nil
}
func (c *fakeRemoteClient) Delete(ctx context.Context, sandboxID string) error {
c.mu.Lock()
hook := c.deleteHook
c.mu.Unlock()
if hook != nil {
if err := hook(ctx, sandboxID); err != nil {
return err
}
}
if err := ctx.Err(); err != nil {
return err
}
c.mu.Lock()
defer c.mu.Unlock()
c.deleteIDs = append(c.deleteIDs, sandboxID)
if err := c.deleteErrs[sandboxID]; err != nil {
return err
}
if _, ok := c.sandboxes[sandboxID]; !ok {
return NewRemoteError(
c.provider,
"Delete",
RemoteErrorKindNotFound,
"sandbox not found",
nil,
)
}
delete(c.sandboxes, sandboxID)
return nil
}
func (c *fakeRemoteClient) Exec(
_ context.Context,
_ RemoteSandboxHandle,
request RemoteExecRequest,
) (*RemoteExecResult, error) {
c.mu.Lock()
c.execRequests = append(c.execRequests, request)
c.mu.Unlock()
if c.execHook != nil {
return c.execHook(request)
}
return &RemoteExecResult{ExitCode: 0}, nil
}
func (c *fakeRemoteClient) WriteFile(
_ context.Context,
_ RemoteSandboxHandle,
path string,
content []byte,
) error {
c.mu.Lock()
c.writeFiles = append(c.writeFiles, fakeRemoteWriteFile{
path: path,
content: append([]byte(nil), content...),
})
c.mu.Unlock()
return nil
}
func (c *fakeRemoteClient) ReadFile(
context.Context,
RemoteSandboxHandle,
string,
) ([]byte, error) {
return nil, nil
}
func (c *fakeRemoteClient) ListDir(
context.Context,
RemoteSandboxHandle,
string,
) ([]RemoteDirEntry, error) {
return nil, nil
}
func (c *fakeRemoteClient) MakeDir(_ context.Context, handle RemoteSandboxHandle, path string) error {
c.mu.Lock()
defer c.mu.Unlock()
if c.missingPathMakeDir {
return NewRemoteError(c.provider, "MakeDir", RemoteErrorKindNotFound, path+" does not exist", nil)
}
if c.vanishOnFirstMakeDir {
c.vanishOnFirstMakeDir = false
if handle != nil {
delete(c.sandboxes, handle.ID())
}
return NewRemoteError(c.provider, "MakeDir", RemoteErrorKindNotFound, "container vanished mid-op", nil)
}
if c.failMakeDirIfExists {
for _, existing := range c.makeDirPaths {
if existing == path {
return NewRemoteError(
c.provider, "MakeDir", RemoteErrorKindInternal,
fmt.Sprintf("failed to make dir %s: directory already exists: %s", path, path),
nil,
)
}
}
}
c.makeDirPaths = append(c.makeDirPaths, path)
return nil
}
func (c *fakeRemoteClient) Remove(context.Context, RemoteSandboxHandle, string) error {
return nil
}
func (c *fakeRemoteClient) Stat(
context.Context,
RemoteSandboxHandle,
string,
) (*RemoteStatEntry, error) {
return nil, nil
}
func (c *fakeRemoteClient) CreateSnapshot(
ctx context.Context, sandboxID string, name string,
) (RemoteSnapshotRef, error) {
c.mu.Lock()
defer c.mu.Unlock()
if c.snapshots == nil {
c.snapshots = map[string]string{}
}
c.snapshotSeq++
id := fmt.Sprintf("snap-%d", c.snapshotSeq)
c.snapshots[id] = sandboxID
names := []string(nil)
if name != "" {
names = []string{name}
}
return RemoteSnapshotRef{ID: id, Names: names}, nil
}
func (c *fakeRemoteClient) DeleteSnapshot(ctx context.Context, snapshotID string) error {
c.mu.Lock()
defer c.mu.Unlock()
delete(c.snapshots, snapshotID) // missing snapshot is success
return nil
}
func (c *fakeRemoteClient) ListSnapshots(
ctx context.Context, sandboxID string,
) ([]RemoteSnapshotRef, error) {
c.mu.Lock()
defer c.mu.Unlock()
var out []RemoteSnapshotRef
for id, src := range c.snapshots {
if sandboxID != "" && src != sandboxID {
continue
}
out = append(out, RemoteSnapshotRef{ID: id})
}
return out, nil
}
func (c *fakeRemoteClient) addSandbox(
id string,
templateID string,
state RemoteSandboxState,
metadata map[string]string,
startedAt time.Time,
) {
c.mu.Lock()
defer c.mu.Unlock()
c.sandboxes[id] = &fakeRemoteRecord{
id: id,
templateID: templateID,
state: state,
rawState: string(state),
metadata: cloneStringMap(metadata),
startedAt: startedAt,
}
}
// addSandboxWithMetadata registers a running sandbox that already carries
// metadata, the way a failed create can leave a duplicate behind.
func (c *fakeRemoteClient) addSandboxWithMetadata(metadata map[string]string) string {
c.mu.Lock()
defer c.mu.Unlock()
c.nextID++
id := fmt.Sprintf("%s-%d", c.provider, c.nextID)
c.sandboxes[id] = &fakeRemoteRecord{
id: id,
state: RemoteStateRunning,
rawState: string(RemoteStateRunning),
metadata: cloneStringMap(metadata),
startedAt: time.Now().UTC(),
}
return id
}
func (c *fakeRemoteClient) counts() (creates, connects, gets, lists, deletes int) {
c.mu.Lock()
defer c.mu.Unlock()
return c.createCount, len(c.connectIDs), len(c.getIDs), c.listCount, len(c.deleteIDs)
}
func (c *fakeRemoteClient) OpenTerminal(
ctx context.Context, _ RemoteSandboxHandle, opts RemoteTerminalOptions,
) (RemoteTerminalSession, error) {
if c.openTerminalHook != nil {
if err := c.openTerminalHook(ctx); err != nil {
return nil, err
}
}
c.mu.Lock()
c.terminalOptions = append(c.terminalOptions, opts)
c.mu.Unlock()
return &fakeRemoteTerminal{client: c}, nil
}
func (c *fakeRemoteClient) lastTerminalOptions() RemoteTerminalOptions {
c.mu.Lock()
defer c.mu.Unlock()
if len(c.terminalOptions) == 0 {
return RemoteTerminalOptions{}
}
return c.terminalOptions[len(c.terminalOptions)-1]
}
func (c *fakeRemoteClient) terminalClosed() bool { return c.ptyClosed.Load() }
// fakeRemoteTerminal is the PTY the shared fake opens. Close records that
// the stream was torn down, which is how a lost admission lease is observed.
type fakeRemoteTerminal struct {
client *fakeRemoteClient
}
func (s *fakeRemoteTerminal) Output() <-chan RemoteTerminalEvent { return nil }
func (s *fakeRemoteTerminal) PID() uint32 { return 1 }
func (s *fakeRemoteTerminal) Write(context.Context, []byte) error { return nil }
func (s *fakeRemoteTerminal) Resize(context.Context, uint32, uint32) error {
return nil
}
func (s *fakeRemoteTerminal) Close() error {
if s.client != nil {
s.client.ptyClosed.Store(true)
}
return nil
}
func (c *fakeRemoteClient) hasSandbox(id string) bool {
c.mu.Lock()
defer c.mu.Unlock()
_, ok := c.sandboxes[id]
return ok
}
func (c *fakeRemoteClient) handle(
record *fakeRemoteRecord,
trafficAccessToken string,
) RemoteSandboxHandle {
if c.omitsInboundTokenCarrier {
return &fakeTokenlessHandle{
id: record.id,
provider: c.provider,
metadata: cloneStringMap(record.metadata),
}
}
return &fakeRemoteHandle{
id: record.id,
provider: c.provider,
metadata: cloneStringMap(record.metadata),
trafficAccessToken: trafficAccessToken,
}
}
func (c *fakeRemoteClient) summary(record *fakeRemoteRecord) *RemoteSandboxSummary {
return &RemoteSandboxSummary{
ID: record.id,
TemplateID: record.templateID,
State: record.state,
RawState: record.rawState,
Metadata: cloneStringMap(record.metadata),
StartedAt: record.startedAt,
}
}
func cloneStringMap(source map[string]string) map[string]string {
if source == nil {
return nil
}
result := make(map[string]string, len(source))
for key, value := range source {
result[key] = value
}
return result
}
func metadataContains(candidate, required map[string]string) bool {
for key, value := range required {
if candidate[key] != value {
return false
}
}
return true
}
func stateMatches(candidate RemoteSandboxState, allowed []RemoteSandboxState) bool {
if len(allowed) == 0 {
return true
}
for _, state := range allowed {
if candidate == state {
return true
}
}
return false
}
var _ RemoteSandboxClient = (*fakeRemoteClient)(nil)
+304
View File
@@ -0,0 +1,304 @@
// Package sandbox: provider-neutral remote Sandbox implementation.
//
// RemoteSandbox is the concrete Sandbox that speaks any RemoteSandboxClient
// backend. It contains no Cube- or E2B-specific logic; every operation is
// expressed against the RemoteSandboxClient contract and a RemoteSandboxHandle.
//
// SessionBoundManager uses it in two shapes:
//
// - Ephemeral: one call to Execute allocates a sandbox, uploads the script,
// runs it, then deletes the sandbox regardless of success. This gives
// stateless-per-call semantics for callers without a SessionID.
// - Persistent (session-bound): SessionBoundManager resolves the session's
// RemoteSandboxHandle through the lifecycle coordinator and hands it to
// RemoteSandbox.ExecuteOnHandle. The handle stays owned by the manager;
// RemoteSandbox never creates or deletes anything in this mode.
package sandbox
import (
"context"
"errors"
"fmt"
"os"
"path"
"path/filepath"
"strings"
"time"
)
// remoteScriptDir is the absolute directory inside every remote sandbox where
// Academy uploads scripts before execution. Kept identical to the historical
// Cube path so existing tenant scripts continue to reference /workspace files.
const remoteScriptDir = "/workspace"
// RemoteSandbox implements Sandbox on top of a RemoteSandboxClient. It is
// intentionally stateless: no local mutexes, no cached handles. Higher layers
// decide whether a call allocates a fresh sandbox or reuses an existing one.
type RemoteSandbox struct {
client RemoteSandboxClient
createRequest RemoteCreateRequest
}
// NewRemoteSandbox builds a stateless RemoteSandbox. createRequest is the
// template used for ephemeral Execute calls. Callers that only use
// ExecuteOnHandle may pass a zero createRequest.
func NewRemoteSandbox(client RemoteSandboxClient, createRequest RemoteCreateRequest) *RemoteSandbox {
return &RemoteSandbox{client: client, createRequest: createRequest}
}
// Type mirrors the underlying provider so callers can gate provider-specific
// behaviour (see agent_service capability registration).
func (s *RemoteSandbox) Type() SandboxType {
if s == nil || s.client == nil {
return SandboxTypeDisabled
}
return s.client.Provider()
}
// IsAvailable probes the provider's control plane. Returns true only when
// Health succeeds within ctx.
func (s *RemoteSandbox) IsAvailable(ctx context.Context) bool {
if s == nil || s.client == nil {
return false
}
return s.client.Health(ctx) == nil
}
// Cleanup is a no-op: RemoteSandbox holds no long-lived state. Session
// cleanup lives in SessionBoundManager, which owns the authoritative binding.
func (s *RemoteSandbox) Cleanup(context.Context) error { return nil }
// Execute allocates a fresh sandbox, runs cfg's script, and always tears the
// sandbox down. It is the ephemeral path used when a caller provides no
// SessionID.
func (s *RemoteSandbox) Execute(ctx context.Context, cfg *ExecuteConfig) (*ExecuteResult, error) {
if s == nil || s.client == nil {
return nil, ErrSandboxDisabled
}
if cfg == nil {
return nil, ErrInvalidScript
}
if s.createRequest.TemplateID == "" {
return nil, errors.New("sandbox: remote sandbox has no template configured")
}
execCtx, cancel := boundedExecuteContext(ctx, cfg)
defer cancel()
handle, err := s.client.Create(execCtx, s.createRequest)
if err != nil {
return nil, fmt.Errorf("remote sandbox: create: %w", err)
}
defer s.disposeEphemeral(ctx, handle)
return s.ExecuteOnHandle(execCtx, handle, cfg)
}
// ExecuteOnHandle runs cfg's script on an existing handle; uploads land in
// /workspace and on-disk scripts run from there.
func (s *RemoteSandbox) ExecuteOnHandle(
ctx context.Context, handle RemoteSandboxHandle, cfg *ExecuteConfig,
) (*ExecuteResult, error) {
return s.ExecuteOnHandleIn(ctx, handle, cfg, SessionWorkspaceRoot, remoteScriptDir)
}
// ExecuteOnHandleIn is ExecuteOnHandle with explicit directories. A shared
// machine passes the session root and a script directory inside it, so two
// sessions uploading run.py never overwrite each other.
func (s *RemoteSandbox) ExecuteOnHandleIn(
ctx context.Context, handle RemoteSandboxHandle, cfg *ExecuteConfig, workDir, scriptDir string,
) (*ExecuteResult, error) {
if s == nil || s.client == nil {
return nil, ErrSandboxDisabled
}
if handle == nil {
return nil, errors.New("sandbox: remote handle is required")
}
if cfg == nil {
return nil, ErrInvalidScript
}
// Scripts already on disk skip upload so the skill venv layout is not
// shadowed. Image paths derive the skill directory; workspace paths
// require an explicit SkillDir so arbitrary files cannot inherit a
// skill interpreter by accident.
if remote := strings.TrimSpace(cfg.RemoteScriptPath); remote != "" {
skillDir, ok := InterpreterSkillDir(remote, cfg.SkillDir)
if !ok {
return nil, ErrInvalidScript
}
command, baseArgs := SkillInterpreterCommand(skillDir, path.Clean(remote))
request := RemoteExecRequest{
Command: command,
Args: append(baseArgs, cfg.Args...),
Stdin: cfg.Stdin,
Env: cfg.Env,
WorkDir: workDir,
User: DefaultSandboxExecUser,
Timeout: effectiveTimeout(cfg, 0),
}
start := time.Now()
execResult, err := s.client.Exec(ctx, handle, request)
return remoteExecuteResult(execResult, err, time.Since(start)), nil
}
content, err := readScriptContent(cfg)
if err != nil {
return nil, err
}
scriptName := filepath.Base(cfg.Script)
if scriptName == "" || scriptName == "." || scriptName == "/" {
return nil, ErrInvalidScript
}
remoteScript := path.Join(scriptDir, scriptName)
if scriptDir != remoteScriptDir {
if err := ignoreExistingDir(s.client.MakeDir(ctx, handle, scriptDir)); err != nil {
return nil, fmt.Errorf("remote sandbox: create script dir %s: %w", scriptDir, err)
}
}
if err := s.client.WriteFile(ctx, handle, remoteScript, content); err != nil {
return nil, fmt.Errorf("remote sandbox: upload script %s: %w", remoteScript, err)
}
timeout := effectiveTimeout(cfg, 0)
request := RemoteExecRequest{
Command: getInterpreter(remoteScript),
Args: append([]string{remoteScript}, cfg.Args...),
Stdin: cfg.Stdin,
Env: cfg.Env,
WorkDir: scriptDir,
User: DefaultSandboxExecUser,
Timeout: timeout,
}
start := time.Now()
execResult, err := s.client.Exec(ctx, handle, request)
duration := time.Since(start)
return remoteExecuteResult(execResult, err, duration), nil
}
// disposeEphemeral deletes the sandbox after an ephemeral Execute completes.
// Errors are logged inside the client's normalization layer; we swallow them
// so the caller always sees the primary result.
func (s *RemoteSandbox) disposeEphemeral(parent context.Context, handle RemoteSandboxHandle) {
if handle == nil || handle.ID() == "" {
return
}
cleanupCtx, cancel := context.WithTimeout(
context.WithoutCancel(parent),
remoteCleanupTimeout,
)
defer cancel()
_ = s.client.Delete(cleanupCtx, handle.ID())
}
// remoteCleanupTimeout bounds the detached delete issued after an ephemeral
// Execute. Matches the manager's session-scoped cleanup budget so behaviour
// stays predictable regardless of which path performs the cleanup.
const remoteCleanupTimeout = 30 * time.Second
// remoteExecuteResult projects RemoteExecResult onto Academy's ExecuteResult.
// It preserves the timeout contract: a timeout returns a killed result with
// exit code -1 and ErrTimeout as Error, never an error return.
func remoteExecuteResult(result *RemoteExecResult, err error, duration time.Duration) *ExecuteResult {
if err != nil {
if IsRemoteInvalidRequest(err) {
return &ExecuteResult{
Duration: duration,
ExitCode: -1,
Error: err.Error(),
}
}
return &ExecuteResult{
Duration: duration,
ExitCode: -1,
Error: err.Error(),
}
}
if result == nil {
return &ExecuteResult{
Duration: duration,
ExitCode: -1,
Error: "sandbox: remote provider returned no result",
}
}
if result.Killed {
return &ExecuteResult{
Stdout: result.Stdout,
Stderr: result.Stderr,
Duration: result.Duration,
Killed: true,
ExitCode: -1,
Error: ErrTimeout.Error(),
}
}
return &ExecuteResult{
Stdout: result.Stdout,
Stderr: result.Stderr,
ExitCode: result.ExitCode,
Duration: result.Duration,
}
}
// getInterpreter picks the interpreter for a script from its extension. The
// remote backends upload the script and then exec this interpreter against
// the uploaded path, so the choice must not depend on anything host-side.
func getInterpreter(scriptName string) string {
switch strings.ToLower(filepath.Ext(scriptName)) {
case ".py":
return "python3"
case ".sh", ".bash":
return "bash"
case ".js", ".mjs", ".cjs":
return "node"
case ".rb":
return "ruby"
case ".pl":
return "perl"
default:
return "sh"
}
}
// readScriptContent resolves the script bytes to upload into the sandbox.
// It prefers cfg.ScriptContent (populated by the security validator) and
// falls back to reading cfg.Script from local disk.
func readScriptContent(cfg *ExecuteConfig) ([]byte, error) {
if cfg.ScriptContent != "" {
return []byte(cfg.ScriptContent), nil
}
if cfg.Script == "" {
return nil, ErrInvalidScript
}
content, err := os.ReadFile(cfg.Script)
if err != nil {
if os.IsNotExist(err) {
return nil, ErrScriptNotFound
}
return nil, fmt.Errorf("remote sandbox: read script: %w", err)
}
return content, nil
}
// boundedExecuteContext returns a derived context with the effective timeout
// applied. It is only used on the ephemeral path; persistent execution runs
// under SessionBoundManager's context (which the lifecycle lock already
// bounds).
func boundedExecuteContext(parent context.Context, cfg *ExecuteConfig) (context.Context, context.CancelFunc) {
timeout := effectiveTimeout(cfg, 0)
if timeout <= 0 {
return parent, func() {}
}
return context.WithTimeout(parent, timeout)
}
func effectiveTimeout(cfg *ExecuteConfig, fallback time.Duration) time.Duration {
if cfg != nil && cfg.Timeout > 0 {
return cfg.Timeout
}
if fallback > 0 {
return fallback
}
return DefaultTimeout
}
+133
View File
@@ -0,0 +1,133 @@
package sandbox
import (
"context"
"testing"
"github.com/stretchr/testify/require"
)
func TestExecuteOnHandleRunsRemoteScriptWithoutUploading(t *testing.T) {
ctx := context.Background()
client := newFakeRemoteClient(SandboxTypeCube)
sb := NewRemoteSandbox(client, RemoteCreateRequest{})
handle, err := client.Create(ctx, RemoteCreateRequest{TemplateID: "tpl"})
require.NoError(t, err)
skillDir := mustSkillDir(t, "sk-1")
_, err = sb.ExecuteOnHandle(ctx, handle, &ExecuteConfig{
RemoteScriptPath: skillDir + "/scripts/run.py",
Args: []string{"--flag"},
})
require.NoError(t, err)
client.mu.Lock()
writes := append([]fakeRemoteWriteFile(nil), client.writeFiles...)
execs := append([]RemoteExecRequest(nil), client.execRequests...)
client.mu.Unlock()
require.Empty(t, writes,
"a script that already lives in the image must not be re-uploaded")
require.Len(t, execs, 1)
last := execs[0]
require.Equal(t, SessionWorkspaceRoot, last.WorkDir)
require.Equal(t, DefaultSandboxExecUser, last.User)
require.Contains(t, last.Args[len(last.Args)-1], "--flag")
require.Contains(t, last.Args[1], skillDir+"/.venv/bin/python")
}
func TestExecuteOnHandleNestedRemoteScriptUsesSkillRootVenv(t *testing.T) {
ctx := context.Background()
client := newFakeRemoteClient(SandboxTypeCube)
sb := NewRemoteSandbox(client, RemoteCreateRequest{})
handle, err := client.Create(ctx, RemoteCreateRequest{TemplateID: "tpl"})
require.NoError(t, err)
skillDir := mustSkillDir(t, "sk-1")
_, err = sb.ExecuteOnHandle(ctx, handle, &ExecuteConfig{
RemoteScriptPath: skillDir + "/scripts/tools/run.py",
})
require.NoError(t, err)
client.mu.Lock()
execs := append([]RemoteExecRequest(nil), client.execRequests...)
client.mu.Unlock()
require.Len(t, execs, 1)
require.Contains(t, execs[0].Args[1], skillDir+"/.venv/bin/python")
}
func TestExecuteOnHandleRejectsRemoteScriptOutsideSkillRoot(t *testing.T) {
ctx := context.Background()
client := newFakeRemoteClient(SandboxTypeCube)
sb := NewRemoteSandbox(client, RemoteCreateRequest{})
handle, err := client.Create(ctx, RemoteCreateRequest{TemplateID: "tpl"})
require.NoError(t, err)
_, err = sb.ExecuteOnHandle(ctx, handle, &ExecuteConfig{
RemoteScriptPath: "/workspace/run.py",
})
require.ErrorIs(t, err, ErrInvalidScript)
client.mu.Lock()
writes := append([]fakeRemoteWriteFile(nil), client.writeFiles...)
execs := append([]RemoteExecRequest(nil), client.execRequests...)
client.mu.Unlock()
require.Empty(t, writes)
require.Empty(t, execs)
}
func TestExecuteOnHandleRunsWorkspaceScriptWithExplicitSkillDir(t *testing.T) {
ctx := context.Background()
client := newFakeRemoteClient(SandboxTypeCube)
sb := NewRemoteSandbox(client, RemoteCreateRequest{})
handle, err := client.Create(ctx, RemoteCreateRequest{TemplateID: "tpl"})
require.NoError(t, err)
skillDir := mustSkillDir(t, "ppt-generator")
_, err = sb.ExecuteOnHandle(ctx, handle, &ExecuteConfig{
RemoteScriptPath: "/workspace/output/generate_rencui_ppt.py",
SkillDir: skillDir,
Args: []string{"--flag"},
})
require.NoError(t, err)
client.mu.Lock()
writes := append([]fakeRemoteWriteFile(nil), client.writeFiles...)
execs := append([]RemoteExecRequest(nil), client.execRequests...)
client.mu.Unlock()
require.Empty(t, writes, "a session workspace script must not be uploaded")
require.Len(t, execs, 1)
require.Equal(t, SessionWorkspaceRoot, execs[0].WorkDir)
require.Contains(t, execs[0].Args[1], skillDir+"/.venv/bin/python")
require.Contains(t, execs[0].Args[1], "/workspace/output/generate_rencui_ppt.py")
require.Contains(t, execs[0].Args[len(execs[0].Args)-1], "--flag")
}
func TestExecuteOnHandleRejectsWorkspaceScriptWithoutSkillDir(t *testing.T) {
ctx := context.Background()
client := newFakeRemoteClient(SandboxTypeCube)
sb := NewRemoteSandbox(client, RemoteCreateRequest{})
handle, err := client.Create(ctx, RemoteCreateRequest{TemplateID: "tpl"})
require.NoError(t, err)
_, err = sb.ExecuteOnHandle(ctx, handle, &ExecuteConfig{
RemoteScriptPath: "/workspace/output/generate_ppt.py",
})
require.ErrorIs(t, err, ErrInvalidScript)
}
func TestExecuteOnHandleRejectsWorkspaceInputEvenWithSkillDir(t *testing.T) {
ctx := context.Background()
client := newFakeRemoteClient(SandboxTypeCube)
sb := NewRemoteSandbox(client, RemoteCreateRequest{})
handle, err := client.Create(ctx, RemoteCreateRequest{TemplateID: "tpl"})
require.NoError(t, err)
_, err = sb.ExecuteOnHandle(ctx, handle, &ExecuteConfig{
RemoteScriptPath: "/workspace/input/upload.py",
SkillDir: mustSkillDir(t, "pdf"),
})
require.ErrorIs(t, err, ErrInvalidScript)
client.mu.Lock()
require.Empty(t, client.execRequests)
client.mu.Unlock()
}
+65
View File
@@ -0,0 +1,65 @@
package sandbox
import (
"context"
"testing"
"github.com/stretchr/testify/require"
)
func TestSnapshotManagerFromDetectsCapability(t *testing.T) {
t.Run("client implementing the interface is returned", func(t *testing.T) {
client := newFakeRemoteClient(SandboxTypeCube)
client.capabilities.SupportsSnapshots = true
mgr, ok := SnapshotManagerFrom(client)
require.True(t, ok)
require.NotNil(t, mgr)
})
t.Run("client without snapshot support is rejected", func(t *testing.T) {
client := &noSnapshotClient{}
mgr, ok := SnapshotManagerFrom(client)
require.False(t, ok)
require.Nil(t, mgr)
})
t.Run("interface without SupportsSnapshots is rejected", func(t *testing.T) {
client := newFakeRemoteClient(SandboxTypeCube)
client.capabilities.SupportsSnapshots = false
mgr, ok := SnapshotManagerFrom(client)
require.False(t, ok, "embedding snapshot methods must not override a false capability flag")
require.Nil(t, mgr)
})
}
func TestFakeSnapshotRoundTrip(t *testing.T) {
ctx := context.Background()
client := newFakeRemoteClient(SandboxTypeCube)
ref, err := client.CreateSnapshot(ctx, "sb-1", "academy-sk-abc-g1")
require.NoError(t, err)
require.NotEmpty(t, ref.ID)
list, err := client.ListSnapshots(ctx, "sb-1")
require.NoError(t, err)
require.Len(t, list, 1)
require.Equal(t, ref.ID, list[0].ID)
// Deleting twice must be idempotent: a missing snapshot is not an error.
require.NoError(t, client.DeleteSnapshot(ctx, ref.ID))
require.NoError(t, client.DeleteSnapshot(ctx, ref.ID))
list, err = client.ListSnapshots(ctx, "sb-1")
require.NoError(t, err)
require.Empty(t, list)
}
// noSnapshotClient implements RemoteSandboxClient without the snapshot methods,
// so SnapshotManagerFrom must reject it.
type noSnapshotClient struct{ RemoteSandboxClient }
+55
View File
@@ -0,0 +1,55 @@
package sandbox
// Runtime tuning has safe built-in defaults. Unlike endpoints, credentials,
// and templates, these values do not identify an external backend.
func applyCubeRuntimeDefaults(cfg *Config) {
if cfg == nil {
return
}
if cfg.CubeSandboxTTL <= 0 {
cfg.CubeSandboxTTL = DefaultCubeSandboxTTL
}
if cfg.CubeHTTPTimeout <= 0 {
cfg.CubeHTTPTimeout = DefaultCubeHTTPTimeout
}
}
func applyDockerRuntimeDefaults(cfg *Config) {
if cfg == nil {
return
}
// The image is deliberately not defaulted here: it is this backend's
// template, and a config that fails to name one must be reported as
// incomplete rather than silently pointed at whatever image the release
// happens to ship.
if cfg.DockerHost == "" {
cfg.DockerHost = DetectLocalDockerHost()
}
if cfg.DockerCPULimit <= 0 {
cfg.DockerCPULimit = DefaultDockerCPULimit
}
if cfg.DockerMemoryBytes <= 0 {
cfg.DockerMemoryBytes = DefaultDockerMemoryLimit
}
if cfg.DockerPidsLimit <= 0 {
cfg.DockerPidsLimit = DefaultDockerPidsLimit
}
if cfg.DockerIdleTTL <= 0 {
cfg.DockerIdleTTL = DefaultDockerIdleTTL
}
if cfg.DockerHTTPTimeout <= 0 {
cfg.DockerHTTPTimeout = DefaultDockerHTTPTimeout
}
}
func applyE2BRuntimeDefaults(cfg *Config) {
if cfg == nil {
return
}
if cfg.E2BSandboxTTL <= 0 {
cfg.E2BSandboxTTL = DefaultE2BSandboxTTL
}
if cfg.E2BHTTPTimeout <= 0 {
cfg.E2BHTTPTimeout = DefaultE2BHTTPTimeout
}
}
+496
View File
@@ -0,0 +1,496 @@
// Package sandbox provides isolated execution environments for running untrusted scripts.
// It supports Docker containers and remote MicroVM backends (CubeSandbox, E2B).
package sandbox
import (
"context"
"errors"
"fmt"
"time"
)
// SandboxType represents the type of sandbox environment
type SandboxType string
const (
// SandboxTypeDocker runs each session in its own long-lived Docker
// container, driven through the Docker Engine API. Like the MicroVM
// backends it keeps session state between executions; unlike them it
// shares the host kernel and lives on a single daemon.
SandboxTypeDocker SandboxType = "docker"
// SandboxTypeCube uses Tencent CubeSandbox (E2B-compatible) MicroVM for isolation.
// Like Docker and E2B it keeps session-scoped persistent sandboxes: multiple
// executions bound to the same SessionID share one instance and preserve
// installed packages, created files, running services, etc.
SandboxTypeCube SandboxType = "cube"
// SandboxTypeE2B uses E2B's hosted MicroVM sandbox service.
SandboxTypeE2B SandboxType = "e2b"
// SandboxTypeHost runs commands on the user's own machine under
// OS-enforced restrictions (macOS Seatbelt, Windows restricted token).
// It is deliberately not named "local": the removed Local backend ran
// bare host processes with no isolation at all, and reusing that name
// would misrepresent this one.
SandboxTypeHost SandboxType = "host"
// SandboxTypeDisabled means script execution is disabled
SandboxTypeDisabled SandboxType = "disabled"
)
// IsNamedSandboxBackendType reports whether raw is a user-facing named sandbox
// backend. Host is absent because it has no session-scoped instance to pin:
// each command is a fresh local process. The same predicate is used by
// resolveSandboxForExecution.
func IsNamedSandboxBackendType(raw string) bool {
switch SandboxType(raw) {
case SandboxTypeCube, SandboxTypeE2B, SandboxTypeDocker:
return true
default:
return false
}
}
// Default configuration values
const (
DefaultTimeout = 60 * time.Second
DefaultMemoryLimit = 256 * 1024 * 1024 // 256MB
DefaultCPULimit = 1.0 // 1 CPU core
// DefaultDockerImage tracks main rather than latest. The latest tag only
// moves when a version is released, so it still carries the image from
// before /workspace and its input/output directories were handed to the
// sandbox account — a sandbox built from it cannot write its own artifact
// directory. Point this back at latest once a release ships that fix.
DefaultDockerImage = "wechatopenai/weknora-sandbox:main"
// DefaultCubeTemplateImage is the same environment with Cube's envd daemon
// baked in (target "cube" of docker/Dockerfile.sandbox).
//
// Cube turns an OCI image into a template directly and gates the build on
// GET :49983/health, which only envd answers. Building a Cube template from
// DefaultDockerImage therefore always fails the probe with "connection
// refused" — E2B gets away with that image because its own builder injects
// envd, and the Docker backend never needs one.
DefaultCubeTemplateImage = "wechatopenai/weknora-sandbox:main-cube"
// DefaultDesktopDockerImage is the XFCE/x11vnc/websockify variant of
// DefaultDockerImage (target "desktop" of docker/Dockerfile.sandbox).
// E2B desktop templates are built from it. The Docker backend does not
// consume this tag yet.
DefaultDesktopDockerImage = "wechatopenai/weknora-sandbox:main-desktop"
// DefaultCubeDesktopTemplateImage is DefaultDesktopDockerImage plus Cube
// envd (target "desktop-cube").
DefaultCubeDesktopTemplateImage = "wechatopenai/weknora-sandbox:main-desktop-cube"
// DesktopWebsockifyPort is websockify inside the sandbox. Academy dials
// it through the provider gateway (Host "{port}-{id}.{domain}"), not by
// publishing the port on the host NIC. x11vnc stays on 127.0.0.1:5900
// with no RFB password; the Basic-auth check lives on websockify.
DesktopWebsockifyPort = 6080
// DesktopWebsockifyPath is websockify's WebSocket endpoint. The image
// hosts no HTML UI, so GET / answers 405 by design.
DesktopWebsockifyPath = "/websockify"
// DesktopStartScript is the idempotent lazy-start entry point baked into
// the desktop images. It is re-run on every desktop connect: that is what
// heals a sandbox after pause/resume.
DesktopStartScript = "/usr/local/bin/start-desktop.sh"
// DesktopSecretPath holds the per-sandbox websockify Basic-auth password.
// It is read by the backend and never sent to the browser.
DesktopSecretPath = "/run/desktop/secret"
// DesktopBasicAuthUser is the fixed username half of that credential.
DesktopBasicAuthUser = "academy"
// The two commands the backend Execs around DesktopStartScript live in
// desktop_scripts.go as embedded .sh files:
// DesktopEnsureCmd and DesktopResetListenersCmd.
// CubeEnvdPort is the port envd listens on inside a Cube sandbox. It carries
// the readiness probe as well as every exec and filesystem call, and the
// data plane addresses sandboxes as "49983-{id}.{domain}".
CubeEnvdPort = 49983
// CubeEnvdHealthPath is the envd endpoint Cube probes to decide whether a
// template build succeeded.
CubeEnvdHealthPath = "/health"
// DefaultCubeAPIURL is retained for SDK tests and explicit local helpers;
// workspace configs must still provide their endpoint.
DefaultCubeAPIURL = "http://127.0.0.1:33000"
// DefaultCubeProxyURL is the default CubeProxy endpoint (HTTP, port 80) used
// to reach the in-sandbox envd via host-header routing.
DefaultCubeProxyURL = "http://127.0.0.1:80"
// DefaultCubeSandboxDomain is the sandbox routing domain configured on
// CubeProxy (matches CUBE_API_SANDBOX_DOMAIN in the Cube deployment).
DefaultCubeSandboxDomain = "cube.app"
// DefaultCubeSandboxTTL is the Cube-side sandbox lifetime hint (in seconds)
// requested at creation; the sandbox is torn down by CubeMaster if the
// client goes silent for longer than this value.
DefaultCubeSandboxTTL = 30 * time.Minute
// DefaultCubeHTTPTimeout bounds a single HTTP call to the CubeAPI
// (excluding user script execution which has its own per-call timeout).
DefaultCubeHTTPTimeout = 30 * time.Second
// DefaultE2BSandboxTTL matches the E2B SDK's built-in default so an
// unset E2BSandboxTTL still yields a valid sandbox lifetime.
DefaultE2BSandboxTTL = 5 * time.Minute
// DefaultE2BHTTPTimeout bounds a single HTTP call to the E2B API.
DefaultE2BHTTPTimeout = 30 * time.Second
// DefaultE2BSandboxDomain is go-e2b's built-in sandbox routing domain.
// Named E2B configs may omit sandbox_domain (config_required.go); envd
// then uses this value, and DialDesktop must too.
DefaultE2BSandboxDomain = "e2b.app"
)
// Common errors
var (
ErrSandboxDisabled = errors.New("sandbox is disabled")
ErrTimeout = errors.New("execution timed out")
ErrScriptNotFound = errors.New("script not found")
ErrInvalidScript = errors.New("invalid script")
ErrExecutionFailed = errors.New("script execution failed")
ErrSecurityViolation = errors.New("security validation failed")
ErrDangerousCommand = errors.New("script contains dangerous command")
ErrArgInjection = errors.New("argument injection detected")
ErrStdinInjection = errors.New("stdin injection detected")
// ErrNoLiveSessionSandbox is returned by lookup-only entry points (the
// interactive terminal) when the session has no currently bound sandbox.
// Unlike Execute, these entry points never provision: creating a sandbox
// needs the agent's config-pin context, which they do not carry.
ErrNoLiveSessionSandbox = errors.New("session has no live sandbox")
// ErrSandboxPaused is returned by lookup-only terminal and desktop
// opens when the session has a bound sandbox that is not confirmed
// running (paused, transitioning, or missing from the provider list).
// Connect / Exec would resume a paused instance and start billing
// again; the UI must get an explicit click first. Distinct from
// ErrNoLiveSessionSandbox, which means there is no binding to resume.
ErrSandboxPaused = errors.New("session sandbox is paused")
// ErrSandboxStopped is ErrSandboxPaused for a backend that never pauses
// (Docker): a bound sandbox that is not running is either a stopped
// container, which a resume restarts with its files intact, or one the
// idle sweep already deleted, which a resume replaces with a fresh one.
// The UI cannot promise "wake it up" there. It wraps ErrSandboxPaused, so
// every caller that only distinguishes "needs a confirmed click" keeps
// working unchanged.
ErrSandboxStopped = fmt.Errorf("%w: sandbox is stopped or was reclaimed", ErrSandboxPaused)
// ErrSessionRewindLocked means another rewind already holds the session.
ErrSessionRewindLocked = errors.New("sandbox: session rewind already in progress")
// ErrSessionTurnActive means a chat turn already holds the session lease,
// so rewind must not take the exclusive lock or reset the workspace.
ErrSessionTurnActive = errors.New("sandbox: session turn is active")
// ErrSessionWorkActive means background work is still live in the session,
// so rewind must not take the exclusive lock or reset the workspace.
ErrSessionWorkActive = errors.New("sandbox: session has live background work")
// ErrTerminalUnsupported is returned when the active backend cannot
// stream PTYs (Docker, a disabled manager). Distinct from
// ErrNoLiveSessionSandbox: the session may well have a live sandbox,
// it just cannot host an interactive terminal.
ErrTerminalUnsupported = errors.New("sandbox backend does not support interactive terminals")
)
// Sandbox defines the interface for isolated script execution
type Sandbox interface {
// Execute runs a script in an isolated environment
Execute(ctx context.Context, config *ExecuteConfig) (*ExecuteResult, error)
// Cleanup releases sandbox resources
Cleanup(ctx context.Context) error
// Type returns the sandbox type
Type() SandboxType
// IsAvailable checks if the sandbox is available for use
IsAvailable(ctx context.Context) bool
}
// Manager provides a unified interface for sandbox operations
// It handles sandbox selection and fallback logic
type Manager interface {
// Execute runs a script using the configured sandbox
Execute(ctx context.Context, config *ExecuteConfig) (*ExecuteResult, error)
// Cleanup releases all sandbox resources
Cleanup(ctx context.Context) error
// GetSandbox returns the active sandbox
GetSandbox() Sandbox
// GetType returns the current sandbox type
GetType() SandboxType
}
// ExecuteConfig contains configuration for script execution
type ExecuteConfig struct {
// Script is the absolute path to the script file
Script string
// Args are command-line arguments to pass to the script
Args []string
// WorkDir is the working directory for script execution
WorkDir string
// Timeout is the maximum execution time (0 = use default)
Timeout time.Duration
// Env is additional environment variables
Env map[string]string
// AllowNetwork enables network access (Docker only)
AllowNetwork bool
// MemoryLimit is the maximum memory in bytes (Docker only)
MemoryLimit int64
// CPULimit is the maximum CPU cores (Docker only)
CPULimit float64
// ReadOnlyRootfs makes the root filesystem read-only (Docker only)
ReadOnlyRootfs bool
// Stdin provides input to the script
Stdin string
// SkipValidation skips security validation (use with caution, only for trusted scripts)
SkipValidation bool
// ScriptContent is the script content for validation (optional, will be read from file if not provided)
ScriptContent string
// SessionID scopes the execution to a per-session persistent sandbox.
// Honoured by Cube, E2B and Docker. When empty, those backends fall back
// to an ephemeral (one-shot) sandbox created and torn down inside the
// single Execute call.
SessionID string
// RemoteScriptPath is an absolute path to a script that already exists
// inside the sandbox. When set, the executor skips the upload step and
// runs it in place. Accepted locations:
// - an installed skill file under SkillsImageRoot (bundle vetted at install)
// - a session-writable file under /workspace, not under /workspace/input,
// which also requires SkillDir so the skill's interpreter is used
RemoteScriptPath string
// SkillDir is the installed skill directory whose venv/node_modules
// should run RemoteScriptPath. Required when RemoteScriptPath sits under
// /workspace. Image-skill paths derive the directory from the script and
// ignore this field.
SkillDir string
}
// ExecuteResult contains the result of script execution
type ExecuteResult struct {
// Stdout is the standard output from the script
Stdout string
// Stderr is the standard error from the script
Stderr string
// ExitCode is the process exit code
ExitCode int
// Duration is the actual execution time
Duration time.Duration
// Killed indicates if the process was killed (e.g., timeout)
Killed bool
// Error contains any execution error
Error string
}
// IsSuccess returns true if the script executed successfully
func (r *ExecuteResult) IsSuccess() bool {
return r.ExitCode == 0 && !r.Killed && r.Error == ""
}
// Config holds sandbox manager configuration
type Config struct {
// Type is the preferred sandbox type
Type SandboxType
// DefaultTimeout is the default execution timeout
DefaultTimeout time.Duration
// TerminalIdleDisconnect is how long an open interactive terminal may
// go without input or PTY output before the WebSocket is closed. Zero
// is treated as DefaultTerminalIdleDisconnect at use time.
TerminalIdleDisconnect time.Duration
// DesktopEnabled mirrors TenantSandboxConfig.DesktopEnabled: this
// config's template is a desktop image. The desktop endpoint refuses
// with DESKTOP_UNSUPPORTED when it is false, before touching a sandbox.
DesktopEnabled bool
// AllowPrivateEndpoints is the per-workspace outbound policy for this
// connection. Link-local addresses are blocked regardless.
AllowPrivateEndpoints bool
// DockerImage is the image every sandbox container is created from. It
// plays the same role as a Cube/E2B template ID.
DockerImage string
// DockerHost is the daemon endpoint, in DOCKER_HOST form
// ("unix:///var/run/docker.sock", "tcp://10.0.0.5:2376"). Empty uses
// DefaultDockerHost.
DockerHost string
// DockerTLSCertPath is a directory on the Academy host holding
// ca.pem / cert.pem / key.pem. Required for a TCP daemon; unix sockets
// do not use TLS.
DockerTLSCertPath string
// DockerCPULimit / DockerMemoryBytes / DockerPidsLimit cap one sandbox
// container. Zero uses the built-in defaults.
DockerCPULimit float64
DockerMemoryBytes int64
DockerPidsLimit int64
// DockerNetworkMode is the Docker network every sandbox joins: "bridge" or
// "none". host, container: and named networks are rejected (see
// ValidateDockerNetworkMode). Empty means "bridge"; skills that install
// packages need egress, so a sandbox is not isolated from the network by
// default.
DockerNetworkMode string
// DockerRuntime selects an alternative OCI runtime, e.g. "runsc" for
// gVisor. Empty uses the daemon's default runtime.
DockerRuntime string
// DockerIdleTTL is how long a container may go without executing anything
// before the idle sweep reclaims it. Zero uses DefaultDockerIdleTTL.
DockerIdleTTL time.Duration
// DockerHTTPTimeout bounds each Engine API call. Zero uses the default.
DockerHTTPTimeout time.Duration
// MaxMemory is the maximum memory limit in bytes
MaxMemory int64
// MaxCPU is the maximum CPU cores
MaxCPU float64
// EnvVars are additional environment variables to set for the sandbox.
EnvVars map[string]string
// Network is the outbound/inbound policy every sandbox built from this
// config is created with. DefaultConfig and ResolveEffectiveConfig fully
// specify it: leaving it nil would let adapters use provider defaults,
// which expose inbound traffic publicly.
Network RemoteNetworkPolicy
// CubeAPIURL is the base URL of the CubeAPI (E2B-compatible) endpoint.
// Only used when Type == SandboxTypeCube. Example: "http://127.0.0.1:33000".
CubeAPIURL string
// CubeProxyURL is the base URL of the CubeProxy HTTP endpoint through which
// in-sandbox envd traffic is routed via host-header rewriting. Example:
// "http://127.0.0.1:80".
CubeProxyURL string
// CubeSandboxDomain matches CubeAPI's CUBE_API_SANDBOX_DOMAIN. It is used to
// build the Host header "<port>-<sandboxID>.<domain>" that CubeProxy relies
// on to route requests into the correct MicroVM.
CubeSandboxDomain string
// CubeAPIKey is the API key sent via X-API-Key. Leave empty when the Cube
// deployment does not enforce authentication.
CubeAPIKey string
// CubeTemplate is the default template ID used when creating sandboxes.
CubeTemplate string
// CubeSandboxTTL is the Cube-side lifetime hint (passed as `timeout` when
// creating a sandbox). CubeMaster will reap the MicroVM if the client stops
// touching it for longer than this duration.
CubeSandboxTTL time.Duration
// CubeHTTPTimeout bounds each HTTP call to CubeAPI. Zero uses the default.
CubeHTTPTimeout time.Duration
// CubeDNSServers are nameserver IPs included when Academy builds the
// standard Cube template. Empty omits the field so Cubelet uses its
// cluster default.
CubeDNSServers []string
// E2BAPIKey is the E2B API key sent via X-API-Key. Only used when
// Type == SandboxTypeE2B.
E2BAPIKey string
// E2BAPIURL is the E2B control-plane endpoint. Empty defaults to
E2BAPIURL string
// E2BSandboxDomain is the domain envd traffic is routed through, e.g.
// "e2b.app". Empty defaults to the SDK's built-in.
E2BSandboxDomain string
// E2BProxyURL is the data-plane gateway that fronts envd for self-hosted
// E2B-compatible control planes. Empty keeps the SDK's behaviour of
// resolving the sandbox authority through DNS over TLS, which is what E2B
// Cloud expects. See types.E2BSandboxConfig.ProxyURL.
E2BProxyURL string
// E2BTemplate is the E2B template ID used at sandbox creation.
E2BTemplate string
// TemplateFromSnapshot reports that the boot target (E2BTemplate or
// CubeTemplate) was replaced by a skill snapshot. The env baked into that
// snapshot must not be sent again: Aliyun Agent Sandbox returns 400
// "creating from a snapshot does not allow envVars or function config
// overrides".
TemplateFromSnapshot bool
// E2BSandboxTTL is the E2B-side idle timeout hint.
E2BSandboxTTL time.Duration
// E2BHTTPTimeout bounds ordinary E2B HTTP calls, including response bodies.
// Command streams use their execution timeout instead.
E2BHTTPTimeout time.Duration
}
// DefaultConfig returns a default sandbox configuration.
//
// It deliberately carries no Cube or E2B endpoint, credential or template:
// those belong to a named workspace config. Presetting them here once meant an
// incomplete workspace config could silently dial localhost.
func DefaultConfig() *Config {
return &Config{
Type: SandboxTypeDisabled,
DefaultTimeout: DefaultTimeout,
DockerImage: DefaultDockerImage,
MaxMemory: DefaultMemoryLimit,
MaxCPU: DefaultCPULimit,
CubeSandboxTTL: DefaultCubeSandboxTTL,
CubeHTTPTimeout: DefaultCubeHTTPTimeout,
Network: resolveNetworkPolicy(nil),
}
}
// ValidateConfig validates sandbox configuration
func ValidateConfig(config *Config) error {
if config == nil {
return errors.New("config is nil")
}
switch config.Type {
case SandboxTypeDocker, SandboxTypeCube, SandboxTypeE2B, SandboxTypeHost, SandboxTypeDisabled:
// Valid types
default:
return errors.New("invalid sandbox type")
}
if config.DefaultTimeout < 0 {
return errors.New("timeout cannot be negative")
}
if config.MaxMemory < 0 {
return errors.New("memory limit cannot be negative")
}
if config.MaxCPU < 0 {
return errors.New("CPU limit cannot be negative")
}
return nil
}
+162
View File
@@ -0,0 +1,162 @@
package sandbox
import (
"context"
"testing"
"time"
"github.com/stretchr/testify/require"
)
func TestDefaultConfig(t *testing.T) {
config := DefaultConfig()
if config.Type != SandboxTypeDisabled {
t.Errorf("Expected default type to be disabled, got %s", config.Type)
}
if config.DefaultTimeout != DefaultTimeout {
t.Errorf("Expected default timeout %v, got %v", DefaultTimeout, config.DefaultTimeout)
}
}
func TestValidateConfig(t *testing.T) {
tests := []struct {
name string
config *Config
wantErr bool
}{
{
name: "nil config",
config: nil,
wantErr: true,
},
{
name: "valid disabled config",
config: &Config{
Type: SandboxTypeDisabled,
DefaultTimeout: 30 * time.Second,
},
wantErr: false,
},
{
name: "invalid type",
config: &Config{
Type: "invalid",
},
wantErr: true,
},
{
name: "removed local type",
config: &Config{
Type: "local",
},
wantErr: true,
},
{
name: "negative timeout",
config: &Config{
Type: SandboxTypeDisabled,
DefaultTimeout: -1 * time.Second,
},
wantErr: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
err := ValidateConfig(tt.config)
if (err != nil) != tt.wantErr {
t.Errorf("ValidateConfig() error = %v, wantErr %v", err, tt.wantErr)
}
})
}
}
func TestNewManager(t *testing.T) {
config := DefaultConfig()
config.Type = SandboxTypeDisabled
manager, err := NewManager(config)
if err != nil {
t.Fatalf("Failed to create manager: %v", err)
}
if manager.GetType() != SandboxTypeDisabled {
t.Errorf("Expected type disabled, got %s", manager.GetType())
}
}
func TestNewDisabledManager(t *testing.T) {
manager := NewDisabledManager()
if manager.GetType() != SandboxTypeDisabled {
t.Errorf("Expected type disabled, got %s", manager.GetType())
}
ctx := context.Background()
_, err := manager.Execute(ctx, &ExecuteConfig{
Script: "/some/script.sh",
})
if err != ErrSandboxDisabled {
t.Errorf("Expected ErrSandboxDisabled, got %v", err)
}
}
func TestIsNamedSandboxBackendType(t *testing.T) {
for _, tc := range []struct {
raw string
want bool
}{
{"cube", true},
{"e2b", true},
{"docker", true},
{"local", false},
{"disabled", false},
{"", false},
} {
if got := IsNamedSandboxBackendType(tc.raw); got != tc.want {
t.Fatalf("IsNamedSandboxBackendType(%q) = %v, want %v", tc.raw, got, tc.want)
}
}
}
func TestExecuteResultHelpers(t *testing.T) {
successResult := &ExecuteResult{
ExitCode: 0,
Stdout: "output",
}
if !successResult.IsSuccess() {
t.Error("Expected IsSuccess() to return true for exit code 0")
}
failResult := &ExecuteResult{
ExitCode: 1,
Stderr: "error",
}
if failResult.IsSuccess() {
t.Error("Expected IsSuccess() to return false for exit code 1")
}
killedResult := &ExecuteResult{
ExitCode: 0,
Killed: true,
}
if killedResult.IsSuccess() {
t.Error("Expected IsSuccess() to return false when killed")
}
}
// host has no remote instance, so the session must never be pinned to it:
// a pin would record a binding that artifact collection and teardown then try
// to resolve against a sandbox that never existed. Keeping host out of the
// named-backend set is what delivers that today — see the task notes before
// changing this expectation.
func TestHostIsNotANamedBackend(t *testing.T) {
require.False(t, IsNamedSandboxBackendType(string(SandboxTypeHost)))
}
func TestValidateConfigAcceptsHost(t *testing.T) {
require.NoError(t, ValidateConfig(&Config{Type: SandboxTypeHost}))
}
+771
View File
@@ -0,0 +1,771 @@
package sandbox
import (
"context"
"errors"
"fmt"
"strings"
"sync"
"time"
"unicode"
"academy/internal/background"
"academy/internal/sandbox/allocation"
"academy/internal/sandbox/workspace"
)
// SessionSandboxBindingVersion is the schema of a per-session machine binding.
const SessionSandboxBindingVersion = 1
// UserSandboxBindingVersion is the schema of a shared user machine binding.
const UserSandboxBindingVersion = 2
// SessionSandboxKey addresses persistent sandbox state.
//
// With User zero it is today's per-session key. With User set and SessionID
// empty it addresses a shared user machine (binding, lifecycle lock); with
// both set it addresses one session's leases on that machine (turn lease,
// rewind lock).
type SessionSandboxKey struct {
TenantID uint64
SessionID string
User allocation.UserMachine
}
// IsUserScoped reports a key on a shared user machine.
func (k SessionSandboxKey) IsUserScoped() bool { return k.User.OwnerID != "" }
// IsUserMachine reports the machine-level key of a shared user machine.
func (k SessionSandboxKey) IsUserMachine() bool { return k.IsUserScoped() && k.SessionID == "" }
// Machine is the key the binding and the lifecycle lock live under.
func (k SessionSandboxKey) Machine() SessionSandboxKey {
if k.IsUserScoped() {
return SessionSandboxKey{TenantID: k.TenantID, User: k.User}
}
return k
}
// String identifies the key in logs without the owner id.
func (k SessionSandboxKey) String() string {
if k.IsUserScoped() {
if k.SessionID == "" {
return fmt.Sprintf("user-machine(tenant=%d,config=%d/%s)",
k.TenantID, k.User.ConfigTenantID, k.User.ConfigID)
}
return fmt.Sprintf("user-session(tenant=%d,session=%s)", k.TenantID, k.SessionID)
}
return fmt.Sprintf("session(tenant=%d,session=%s)", k.TenantID, k.SessionID)
}
// Validate rejects keys that cannot address sandbox state.
func (k SessionSandboxKey) Validate() error {
if k.IsUserScoped() {
if err := k.User.Validate(); err != nil {
return fmt.Errorf("sandbox binding: %w", err)
}
if k.TenantID != k.User.OwnerTenantID {
return errors.New("sandbox binding tenant must be the user machine's owner tenant")
}
if k.SessionID != "" && !workspace.IsCanonicalUUID(k.SessionID) {
return errors.New("sandbox binding session on a user machine must be a canonical UUID")
}
return nil
}
if k.TenantID == 0 || strings.TrimSpace(k.SessionID) == "" {
return errors.New("sandbox binding requires tenant and session")
}
if strings.ContainsAny(k.SessionID, "{}") {
return errors.New("sandbox binding session must not contain braces")
}
for _, r := range k.SessionID {
if unicode.IsControl(r) {
return errors.New("sandbox binding session must not contain control characters")
}
}
return nil
}
// SessionSandboxBinding records the remote sandbox assigned to a session.
type SessionSandboxBinding struct {
Version int `json:"version"`
Provider RemoteProvider `json:"provider,omitempty"`
TenantID uint64 `json:"tenant_id"`
SessionID string `json:"session_id"`
SandboxID string `json:"sandbox_id"`
TemplateID string `json:"template_id"`
CreatedAt time.Time `json:"created_at"`
// ConfigID is the sandbox config the sandbox was created from. It is what
// makes "every sandbox of this config" answerable from the binding store:
// the sandbox itself carries the same value in provider metadata, but a
// staleness mark must not depend on the provider being reachable.
//
// Bindings written before this field existed carry an empty value. They are
// deliberately still valid — refusing them would break every live session
// on upgrade — and simply match no config until they are rebuilt.
ConfigID string `json:"config_id,omitempty"`
// StaleAt marks a binding whose sandbox boots an image the config has
// since replaced. The sandbox keeps serving until the session's next
// resolve, which destroys and recreates it; see InvalidateByConfig.
StaleAt *time.Time `json:"stale_at,omitempty"`
// TrafficAccessToken is the per-sandbox inbound credential issued at
// create time for Cube and E2B. Inbound is always credential-required.
//
// Cube may reissue it on Connect after pause/resume; the lifecycle writes
// the fresh value back here. E2B issues it only at create. Either way this
// binding is the only place the credential survives a Academy restart.
//
// Stored as-is. It is a bearer credential, so the Redis instance holding
// these bindings must be access-controlled — it already holds the
// session-to-sandbox ownership anyway. Never log the binding payload.
//
// Empty for Docker (no such credential) and for bindings written before
// this field existed; both are valid.
TrafficAccessToken string `json:"traffic_access_token,omitempty"`
// OwnerID and ConfigTenantID complete a user machine's identity
// (version 2). Empty on per-session bindings.
OwnerID string `json:"owner_id,omitempty"`
ConfigTenantID uint64 `json:"config_tenant_id,omitempty"`
}
// Validate checks a binding against its schema and authoritative key.
func (b SessionSandboxBinding) Validate(key SessionSandboxKey) error {
if err := key.Validate(); err != nil {
return err
}
if key.IsUserScoped() {
if !key.IsUserMachine() {
return errors.New("sandbox binding must be addressed by its user machine key")
}
if b.Version != UserSandboxBindingVersion {
return fmt.Errorf("user sandbox binding version must be %d, got %d", UserSandboxBindingVersion, b.Version)
}
if b.TenantID != key.TenantID || b.SessionID != "" ||
b.OwnerID != key.User.OwnerID ||
b.ConfigTenantID != key.User.ConfigTenantID ||
b.ConfigID != key.User.ConfigID {
return errors.New("sandbox binding identity does not match its key")
}
} else {
if b.Version != SessionSandboxBindingVersion {
return fmt.Errorf("sandbox binding version must be %d, got %d", SessionSandboxBindingVersion, b.Version)
}
if b.TenantID != key.TenantID || b.SessionID != key.SessionID {
return errors.New("sandbox binding identity does not match its key")
}
}
if !isRemoteProvider(b.Provider) {
return fmt.Errorf("unsupported sandbox binding provider %q", b.Provider)
}
if strings.TrimSpace(b.SandboxID) == "" {
return errors.New("sandbox binding requires sandbox ID")
}
if strings.TrimSpace(b.TemplateID) == "" {
return errors.New("sandbox binding requires template ID")
}
if b.CreatedAt.IsZero() {
return errors.New("sandbox binding requires creation time")
}
return nil
}
// SessionSandboxBindingStore persists bindings and serializes lifecycle
// transitions. Implementations must use create-if-absent and compare-delete
// semantics.
type SessionSandboxBindingStore interface {
Get(context.Context, SessionSandboxKey) (*SessionSandboxBinding, error)
Create(context.Context, SessionSandboxKey, SessionSandboxBinding) (bool, error)
DeleteIfMatch(
context.Context,
SessionSandboxKey,
RemoteProvider,
string,
) (bool, error)
// ReplaceTrafficTokenIfMatch writes token onto the binding only while it
// still names expected's provider and sandbox. It patches that one field
// so a concurrent stale-mark cannot be wiped. Empty token is a no-op.
ReplaceTrafficTokenIfMatch(
ctx context.Context,
key SessionSandboxKey,
expected SessionSandboxBinding,
token string,
) (bool, error)
// WithLifecycleLock passes fn a request context carrying a separate
// ownership context. The ownership context survives caller cancellation
// but is canceled when exclusive lock ownership is lost.
WithLifecycleLock(context.Context, SessionSandboxKey, func(context.Context) error) error
// InvalidateByConfig marks every binding of one workspace's sandbox config
// stale and reports how many it marked. Already-marked bindings are not
// counted again.
InvalidateByConfig(ctx context.Context, tenantID uint64, configID string) (int, error)
}
// sessionTurnLeaseStore is the optional turn-lease half of a binding store.
// A resolve that sees a stale binding consults it so an in-flight chat turn
// keeps its sandbox, and only the first resolve of the next turn rebuilds.
type sessionTurnLeaseStore interface {
BeginTurn(ctx context.Context, key SessionSandboxKey) error
EndTurn(ctx context.Context, key SessionSandboxKey) error
TurnState(ctx context.Context, key SessionSandboxKey) (active, rebuildOnce bool, err error)
ConsumeTurnRebuild(ctx context.Context, key SessionSandboxKey) error
}
// bindingInvalidateLockTimeout bounds the wait for ONE session's lifecycle
// lock while marking. The caller runs inside the per-config install lock, so a
// single session that happens to be creating a sandbox right now must cost only
// its own mark rather than everyone else's.
const bindingInvalidateLockTimeout = 2 * time.Second
// bindingInvalidateMarkTimeout bounds the marking itself, once the lock is
// held. It is deliberately separate from the wait: sharing one budget would
// leave a mark that waited most of bindingInvalidateLockTimeout for the lock
// with milliseconds for its read plus compare-and-set, failing with a deadline
// error indistinguishable from a Redis fault.
const bindingInvalidateMarkTimeout = 3 * time.Second
// tenantBindingScanner is the store-specific half of InvalidateByConfig:
// enumerating one workspace's bindings and writing the mark. The serialisation
// and matching rules are shared, in invalidateBindingsByConfig.
type tenantBindingScanner interface {
SessionSandboxBindingStore
// listTenantBindingKeys returns the keys of every binding the store holds
// for tenantID. Bindings that disappear before they are marked are
// expected, not an error.
listTenantBindingKeys(ctx context.Context, tenantID uint64) ([]SessionSandboxKey, error)
// markBindingStale sets StaleAt only while the binding still names
// expected's provider and sandbox ID, and reports whether it wrote.
markBindingStale(
ctx context.Context,
key SessionSandboxKey,
expected SessionSandboxBinding,
staleAt time.Time,
) (bool, error)
}
// invalidateBindingsByConfig marks one config's bindings stale, one session at
// a time under that session's lifecycle lock.
//
// The lock is what makes the mark reliable: resolve reads the binding, decides
// whether to replace the sandbox, and rebinds all inside it, so marking outside
// would silently lose against a resolve running at the same moment. The mark
// itself is only ever an added field — the binding is never deleted here — so a
// concurrent resolve can lose a mark but never a sandbox.
//
// One session that cannot be marked does not stop the others: the image pointer
// has already moved by the time this runs, and an unmarked session serves the
// previous image until it ends, which is strictly better than leaving the rest
// of the workspace unmarked too. The failures are still returned so the caller
// can say which sessions are affected.
func invalidateBindingsByConfig(
ctx context.Context,
store tenantBindingScanner,
tenantID uint64,
configID string,
) (int, error) {
if tenantID == 0 {
return 0, errors.New("sandbox binding invalidation requires a tenant")
}
keys, err := store.listTenantBindingKeys(ctx, tenantID)
if err != nil {
return 0, err
}
return markBindingKeysStale(ctx, store, keys, configID)
}
// markBindingKeysStale marks every listed binding of configID stale, one key
// at a time under that key's lifecycle lock. Shared with the user machines
// the manager enumerates from the allocation registry.
func markBindingKeysStale(
ctx context.Context, store tenantBindingScanner, keys []SessionSandboxKey, configID string,
) (int, error) {
wanted := NormalizeConfigID(configID)
marked := 0
var failures []error
for _, key := range keys {
if err := ctx.Err(); err != nil {
failures = append(failures, err)
break
}
// The cap applies to acquiring the lock only: the timer is stopped once
// fn runs, and the work below gets a budget of its own. Cancelling
// waitCtx is how the wait is abandoned, so the timer cannot simply be
// a deadline on the context fn is given.
waitCtx, cancel := context.WithCancel(ctx)
acquireTimer := time.AfterFunc(bindingInvalidateLockTimeout, cancel)
err := store.WithLifecycleLock(waitCtx, key, func(lockCtx context.Context) error {
// A false Stop means the cap fired as the lock was granted; then
// lockCtx is already cancelled and the calls below fail, which is
// the same outcome as losing the wait.
acquireTimer.Stop()
markCtx, cancelMark := context.WithTimeout(lockCtx, bindingInvalidateMarkTimeout)
defer cancelMark()
binding, err := store.Get(markCtx, key)
if err != nil || binding == nil {
return err
}
if binding.ConfigID != wanted || binding.StaleAt != nil {
return nil
}
wrote, err := store.markBindingStale(
markCtx, key, *binding, time.Now().UTC(),
)
if err != nil {
return err
}
if wrote {
marked++
}
return nil
})
acquireTimer.Stop()
cancel()
if err != nil {
failures = append(failures, fmt.Errorf("mark %s stale: %w", key, err))
}
}
return marked, errors.Join(failures...)
}
type lifecycleOwnershipContextKey struct{}
func withLifecycleOwnershipContext(
ctx context.Context,
ownershipCtx context.Context,
) context.Context {
return context.WithValue(ctx, lifecycleOwnershipContextKey{}, ownershipCtx)
}
func lifecycleOwnershipContext(ctx context.Context) context.Context {
if ownershipCtx, ok := ctx.Value(lifecycleOwnershipContextKey{}).(context.Context); ok {
return ownershipCtx
}
// Unknown store implementations fail safe by retaining request/lock
// cancellation rather than detaching destructive cleanup.
return ctx
}
type memoryLifecycleLock struct {
semaphore chan struct{}
users int
}
type memoryTurnLease struct {
refs int
rebuildOnce bool
}
// MemorySessionSandboxBindingStore is a process-local implementation intended
// for tests and explicitly configured single-process deployments.
type MemorySessionSandboxBindingStore struct {
mu sync.Mutex
bindings map[SessionSandboxKey]SessionSandboxBinding
locks map[SessionSandboxKey]*memoryLifecycleLock
turns map[SessionSandboxKey]*memoryTurnLease
rewinds map[SessionSandboxKey]struct{}
activity *background.MemoryActivityRegistry
}
// NewMemorySessionSandboxBindingStore creates an empty in-memory store.
func NewMemorySessionSandboxBindingStore() *MemorySessionSandboxBindingStore {
return &MemorySessionSandboxBindingStore{
bindings: make(map[SessionSandboxKey]SessionSandboxBinding),
locks: make(map[SessionSandboxKey]*memoryLifecycleLock),
turns: make(map[SessionSandboxKey]*memoryTurnLease),
rewinds: make(map[SessionSandboxKey]struct{}),
activity: background.NewMemoryActivityRegistry(nil),
}
}
// Get returns the current binding, or nil when the session is unbound.
func (s *MemorySessionSandboxBindingStore) Get(
ctx context.Context,
key SessionSandboxKey,
) (*SessionSandboxBinding, error) {
if err := key.Validate(); err != nil {
return nil, err
}
if err := ctx.Err(); err != nil {
return nil, err
}
s.mu.Lock()
defer s.mu.Unlock()
binding, ok := s.bindings[key.Machine()]
if !ok {
return nil, nil
}
result := binding
if err := result.Validate(key); err != nil {
return nil, fmt.Errorf("validate sandbox binding: %w", err)
}
return &result, nil
}
// Create stores a validated current-schema binding only if key is unbound.
func (s *MemorySessionSandboxBindingStore) Create(
ctx context.Context,
key SessionSandboxKey,
binding SessionSandboxBinding,
) (bool, error) {
if err := binding.Validate(key); err != nil {
return false, err
}
if err := ctx.Err(); err != nil {
return false, err
}
s.mu.Lock()
defer s.mu.Unlock()
machine := key.Machine()
if _, exists := s.bindings[machine]; exists {
return false, nil
}
s.bindings[machine] = binding
return true, nil
}
// DeleteIfMatch deletes only the expected provider and sandbox ID.
func (s *MemorySessionSandboxBindingStore) DeleteIfMatch(
ctx context.Context,
key SessionSandboxKey,
provider RemoteProvider,
sandboxID string,
) (bool, error) {
if err := validateBindingMatch(key, provider, sandboxID); err != nil {
return false, err
}
if err := ctx.Err(); err != nil {
return false, err
}
s.mu.Lock()
defer s.mu.Unlock()
machine := key.Machine()
binding, exists := s.bindings[machine]
if !exists || binding.Provider != provider || binding.SandboxID != sandboxID {
return false, nil
}
delete(s.bindings, machine)
return true, nil
}
// ReplaceTrafficTokenIfMatch patches the inbound credential without disturbing
// the rest of the binding, including a concurrent StaleAt mark.
func (s *MemorySessionSandboxBindingStore) ReplaceTrafficTokenIfMatch(
ctx context.Context,
key SessionSandboxKey,
expected SessionSandboxBinding,
token string,
) (bool, error) {
if err := validateBindingMatch(key, expected.Provider, expected.SandboxID); err != nil {
return false, err
}
if token == "" {
return false, nil
}
if err := ctx.Err(); err != nil {
return false, err
}
s.mu.Lock()
defer s.mu.Unlock()
machine := key.Machine()
binding, exists := s.bindings[machine]
if !exists ||
binding.Provider != expected.Provider ||
binding.SandboxID != expected.SandboxID {
return false, nil
}
if binding.TrafficAccessToken == token {
return false, nil
}
binding.TrafficAccessToken = token
s.bindings[machine] = binding
return true, nil
}
// InvalidateByConfig marks this process's bindings of one config stale.
func (s *MemorySessionSandboxBindingStore) InvalidateByConfig(
ctx context.Context,
tenantID uint64,
configID string,
) (int, error) {
return invalidateBindingsByConfig(ctx, s, tenantID, configID)
}
func (s *MemorySessionSandboxBindingStore) listTenantBindingKeys(
ctx context.Context,
tenantID uint64,
) ([]SessionSandboxKey, error) {
if err := ctx.Err(); err != nil {
return nil, err
}
s.mu.Lock()
defer s.mu.Unlock()
var keys []SessionSandboxKey
for key := range s.bindings {
if key.TenantID == tenantID && !key.IsUserScoped() {
keys = append(keys, key)
}
}
return keys, nil
}
func (s *MemorySessionSandboxBindingStore) markBindingStale(
ctx context.Context,
key SessionSandboxKey,
expected SessionSandboxBinding,
staleAt time.Time,
) (bool, error) {
if err := ctx.Err(); err != nil {
return false, err
}
s.mu.Lock()
defer s.mu.Unlock()
machine := key.Machine()
binding, exists := s.bindings[machine]
if !exists ||
binding.Provider != expected.Provider ||
binding.SandboxID != expected.SandboxID {
return false, nil
}
marked := staleAt
binding.StaleAt = &marked
s.bindings[machine] = binding
return true, nil
}
// WithLifecycleLock runs fn while holding the process-local lock for key.Machine().
func (s *MemorySessionSandboxBindingStore) WithLifecycleLock(
ctx context.Context,
key SessionSandboxKey,
fn func(context.Context) error,
) error {
if err := key.Validate(); err != nil {
return err
}
if fn == nil {
return errors.New("sandbox lifecycle lock callback is required")
}
machine := key.Machine()
s.mu.Lock()
lock := s.locks[machine]
if lock == nil {
lock = &memoryLifecycleLock{semaphore: make(chan struct{}, 1)}
s.locks[machine] = lock
}
lock.users++
s.mu.Unlock()
select {
case lock.semaphore <- struct{}{}:
case <-ctx.Done():
s.dropMemoryLifecycleLockUser(machine, lock)
return ctx.Err()
}
defer func() {
<-lock.semaphore
s.dropMemoryLifecycleLockUser(machine, lock)
}()
if err := ctx.Err(); err != nil {
return err
}
return fn(withLifecycleOwnershipContext(ctx, context.WithoutCancel(ctx)))
}
func (s *MemorySessionSandboxBindingStore) dropMemoryLifecycleLockUser(
key SessionSandboxKey,
lock *memoryLifecycleLock,
) {
s.mu.Lock()
defer s.mu.Unlock()
lock.users--
if lock.users == 0 {
delete(s.locks, key)
}
}
func validateBindingMatch(
key SessionSandboxKey,
provider RemoteProvider,
sandboxID string,
) error {
if err := key.Validate(); err != nil {
return err
}
if !isRemoteProvider(provider) {
return fmt.Errorf("unsupported sandbox binding provider %q", provider)
}
if strings.TrimSpace(sandboxID) == "" {
return errors.New("sandbox binding match requires sandbox ID")
}
return nil
}
// BeginTurn opens a chat-turn lease. The first increment of a session's
// refcount allows the next resolve to rebuild a stale sandbox.
func (s *MemorySessionSandboxBindingStore) BeginTurn(
ctx context.Context,
key SessionSandboxKey,
) error {
if err := key.Validate(); err != nil {
return err
}
if err := ctx.Err(); err != nil {
return err
}
s.mu.Lock()
defer s.mu.Unlock()
if _, held := s.rewinds[key]; held {
return ErrSessionRewindLocked
}
lease := s.turns[key]
if lease == nil {
lease = &memoryTurnLease{}
s.turns[key] = lease
}
if lease.refs == 0 {
lease.rebuildOnce = !s.hasSessionActivityLocked(ctx, key)
}
lease.refs++
return nil
}
// EndTurn releases one chat-turn lease. The last release drops the lease so
// a later resolve may rebuild a stale sandbox immediately.
func (s *MemorySessionSandboxBindingStore) EndTurn(
_ context.Context,
key SessionSandboxKey,
) error {
if err := key.Validate(); err != nil {
return err
}
s.mu.Lock()
defer s.mu.Unlock()
lease := s.turns[key]
if lease == nil {
return nil
}
lease.refs--
if lease.refs <= 0 {
delete(s.turns, key)
}
return nil
}
// TryLockRewind takes a process-local exclusive rewind lock for key.
func (s *MemorySessionSandboxBindingStore) TryLockRewind(
ctx context.Context,
key SessionSandboxKey,
) (func(), error) {
if err := key.Validate(); err != nil {
return nil, err
}
if err := ctx.Err(); err != nil {
return nil, err
}
s.mu.Lock()
defer s.mu.Unlock()
if s.rewinds == nil {
s.rewinds = make(map[SessionSandboxKey]struct{})
}
if lease := s.turns[key]; lease != nil && lease.refs > 0 {
return nil, ErrSessionTurnActive
}
if s.hasSessionActivityLocked(ctx, key) {
return nil, ErrSessionWorkActive
}
if _, held := s.rewinds[key]; held {
return nil, ErrSessionRewindLocked
}
s.rewinds[key] = struct{}{}
return func() {
s.mu.Lock()
delete(s.rewinds, key)
s.mu.Unlock()
}, nil
}
// HasRewindLock reports whether rewind currently holds key.
func (s *MemorySessionSandboxBindingStore) HasRewindLock(
ctx context.Context,
key SessionSandboxKey,
) (bool, error) {
if err := key.Validate(); err != nil {
return false, err
}
if err := ctx.Err(); err != nil {
return false, err
}
s.mu.Lock()
defer s.mu.Unlock()
_, held := s.rewinds[key]
return held, nil
}
// TurnState reports whether a chat turn is open and whether its first
// resolve may still rebuild a stale sandbox.
func (s *MemorySessionSandboxBindingStore) TurnState(
ctx context.Context,
key SessionSandboxKey,
) (bool, bool, error) {
if err := key.Validate(); err != nil {
return false, false, err
}
if err := ctx.Err(); err != nil {
return false, false, err
}
s.mu.Lock()
defer s.mu.Unlock()
if s.hasSessionActivityLocked(ctx, key) {
return true, false, nil
}
lease := s.turns[key]
if lease == nil || lease.refs <= 0 {
return false, false, nil
}
return true, lease.rebuildOnce, nil
}
// ConsumeTurnRebuild spends the one rebuild allowed for the current turn.
func (s *MemorySessionSandboxBindingStore) ConsumeTurnRebuild(
ctx context.Context,
key SessionSandboxKey,
) error {
if err := key.Validate(); err != nil {
return err
}
if err := ctx.Err(); err != nil {
return err
}
s.mu.Lock()
defer s.mu.Unlock()
if lease := s.turns[key]; lease != nil {
lease.rebuildOnce = false
}
return nil
}
var (
_ tenantBindingScanner = (*MemorySessionSandboxBindingStore)(nil)
_ sessionTurnLeaseStore = (*MemorySessionSandboxBindingStore)(nil)
)
func isRemoteProvider(provider RemoteProvider) bool {
switch provider {
case SandboxTypeCube, SandboxTypeE2B, SandboxTypeDocker:
return true
default:
return false
}
}
+683
View File
@@ -0,0 +1,683 @@
package sandbox
import (
"context"
"encoding/json"
"errors"
"fmt"
"strings"
"sync"
"time"
"unicode"
"github.com/redis/go-redis/v9"
"academy/internal/common/redislock"
)
const (
redisLifecycleLockLease = 60 * time.Second
redisLifecycleLockRenewInterval = 20 * time.Second
sessionRewindLockTTL = 2 * time.Minute
sessionRewindLockRenewInterval = 40 * time.Second
)
var deleteBindingIfMatchScript = redis.NewScript(`
local raw = redis.call('GET', KEYS[1])
if not raw then return 0 end
local value = cjson.decode(raw)
local provider = value['provider']
if provider == ARGV[1] and value['sandbox_id'] == ARGV[2] then
return redis.call('DEL', KEYS[1])
end
return 0
`)
var markBindingStaleIfMatchScript = redis.NewScript(`
local raw = redis.call('GET', KEYS[1])
if not raw then return 0 end
local value = cjson.decode(raw)
if value['provider'] ~= ARGV[1] or value['sandbox_id'] ~= ARGV[2] then
return 0
end
redis.call('SET', KEYS[1], ARGV[3])
return 1
`)
// Patches only traffic_access_token so a concurrent stale-mark cannot be
// overwritten by a full-document replace. ARGV[3] is the new token.
//
// The field is rewritten in the stored JSON text rather than via
// cjson.encode of the whole object: Redis's cjson turns integers into
// x.0, and encoding/json then refuses those into uint64 (tenant_id).
var replaceTrafficTokenIfMatchScript = redis.NewScript(`
local raw = redis.call('GET', KEYS[1])
if not raw then return 0 end
local value = cjson.decode(raw)
if value['provider'] ~= ARGV[1] or value['sandbox_id'] ~= ARGV[2] then
return 0
end
if value['traffic_access_token'] == ARGV[3] then
return 0
end
local encoded = string.gsub(cjson.encode(ARGV[3]), '%%', '%%%%')
local updated, n = string.gsub(raw, '"traffic_access_token"%s*:%s*".-"', '"traffic_access_token":'..encoded, 1)
if n == 0 then
updated, n = string.gsub(raw, '}(%s*)$', ',"traffic_access_token":'..encoded..'}%1', 1)
if n == 0 then
return 0
end
end
redis.call('SET', KEYS[1], updated)
return 1
`)
// sessionTurnLeaseTTL bounds a leaked turn if EndSessionTurn never runs
// (process crash). After it expires the next resolve may rebuild a stale
// image, which is what we want once no turn is actually using the sandbox.
const sessionTurnLeaseTTL = 30 * time.Minute
// KEYS[1] turn lease, KEYS[2] rewind lock, KEYS[3] background activity.
// ARGV[1] TTL ms. A turn that opens while background work is live does not
// arm its one rebuild: replacing the sandbox would destroy that work.
var beginTurnScript = redis.NewScript(activityLiveCountLua + `
if redis.call('EXISTS', KEYS[2]) == 1 then
return redis.error_reply('ERR_SESSION_REWIND_LOCKED')
end
local refs = redis.call('HINCRBY', KEYS[1], 'refs', 1)
if refs == 1 then
if live_count(KEYS[3], now_ms()) > 0 then
redis.call('HSET', KEYS[1], 'rebuild', '0')
else
redis.call('HSET', KEYS[1], 'rebuild', '1')
end
end
redis.call('PEXPIRE', KEYS[1], ARGV[1])
return refs
`)
// KEYS[1] turn lease, KEYS[2] background activity. ARGV[1] turn TTL ms.
// Returns {refs, rebuild, live background items}.
var turnStateScript = redis.NewScript(activityLiveCountLua + `
local live = live_count(KEYS[2], now_ms())
local refs = 0
local rebuild = '0'
if redis.call('EXISTS', KEYS[1]) == 1 then
redis.call('PEXPIRE', KEYS[1], ARGV[1])
refs = tonumber(redis.call('HGET', KEYS[1], 'refs') or '0') or 0
rebuild = redis.call('HGET', KEYS[1], 'rebuild') or '0'
end
return {refs, rebuild, live}
`)
// KEYS[1] turn lease, KEYS[2] rewind lock, KEYS[3] background activity.
// ARGV[1] owner token, ARGV[2] TTL ms.
var tryLockRewindScript = redis.NewScript(activityLiveCountLua + `
if redis.call('EXISTS', KEYS[1]) == 1 then
return redis.error_reply('ERR_SESSION_TURN_ACTIVE')
end
if live_count(KEYS[3], now_ms()) > 0 then
return redis.error_reply('ERR_SESSION_WORK_ACTIVE')
end
if redis.call('EXISTS', KEYS[2]) == 1 then
return 0
end
redis.call('SET', KEYS[2], ARGV[1], 'PX', ARGV[2])
return 1
`)
var endTurnScript = redis.NewScript(`
if redis.call('EXISTS', KEYS[1]) == 0 then return 0 end
local refs = redis.call('HINCRBY', KEYS[1], 'refs', -1)
if refs <= 0 then
redis.call('DEL', KEYS[1])
return 0
end
return refs
`)
var consumeTurnRebuildScript = redis.NewScript(`
if redis.call('EXISTS', KEYS[1]) == 0 then return 0 end
redis.call('HSET', KEYS[1], 'rebuild', '0')
redis.call('PEXPIRE', KEYS[1], ARGV[1])
return 1
`)
// redisBindingScanCount is the SCAN batch size. Bindings are one small key per
// live session, so a workspace's whole set is normally a single batch.
const redisBindingScanCount = 200
// RedisSessionSandboxBindingStore is the authoritative distributed store for
// persistent remote-session bindings.
type RedisSessionSandboxBindingStore struct {
client redis.UniversalClient
namespace string
lockLease time.Duration
lockRenewInterval time.Duration
rewindLockTTL time.Duration
rewindLockRenew time.Duration
rewindRenewer func(ctx context.Context, key, token string, lease time.Duration) (bool, error)
}
// NewRedisSessionSandboxBindingStore creates a fail-closed Redis store.
func NewRedisSessionSandboxBindingStore(
client redis.UniversalClient,
namespace string,
) (*RedisSessionSandboxBindingStore, error) {
if client == nil {
return nil, errors.New("sandbox binding Redis client is required")
}
namespace = strings.TrimSpace(namespace)
if err := validateRedisNamespace(namespace); err != nil {
return nil, err
}
return &RedisSessionSandboxBindingStore{
client: client,
namespace: namespace,
lockLease: redisLifecycleLockLease,
lockRenewInterval: redisLifecycleLockRenewInterval,
rewindLockTTL: sessionRewindLockTTL,
rewindLockRenew: sessionRewindLockRenewInterval,
}, nil
}
// Get returns the current binding, or nil when the session is unbound.
func (s *RedisSessionSandboxBindingStore) Get(
ctx context.Context,
key SessionSandboxKey,
) (*SessionSandboxBinding, error) {
if err := key.Validate(); err != nil {
return nil, err
}
raw, err := s.client.Get(ctx, s.bindingKey(key)).Bytes()
if errors.Is(err, redis.Nil) {
return nil, nil
}
if err != nil {
return nil, fmt.Errorf("get sandbox binding: %w", err)
}
var binding SessionSandboxBinding
if err := json.Unmarshal(raw, &binding); err != nil {
return nil, fmt.Errorf("decode sandbox binding: %w", err)
}
if err := binding.Validate(key); err != nil {
return nil, fmt.Errorf("validate sandbox binding: %w", err)
}
return &binding, nil
}
// Create stores a validated current-schema binding with SET NX and no
// expiration.
func (s *RedisSessionSandboxBindingStore) Create(
ctx context.Context,
key SessionSandboxKey,
binding SessionSandboxBinding,
) (bool, error) {
if err := binding.Validate(key); err != nil {
return false, err
}
raw, err := json.Marshal(binding)
if err != nil {
return false, fmt.Errorf("encode sandbox binding: %w", err)
}
created, err := s.client.SetNX(ctx, s.bindingKey(key), raw, 0).Result()
if err != nil {
return false, fmt.Errorf("create sandbox binding: %w", err)
}
return created, nil
}
// DeleteIfMatch atomically deletes only the expected provider and sandbox ID.
func (s *RedisSessionSandboxBindingStore) DeleteIfMatch(
ctx context.Context,
key SessionSandboxKey,
provider RemoteProvider,
sandboxID string,
) (bool, error) {
if err := validateBindingMatch(key, provider, sandboxID); err != nil {
return false, err
}
deleted, err := deleteBindingIfMatchScript.Run(
ctx,
s.client,
[]string{s.bindingKey(key)},
string(provider),
sandboxID,
).Int64()
if err != nil {
return false, fmt.Errorf("delete sandbox binding: %w", err)
}
return deleted != 0, nil
}
// ReplaceTrafficTokenIfMatch patches the inbound credential only while the
// stored binding still names expected's provider and sandbox.
func (s *RedisSessionSandboxBindingStore) ReplaceTrafficTokenIfMatch(
ctx context.Context,
key SessionSandboxKey,
expected SessionSandboxBinding,
token string,
) (bool, error) {
if err := validateBindingMatch(key, expected.Provider, expected.SandboxID); err != nil {
return false, err
}
if token == "" {
return false, nil
}
wrote, err := replaceTrafficTokenIfMatchScript.Run(
ctx,
s.client,
[]string{s.bindingKey(key)},
string(expected.Provider),
expected.SandboxID,
token,
).Int64()
if err != nil {
return false, fmt.Errorf("replace sandbox inbound token: %w", err)
}
return wrote != 0, nil
}
// WithLifecycleLock serializes create, recover, replace, and delete transitions
// across all Academy processes sharing Redis.
func (s *RedisSessionSandboxBindingStore) WithLifecycleLock(
ctx context.Context,
key SessionSandboxKey,
fn func(context.Context) error,
) error {
if err := key.Validate(); err != nil {
return err
}
if fn == nil {
return errors.New("sandbox lifecycle lock callback is required")
}
return redislock.WithRenewableLock(
ctx,
s.client,
s.lockKey(key),
s.lockLease,
s.lockRenewInterval,
func(lockCtx context.Context) error {
return fn(withLifecycleOwnershipContext(
lockCtx,
redislock.OwnershipContext(lockCtx),
))
},
)
}
// InvalidateByConfig marks every binding of one workspace's config stale.
func (s *RedisSessionSandboxBindingStore) InvalidateByConfig(
ctx context.Context,
tenantID uint64,
configID string,
) (int, error) {
return invalidateBindingsByConfig(ctx, s, tenantID, configID)
}
// listTenantBindingKeys SCANs the workspace's binding keys.
//
// SCAN rather than a maintained index: the index would be a second key that
// every create and delete has to keep in step across processes, and a drifted
// index silently under-reports exactly when it matters. The cost is bounded
// because the pattern is anchored on the workspace's own prefix.
//
// A single-node Redis (what the container wires) answers this completely. On a
// Redis Cluster, SCAN reaches one node, so bindings living on the others would
// go unmarked and their sessions would keep the previous image until they end.
func (s *RedisSessionSandboxBindingStore) listTenantBindingKeys(
ctx context.Context,
tenantID uint64,
) ([]SessionSandboxKey, error) {
prefix := fmt.Sprintf(
"academy:sandbox:session:{%s:%d:", s.namespace, tenantID,
)
const suffix = "}:binding"
pattern := escapeRedisGlob(prefix) + "*" + suffix
var keys []SessionSandboxKey
var cursor uint64
for {
batch, next, err := s.client.Scan(ctx, cursor, pattern, redisBindingScanCount).Result()
if err != nil {
return nil, fmt.Errorf("scan sandbox bindings: %w", err)
}
for _, raw := range batch {
sessionID := strings.TrimSuffix(strings.TrimPrefix(raw, prefix), suffix)
key := SessionSandboxKey{TenantID: tenantID, SessionID: sessionID}
if key.Validate() != nil {
continue
}
keys = append(keys, key)
}
if next == 0 {
return keys, nil
}
cursor = next
}
}
// markBindingStale writes the marked binding back only while the stored one
// still names the same sandbox.
func (s *RedisSessionSandboxBindingStore) markBindingStale(
ctx context.Context,
key SessionSandboxKey,
expected SessionSandboxBinding,
staleAt time.Time,
) (bool, error) {
if err := validateBindingMatch(key, expected.Provider, expected.SandboxID); err != nil {
return false, err
}
marked := expected
marked.StaleAt = &staleAt
payload, err := json.Marshal(marked)
if err != nil {
return false, fmt.Errorf("encode stale sandbox binding: %w", err)
}
wrote, err := markBindingStaleIfMatchScript.Run(
ctx,
s.client,
[]string{s.bindingKey(key)},
string(expected.Provider),
expected.SandboxID,
payload,
).Int64()
if err != nil {
return false, fmt.Errorf("mark sandbox binding stale: %w", err)
}
return wrote != 0, nil
}
// escapeRedisGlob quotes the characters SCAN's MATCH treats as wildcards. The
// namespace is operator-supplied and only screened for braces and control
// characters, so a namespace containing "*" would otherwise widen the pattern
// past the workspace it is meant to anchor.
func escapeRedisGlob(literal string) string {
var out strings.Builder
out.Grow(len(literal))
for _, r := range literal {
switch r {
case '\\', '*', '?', '[', ']', '^':
out.WriteByte('\\')
}
out.WriteRune(r)
}
return out.String()
}
// BeginTurn opens a chat-turn lease. The first increment of a session's
// refcount allows the next resolve to rebuild a stale sandbox.
func (s *RedisSessionSandboxBindingStore) BeginTurn(
ctx context.Context,
key SessionSandboxKey,
) error {
if err := key.Validate(); err != nil {
return err
}
ttlMS := sessionTurnLeaseTTL.Milliseconds()
if ttlMS <= 0 {
ttlMS = (30 * time.Minute).Milliseconds()
}
keys := []string{s.turnKey(key), s.rewindKey(key), s.activityKey(key)}
if err := beginTurnScript.Run(ctx, s.client, keys, ttlMS).Err(); err != nil {
if isRewindLockedRedisErr(err) {
return ErrSessionRewindLocked
}
return fmt.Errorf("begin sandbox turn lease: %w", err)
}
return nil
}
// EndTurn releases one chat-turn lease. The last release drops the lease so
// a later resolve may rebuild a stale sandbox immediately.
func (s *RedisSessionSandboxBindingStore) EndTurn(
ctx context.Context,
key SessionSandboxKey,
) error {
if err := key.Validate(); err != nil {
return err
}
if err := endTurnScript.Run(ctx, s.client, []string{s.turnKey(key)}).Err(); err != nil {
return fmt.Errorf("end sandbox turn lease: %w", err)
}
return nil
}
// TurnState reports whether a chat turn is open and whether its first
// resolve may still rebuild a stale sandbox. Live background work counts as an
// open turn that may not rebuild: it runs outside any turn, and a resolve that
// replaced the sandbox under it would destroy it.
func (s *RedisSessionSandboxBindingStore) TurnState(
ctx context.Context,
key SessionSandboxKey,
) (bool, bool, error) {
if err := key.Validate(); err != nil {
return false, false, err
}
values, err := turnStateScript.Run(
ctx, s.client, []string{s.turnKey(key), s.activityKey(key)}, sessionTurnLeaseTTL.Milliseconds(),
).Slice()
if err != nil {
return false, false, fmt.Errorf("read sandbox turn lease: %w", err)
}
if len(values) != 3 {
return false, false, fmt.Errorf("read sandbox turn lease: unexpected reply %v", values)
}
refs, _ := values[0].(int64)
rebuild, _ := values[1].(string)
live, _ := values[2].(int64)
if live > 0 {
return true, false, nil
}
if refs <= 0 {
return false, false, nil
}
return true, rebuild == "1", nil
}
// ConsumeTurnRebuild spends the one rebuild allowed for the current turn.
func (s *RedisSessionSandboxBindingStore) ConsumeTurnRebuild(
ctx context.Context,
key SessionSandboxKey,
) error {
if err := key.Validate(); err != nil {
return err
}
if err := consumeTurnRebuildScript.Run(
ctx, s.client, []string{s.turnKey(key)}, sessionTurnLeaseTTL.Milliseconds(),
).Err(); err != nil {
return fmt.Errorf("consume sandbox turn rebuild: %w", err)
}
return nil
}
func (s *RedisSessionSandboxBindingStore) turnKey(key SessionSandboxKey) string {
if key.IsUserScoped() {
return s.keyBase(key) + ":session:" + key.SessionID + ":turn"
}
return s.keyBase(key) + ":turn"
}
func (s *RedisSessionSandboxBindingStore) rewindKey(key SessionSandboxKey) string {
if key.IsUserScoped() {
return s.keyBase(key) + ":session:" + key.SessionID + ":rewind"
}
return s.keyBase(key) + ":rewind"
}
// TryLockRewind takes a distributed exclusive rewind lock for key.
// The lock fails if a chat-turn lease already exists, and is renewed until
// the returned unlock runs so a slow reset+cleanup cannot expire it.
func (s *RedisSessionSandboxBindingStore) TryLockRewind(
ctx context.Context,
key SessionSandboxKey,
) (func(), error) {
if err := key.Validate(); err != nil {
return nil, err
}
token, err := redislock.NewToken()
if err != nil {
return nil, err
}
lease := s.rewindLease()
ttlMS := lease.Milliseconds()
if ttlMS <= 0 {
ttlMS = sessionRewindLockTTL.Milliseconds()
}
acquired, err := tryLockRewindScript.Run(
ctx, s.client, []string{s.turnKey(key), s.rewindKey(key), s.activityKey(key)}, token, ttlMS,
).Int64()
if err != nil {
if isTurnActiveRedisErr(err) {
return nil, ErrSessionTurnActive
}
if isWorkActiveRedisErr(err) {
return nil, ErrSessionWorkActive
}
return nil, fmt.Errorf("lock session rewind: %w", err)
}
if acquired == 0 {
return nil, ErrSessionRewindLocked
}
stop := make(chan struct{})
done := make(chan struct{})
go s.renewRewindLock(stop, done, s.rewindKey(key), token, lease)
var once sync.Once
return func() {
once.Do(func() {
close(stop)
<-done
relCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Second)
defer cancel()
_, _ = redislock.Release(relCtx, s.client, s.rewindKey(key), token)
})
}, nil
}
// HasRewindLock reports whether rewind currently holds key.
func (s *RedisSessionSandboxBindingStore) HasRewindLock(
ctx context.Context,
key SessionSandboxKey,
) (bool, error) {
if err := key.Validate(); err != nil {
return false, err
}
n, err := s.client.Exists(ctx, s.rewindKey(key)).Result()
if err != nil {
return false, fmt.Errorf("read session rewind lock: %w", err)
}
return n > 0, nil
}
func isRewindLockedRedisErr(err error) bool {
return err != nil && strings.Contains(err.Error(), "ERR_SESSION_REWIND_LOCKED")
}
func isTurnActiveRedisErr(err error) bool {
return err != nil && strings.Contains(err.Error(), "ERR_SESSION_TURN_ACTIVE")
}
func isWorkActiveRedisErr(err error) bool {
return err != nil && strings.Contains(err.Error(), "ERR_SESSION_WORK_ACTIVE")
}
func (s *RedisSessionSandboxBindingStore) rewindLease() time.Duration {
if s != nil && s.rewindLockTTL > 0 {
return s.rewindLockTTL
}
return sessionRewindLockTTL
}
func (s *RedisSessionSandboxBindingStore) rewindRenewInterval() time.Duration {
if s != nil && s.rewindLockRenew > 0 {
return s.rewindLockRenew
}
return sessionRewindLockRenewInterval
}
func (s *RedisSessionSandboxBindingStore) renewRewind(
ctx context.Context, key, token string, lease time.Duration,
) (bool, error) {
if s != nil && s.rewindRenewer != nil {
return s.rewindRenewer(ctx, key, token, lease)
}
return redislock.Renew(ctx, s.client, key, token, lease)
}
func (s *RedisSessionSandboxBindingStore) renewRewindLock(
stop <-chan struct{}, done chan<- struct{}, key, token string, lease time.Duration,
) {
defer close(done)
interval := s.rewindRenewInterval()
if interval <= 0 || interval >= lease {
interval = lease / 3
}
if interval <= 0 {
return
}
ticker := time.NewTicker(interval)
defer ticker.Stop()
for {
select {
case <-stop:
return
case <-ticker.C:
renewed, err := s.renewRewind(context.Background(), key, token, lease)
if err == nil && renewed {
continue
}
// A blip talking to Redis, or a lost lease, must not kill the
// renew loop: git reset can still be running, and the 2m TTL
// would otherwise expire under it. Re-acquire on both, so the
// original unlock token still matches a key that vanished — an
// errored renew is exactly the case where the key may have
// expired underneath us, and sitting the tick out is what lets
// a short outage hand the session to a second rewind.
_, _ = redislock.TryAcquire(
context.Background(), s.client, key, token, lease,
)
}
}
}
// keyBase is the hash-tagged prefix of every key of one machine. User keys
// carry the allocation digest, which already includes the namespace.
func (s *RedisSessionSandboxBindingStore) keyBase(key SessionSandboxKey) string {
if key.IsUserScoped() {
return "academy:sandbox:user:{" + key.User.Digest(s.namespace) + "}"
}
return "academy:sandbox:session:{" + s.hashTag(key) + "}"
}
func (s *RedisSessionSandboxBindingStore) bindingKey(key SessionSandboxKey) string {
return s.keyBase(key.Machine()) + ":binding"
}
func (s *RedisSessionSandboxBindingStore) lockKey(key SessionSandboxKey) string {
// Keep the historical suffix used by the saved multi-node Cube
// implementation so rolling upgrades serialize on the same lock.
return s.keyBase(key.Machine()) + ":create-lock"
}
func (s *RedisSessionSandboxBindingStore) hashTag(key SessionSandboxKey) string {
return fmt.Sprintf("%s:%d:%s", s.namespace, key.TenantID, key.SessionID)
}
var (
_ tenantBindingScanner = (*RedisSessionSandboxBindingStore)(nil)
_ sessionTurnLeaseStore = (*RedisSessionSandboxBindingStore)(nil)
)
func validateRedisNamespace(namespace string) error {
if strings.ContainsAny(namespace, "{}") {
return errors.New("ACADEMY_REDIS_NAMESPACE must not contain braces")
}
for _, r := range namespace {
if unicode.IsControl(r) {
return errors.New("ACADEMY_REDIS_NAMESPACE must not contain control characters")
}
}
return nil
}
@@ -0,0 +1,87 @@
package sandbox
import (
"context"
"testing"
"time"
"academy/internal/types/interfaces"
"github.com/stretchr/testify/require"
)
// addLiveActivity registers one background item for key through the real
// Redis registry, so the turn-lease scripts read exactly what features write.
func addLiveActivity(t *testing.T, store *RedisSessionSandboxBindingStore, key SessionSandboxKey, lease time.Duration) {
t.Helper()
reg := NewRedisActivityRegistry(store)
ref := interfaces.SessionRef{TenantID: key.TenantID, SessionID: key.SessionID}
require.NoError(t, reg.Add(context.Background(), ref, interfaces.BackgroundActivity{
ID: "sj_1", Kind: "shell_job", Title: "build", StartedAt: time.Now(),
}, lease, 0))
}
func TestRedisTurnStateCountsLiveBackgroundWorkAsActiveWithoutRebuild(t *testing.T) {
store, _, mini := newRedisBindingTestStore(t)
ctx := context.Background()
key := SessionSandboxKey{TenantID: 42, SessionID: "session-bg"}
now := time.Date(2026, 10, 15, 10, 0, 0, 0, time.UTC)
mini.SetTime(now)
addLiveActivity(t, store, key, 30*time.Second)
active, rebuildOnce, err := store.TurnState(ctx, key)
require.NoError(t, err)
require.True(t, active, "live background work must keep a turn-less resolve from rebuilding")
require.False(t, rebuildOnce)
mini.SetTime(now.Add(31 * time.Second))
active, rebuildOnce, err = store.TurnState(ctx, key)
require.NoError(t, err)
require.False(t, active, "an expired lease no longer protects the sandbox")
require.False(t, rebuildOnce)
}
func TestRedisBeginTurnDoesNotArmRebuildWhileBackgroundWorkIsLive(t *testing.T) {
store, _, mini := newRedisBindingTestStore(t)
ctx := context.Background()
key := SessionSandboxKey{TenantID: 42, SessionID: "session-bg-turn"}
now := time.Date(2026, 10, 15, 10, 0, 0, 0, time.UTC)
mini.SetTime(now)
addLiveActivity(t, store, key, 30*time.Second)
require.NoError(t, store.BeginTurn(ctx, key))
active, rebuildOnce, err := store.TurnState(ctx, key)
require.NoError(t, err)
require.True(t, active)
require.False(t, rebuildOnce)
// The work ends mid-turn. The turn still must not rebuild: its first
// resolve already ran against this sandbox.
mini.SetTime(now.Add(31 * time.Second))
active, rebuildOnce, err = store.TurnState(ctx, key)
require.NoError(t, err)
require.True(t, active)
require.False(t, rebuildOnce)
require.NoError(t, store.EndTurn(ctx, key))
}
func TestRedisTryLockRewindFailsWhileBackgroundWorkIsLive(t *testing.T) {
store, _, mini := newRedisBindingTestStore(t)
ctx := context.Background()
key := SessionSandboxKey{TenantID: 42, SessionID: "session-bg-rewind"}
now := time.Date(2026, 10, 15, 10, 0, 0, 0, time.UTC)
mini.SetTime(now)
addLiveActivity(t, store, key, 30*time.Second)
_, err := store.TryLockRewind(ctx, key)
require.ErrorIs(t, err, ErrSessionWorkActive)
held, err := store.HasRewindLock(ctx, key)
require.NoError(t, err)
require.False(t, held, "a refused rewind must not leave its lock behind")
mini.SetTime(now.Add(31 * time.Second))
unlock, err := store.TryLockRewind(ctx, key)
require.NoError(t, err)
unlock()
}
@@ -0,0 +1,323 @@
package sandbox
import (
"context"
"encoding/json"
"errors"
"sync/atomic"
"testing"
"time"
"academy/internal/common/redislock"
"github.com/alicebob/miniredis/v2"
"github.com/redis/go-redis/v9"
"github.com/stretchr/testify/require"
)
func newRedisBindingTestStore(
t *testing.T,
) (*RedisSessionSandboxBindingStore, *redis.Client, *miniredis.Miniredis) {
t.Helper()
mini := miniredis.RunT(t)
client := redis.NewClient(&redis.Options{Addr: mini.Addr(), MaxRetries: -1})
t.Cleanup(func() { require.NoError(t, client.Close()) })
store, err := NewRedisSessionSandboxBindingStore(client, "test")
require.NoError(t, err)
return store, client, mini
}
func newTwoRedisBindingTestStores(
t *testing.T,
) (*RedisSessionSandboxBindingStore, *RedisSessionSandboxBindingStore) {
t.Helper()
mini := miniredis.RunT(t)
newStore := func() *RedisSessionSandboxBindingStore {
client := redis.NewClient(&redis.Options{Addr: mini.Addr(), MaxRetries: -1})
t.Cleanup(func() { require.NoError(t, client.Close()) })
store, err := NewRedisSessionSandboxBindingStore(client, "test")
require.NoError(t, err)
return store
}
return newStore(), newStore()
}
func TestRedisSessionSandboxBindingStoreContract(t *testing.T) {
store, _, _ := newRedisBindingTestStore(t)
testSessionSandboxBindingStore(t, store)
}
func TestRedisSessionSandboxBindingStoreReplacesTrafficToken(t *testing.T) {
store, _, _ := newRedisBindingTestStore(t)
testSessionSandboxBindingReplacesTrafficToken(t, store)
}
func TestRedisSessionSandboxBindingStoreTurnLease(t *testing.T) {
store, client, _ := newRedisBindingTestStore(t)
testSessionTurnLeaseStore(t, store)
key := SessionSandboxKey{TenantID: 42, SessionID: "session-missing-turn"}
require.NoError(t, store.ConsumeTurnRebuild(context.Background(), key))
exists, err := client.Exists(context.Background(), store.turnKey(key)).Result()
require.NoError(t, err)
require.Zero(t, exists, "consuming a missing turn must not create a lease key")
}
func TestRedisSessionSandboxBindingStoreBeginTurnFailsWhenRewindLocked(t *testing.T) {
store, _, _ := newRedisBindingTestStore(t)
ctx := context.Background()
key := SessionSandboxKey{TenantID: 42, SessionID: "session-rewind-turn"}
unlock, err := store.TryLockRewind(ctx, key)
require.NoError(t, err)
held, err := store.HasRewindLock(ctx, key)
require.NoError(t, err)
require.True(t, held)
require.ErrorIs(t, store.BeginTurn(ctx, key), ErrSessionRewindLocked)
unlock()
require.NoError(t, store.BeginTurn(ctx, key))
require.NoError(t, store.EndTurn(ctx, key))
}
func TestRedisSessionSandboxBindingStoreTryLockRewindFailsWhenTurnActive(t *testing.T) {
store, _, _ := newRedisBindingTestStore(t)
ctx := context.Background()
key := SessionSandboxKey{TenantID: 42, SessionID: "session-turn-rewind"}
require.NoError(t, store.BeginTurn(ctx, key))
_, err := store.TryLockRewind(ctx, key)
require.ErrorIs(t, err, ErrSessionTurnActive)
require.NoError(t, store.EndTurn(ctx, key))
unlock, err := store.TryLockRewind(ctx, key)
require.NoError(t, err)
unlock()
}
func TestRedisSessionSandboxBindingStoreRewindLockRenews(t *testing.T) {
store, client, _ := newRedisBindingTestStore(t)
store.rewindLockTTL = 150 * time.Millisecond
store.rewindLockRenew = 40 * time.Millisecond
ctx := context.Background()
key := SessionSandboxKey{TenantID: 42, SessionID: "session-rewind-renew"}
unlock, err := store.TryLockRewind(ctx, key)
require.NoError(t, err)
t.Cleanup(unlock)
time.Sleep(220 * time.Millisecond)
n, err := client.Exists(ctx, store.rewindKey(key)).Result()
require.NoError(t, err)
require.Equal(t, int64(1), n, "rewind lock must be renewed past the original TTL")
}
func TestRedisSessionSandboxBindingStoreRewindLockRenewSurvivesErrors(t *testing.T) {
store, client, _ := newRedisBindingTestStore(t)
store.rewindLockTTL = 150 * time.Millisecond
store.rewindLockRenew = 40 * time.Millisecond
var fails atomic.Int32
store.rewindRenewer = func(ctx context.Context, key, token string, lease time.Duration) (bool, error) {
if fails.Add(1) == 1 {
return false, errors.New("redis blip")
}
return redislock.Renew(ctx, store.client, key, token, lease)
}
ctx := context.Background()
key := SessionSandboxKey{TenantID: 42, SessionID: "session-rewind-renew-blip"}
unlock, err := store.TryLockRewind(ctx, key)
require.NoError(t, err)
t.Cleanup(unlock)
time.Sleep(220 * time.Millisecond)
n, err := client.Exists(ctx, store.rewindKey(key)).Result()
require.NoError(t, err)
require.Equal(t, int64(1), n, "rewind lock renew must keep retrying after a transient error")
require.GreaterOrEqual(t, fails.Load(), int32(2))
}
func TestRedisSessionSandboxBindingStoreInvalidatesByConfig(t *testing.T) {
store, _, _ := newRedisBindingTestStore(t)
testSessionSandboxBindingInvalidateByConfig(t, store)
}
func TestRedisSessionSandboxBindingStoreSeparatesTenants(t *testing.T) {
store, _, _ := newRedisBindingTestStore(t)
testSessionSandboxBindingTenantIsolation(t, store)
}
func TestRedisSessionSandboxBindingUsesHashTagAndNoTTL(t *testing.T) {
store, client, _ := newRedisBindingTestStore(t)
key := SessionSandboxKey{TenantID: 42, SessionID: "session-a"}
bindingKey := store.bindingKey(key)
lockKey := store.lockKey(key)
require.Equal(t, "academy:sandbox:session:{test:42:session-a}:binding", bindingKey)
require.Equal(t, "academy:sandbox:session:{test:42:session-a}:create-lock", lockKey)
created, err := store.Create(context.Background(), key, validSessionSandboxBinding(key, "sandbox-a"))
require.NoError(t, err)
require.True(t, created)
require.Equal(t, time.Duration(-1), client.TTL(context.Background(), bindingKey).Val())
}
func TestRedisSessionSandboxBindingRejectsMissingProvider(t *testing.T) {
store, client, _ := newRedisBindingTestStore(t)
key := SessionSandboxKey{TenantID: 42, SessionID: "session-a"}
incomplete := map[string]any{
"version": SessionSandboxBindingVersion,
"tenant_id": 42,
"session_id": "session-a",
"sandbox_id": "sandbox-a",
"template_id": "template-a",
"created_at": time.Unix(100, 0).UTC(),
}
raw, err := json.Marshal(incomplete)
require.NoError(t, err)
require.NoError(t, client.Set(context.Background(), store.bindingKey(key), raw, 0).Err())
_, err = store.Get(context.Background(), key)
require.Error(t, err)
}
func TestRedisSessionSandboxBindingRejectsMalformedOrMismatchedData(t *testing.T) {
store, client, _ := newRedisBindingTestStore(t)
key := SessionSandboxKey{TenantID: 42, SessionID: "session-a"}
require.NoError(t, client.Set(context.Background(), store.bindingKey(key), "{", 0).Err())
_, err := store.Get(context.Background(), key)
require.Error(t, err)
mismatch := validSessionSandboxBinding(
SessionSandboxKey{TenantID: 43, SessionID: "session-a"},
"sandbox-a",
)
raw, err := json.Marshal(mismatch)
require.NoError(t, err)
require.NoError(t, client.Set(context.Background(), store.bindingKey(key), raw, 0).Err())
_, err = store.Get(context.Background(), key)
require.Error(t, err)
}
func TestRedisSessionSandboxBindingFailsClosedWhenRedisStops(t *testing.T) {
store, _, mini := newRedisBindingTestStore(t)
key := SessionSandboxKey{TenantID: 42, SessionID: "session-a"}
binding := validSessionSandboxBinding(key, "sandbox-a")
mini.Close()
_, err := store.Get(context.Background(), key)
require.Error(t, err)
_, err = store.Create(context.Background(), key, binding)
require.Error(t, err)
_, err = store.DeleteIfMatch(context.Background(), key, SandboxTypeCube, "sandbox-a")
require.Error(t, err)
called := false
err = store.WithLifecycleLock(context.Background(), key, func(context.Context) error {
called = true
return nil
})
require.Error(t, err)
require.False(t, called)
}
func TestRedisSessionSandboxBindingValidatesConstructor(t *testing.T) {
_, err := NewRedisSessionSandboxBindingStore(nil, "test")
require.Error(t, err)
client := redis.NewClient(&redis.Options{Addr: "unused"})
t.Cleanup(func() { require.NoError(t, client.Close()) })
for _, namespace := range []string{"bad{namespace", "bad}namespace", "bad\nnamespace"} {
_, err = NewRedisSessionSandboxBindingStore(client, namespace)
require.Error(t, err)
}
_, err = NewRedisSessionSandboxBindingStore(client, "namespace:with-punctuation")
require.NoError(t, err)
}
func TestRedisLifecycleLockSerializesAcrossStores(t *testing.T) {
firstStore, secondStore := newTwoRedisBindingTestStores(t)
key := SessionSandboxKey{TenantID: 42, SessionID: "session-a"}
firstEntered := make(chan struct{})
releaseFirst := make(chan struct{})
firstDone := make(chan error, 1)
go func() {
firstDone <- firstStore.WithLifecycleLock(context.Background(), key, func(context.Context) error {
close(firstEntered)
<-releaseFirst
return nil
})
}()
<-firstEntered
secondEntered := make(chan struct{})
secondDone := make(chan error, 1)
go func() {
secondDone <- secondStore.WithLifecycleLock(context.Background(), key, func(context.Context) error {
close(secondEntered)
return nil
})
}()
select {
case <-secondEntered:
t.Fatal("contender entered before the first owner released")
case <-time.After(50 * time.Millisecond):
}
close(releaseFirst)
require.NoError(t, <-firstDone)
select {
case <-secondEntered:
case <-time.After(time.Second):
t.Fatal("contender did not acquire after release")
}
require.NoError(t, <-secondDone)
}
func TestRedisLifecycleLockAllowsDifferentKeys(t *testing.T) {
firstStore, secondStore := newTwoRedisBindingTestStores(t)
firstKey := SessionSandboxKey{TenantID: 42, SessionID: "session-a"}
secondKey := SessionSandboxKey{TenantID: 43, SessionID: "session-a"}
firstEntered := make(chan struct{})
releaseFirst := make(chan struct{})
firstDone := make(chan error, 1)
go func() {
firstDone <- firstStore.WithLifecycleLock(context.Background(), firstKey, func(context.Context) error {
close(firstEntered)
<-releaseFirst
return nil
})
}()
<-firstEntered
err := secondStore.WithLifecycleLock(context.Background(), secondKey, func(context.Context) error {
return nil
})
require.NoError(t, err)
close(releaseFirst)
require.NoError(t, <-firstDone)
}
func TestRedisUserMachineKeysShareOneHashTag(t *testing.T) {
store, _, mini := newRedisBindingTestStore(t)
ctx := context.Background()
key := userMachineKey()
created, err := store.Create(ctx, key, validUserBinding("sb-1"))
require.NoError(t, err)
require.True(t, created)
digest := testUserMachine().Digest(store.namespace)
require.True(t, mini.Exists("academy:sandbox:user:{"+digest+"}:binding"))
scoped := SessionSandboxKey{TenantID: 42, SessionID: userKeySessionID, User: testUserMachine()}
require.NoError(t, store.BeginTurn(ctx, scoped))
require.True(t, mini.Exists("academy:sandbox:user:{"+digest+"}:session:"+userKeySessionID+":turn"))
got, err := store.Get(ctx, key)
require.NoError(t, err)
require.Equal(t, "sb-1", got.SandboxID)
}
@@ -0,0 +1,67 @@
package sandbox
import (
"context"
"testing"
"github.com/stretchr/testify/require"
"academy/internal/types"
)
func newTenantKeyTestManager(t *testing.T) (*SessionBoundManager, *fakeRemoteClient) {
t.Helper()
client := newFakeRemoteClient(SandboxTypeCube)
cfg := DefaultConfig()
cfg.CubeTemplate = "tpl-test"
mgr, err := NewSessionBoundManager(SessionBoundManagerConfig{
Config: cfg,
Client: client,
Store: NewMemorySessionSandboxBindingStore(),
Checker: &fakeSessionExistenceChecker{exists: true},
SkipHealthProbe: true,
})
require.NoError(t, err)
return mgr, client
}
// A shared agent executes under the agent owner's tenant so its models, KBs and
// named sandbox config resolve in the sharing workspace. Session deletion,
// however, runs from a plain DELETE whose only tenant is the session's own.
//
// If the binding were keyed by the borrowed tenant, that teardown would look up
// a key nobody wrote, silently leave the MicroVM running, and — because session
// sandboxes are created with onTimeout=pause — leak a paused instance that keeps
// billing with nobody holding its ID.
func TestSessionBindingSurvivesBorrowedTenantAcrossDestroy(t *testing.T) {
const sessionOwner, agentOwner = uint64(7), uint64(99)
mgr, client := newTenantKeyTestManager(t)
// Execution: borrowed tenant in TenantID, session owner recorded alongside.
execCtx := context.WithValue(context.Background(), types.TenantIDContextKey, agentOwner)
execCtx = types.WithSandboxTenantID(execCtx, sessionOwner)
_, err := mgr.Execute(execCtx, &ExecuteConfig{
SessionID: "session-shared",
SkipValidation: true,
ScriptContent: "print('ok')\n",
Script: "hello.py",
})
require.NoError(t, err)
client.mu.Lock()
created := client.createCount
client.mu.Unlock()
require.Equal(t, 1, created, "execution should have provisioned one sandbox")
// Teardown: only the session's own tenant is known here, and no sandbox
// tenant key is set — exactly what sessionService.destroyBoundSandbox does.
destroyCtx := context.WithValue(context.Background(), types.TenantIDContextKey, sessionOwner)
require.NoError(t, mgr.DestroySession(destroyCtx, "session-shared"))
client.mu.Lock()
deleted := append([]string(nil), client.deleteIDs...)
client.mu.Unlock()
require.Len(t, deleted, 1, "teardown must reach the sandbox execution created")
}
+655
View File
@@ -0,0 +1,655 @@
package sandbox
import (
"context"
"encoding/json"
"errors"
"strconv"
"sync/atomic"
"testing"
"time"
"github.com/stretchr/testify/require"
"academy/internal/sandbox/allocation"
)
func validSessionSandboxBinding(key SessionSandboxKey, sandboxID string) SessionSandboxBinding {
return SessionSandboxBinding{
Version: SessionSandboxBindingVersion,
Provider: SandboxTypeCube,
TenantID: key.TenantID,
SessionID: key.SessionID,
SandboxID: sandboxID,
TemplateID: "template-a",
CreatedAt: time.Unix(100, 0).UTC(),
}
}
func testSessionSandboxBindingStore(t *testing.T, store SessionSandboxBindingStore) {
t.Helper()
ctx := context.Background()
key := SessionSandboxKey{TenantID: 42, SessionID: "session-a"}
first := validSessionSandboxBinding(key, "sandbox-a")
got, err := store.Get(ctx, key)
require.NoError(t, err)
require.Nil(t, got)
created, err := store.Create(ctx, key, first)
require.NoError(t, err)
require.True(t, created)
got, err = store.Get(ctx, key)
require.NoError(t, err)
require.Equal(t, &first, got)
created, err = store.Create(ctx, key, validSessionSandboxBinding(key, "sandbox-b"))
require.NoError(t, err)
require.False(t, created)
deleted, err := store.DeleteIfMatch(ctx, key, SandboxTypeE2B, "sandbox-a")
require.NoError(t, err)
require.False(t, deleted)
deleted, err = store.DeleteIfMatch(ctx, key, SandboxTypeCube, "sandbox-b")
require.NoError(t, err)
require.False(t, deleted)
deleted, err = store.DeleteIfMatch(ctx, key, SandboxTypeCube, "sandbox-a")
require.NoError(t, err)
require.True(t, deleted)
}
func TestMemorySessionSandboxBindingStoreReplacesTrafficToken(t *testing.T) {
store := NewMemorySessionSandboxBindingStore()
testSessionSandboxBindingReplacesTrafficToken(t, store)
}
func testSessionSandboxBindingReplacesTrafficToken(t *testing.T, store SessionSandboxBindingStore) {
t.Helper()
ctx := context.Background()
key := SessionSandboxKey{TenantID: 42, SessionID: "session-token"}
binding := validSessionSandboxBinding(key, "sandbox-a")
binding.TrafficAccessToken = "old-token"
binding.ConfigID = "cfg-token"
created, err := store.Create(ctx, key, binding)
require.NoError(t, err)
require.True(t, created)
marked, err := store.InvalidateByConfig(ctx, key.TenantID, binding.ConfigID)
require.NoError(t, err)
require.Equal(t, 1, marked)
wrote, err := store.ReplaceTrafficTokenIfMatch(ctx, key, binding, "new-token")
require.NoError(t, err)
require.True(t, wrote)
got, err := store.Get(ctx, key)
require.NoError(t, err)
require.Equal(t, "new-token", got.TrafficAccessToken)
require.Equal(t, binding.SandboxID, got.SandboxID)
require.NotNil(t, got.StaleAt, "patching the token must not wipe a concurrent stale mark")
mismatch := binding
mismatch.SandboxID = "sandbox-other"
wrote, err = store.ReplaceTrafficTokenIfMatch(ctx, key, mismatch, "ignored")
require.NoError(t, err)
require.False(t, wrote)
got, err = store.Get(ctx, key)
require.NoError(t, err)
require.Equal(t, "new-token", got.TrafficAccessToken)
wrote, err = store.ReplaceTrafficTokenIfMatch(ctx, key, binding, "")
require.NoError(t, err)
require.False(t, wrote)
}
func testSessionSandboxBindingTenantIsolation(t *testing.T, store SessionSandboxBindingStore) {
t.Helper()
ctx := context.Background()
firstKey := SessionSandboxKey{TenantID: 42, SessionID: "shared-session"}
secondKey := SessionSandboxKey{TenantID: 43, SessionID: "shared-session"}
created, err := store.Create(ctx, firstKey, validSessionSandboxBinding(firstKey, "sandbox-a"))
require.NoError(t, err)
require.True(t, created)
created, err = store.Create(ctx, secondKey, validSessionSandboxBinding(secondKey, "sandbox-b"))
require.NoError(t, err)
require.True(t, created)
first, err := store.Get(ctx, firstKey)
require.NoError(t, err)
second, err := store.Get(ctx, secondKey)
require.NoError(t, err)
require.Equal(t, "sandbox-a", first.SandboxID)
require.Equal(t, "sandbox-b", second.SandboxID)
}
// testSessionSandboxBindingInvalidateByConfig is a store-level contract: both
// implementations have to find every binding of one workspace's config without
// enumerating another workspace's, and mark it in place.
func testSessionSandboxBindingInvalidateByConfig(t *testing.T, store SessionSandboxBindingStore) {
t.Helper()
ctx := context.Background()
target := SessionSandboxKey{TenantID: 42, SessionID: "session-target"}
otherConfig := SessionSandboxKey{TenantID: 42, SessionID: "session-other-config"}
otherTenant := SessionSandboxKey{TenantID: 43, SessionID: "session-other-tenant"}
// A binding written before ConfigID existed - the one case a rolling
// upgrade actually produces. It must match no config at all, rather than
// every config, or the first install after an upgrade rebuilds the whole
// deployment's sandboxes.
legacy := SessionSandboxKey{TenantID: 42, SessionID: "session-pre-upgrade"}
create := func(key SessionSandboxKey, configID string) {
binding := validSessionSandboxBinding(key, "sandbox-"+key.SessionID)
binding.ConfigID = configID
created, err := store.Create(ctx, key, binding)
require.NoError(t, err)
require.True(t, created)
}
create(target, "cfg-1")
create(otherConfig, "cfg-2")
create(otherTenant, "cfg-1")
create(legacy, "")
marked, err := store.InvalidateByConfig(ctx, 42, "cfg-1")
require.NoError(t, err)
require.Equal(t, 1, marked)
got, err := store.Get(ctx, target)
require.NoError(t, err)
require.NotNil(t, got.StaleAt)
require.Equal(t, "sandbox-"+target.SessionID, got.SandboxID,
"marking must not disturb the rest of the binding")
legacyMarked, err := store.InvalidateByConfig(ctx, 42, "")
require.NoError(t, err)
require.Zero(t, legacyMarked,
"an empty ConfigID means 'unknown', not 'the deployment default config'")
got, err = store.Get(ctx, legacy)
require.NoError(t, err)
require.Nil(t, got.StaleAt, "a pre-upgrade binding must survive an install untouched")
for _, key := range []SessionSandboxKey{otherConfig, otherTenant, legacy} {
got, err = store.Get(ctx, key)
require.NoError(t, err)
require.Nil(t, got.StaleAt, "binding %s must be untouched", key.SessionID)
}
marked, err = store.InvalidateByConfig(ctx, 42, "cfg-1")
require.NoError(t, err)
require.Zero(t, marked, "an already marked binding is not marked again")
}
// bindingMarkBudgetSpy reports the budget the marking work is given, once the
// session's lifecycle lock is held.
type bindingMarkBudgetSpy struct {
*MemorySessionSandboxBindingStore
markBudget time.Duration
markHadBudget bool
}
func (s *bindingMarkBudgetSpy) WithLifecycleLock(
ctx context.Context, key SessionSandboxKey, fn func(context.Context) error,
) error {
return s.MemorySessionSandboxBindingStore.WithLifecycleLock(
ctx, key, func(lockCtx context.Context) error {
return fn(lockCtx)
},
)
}
func (s *bindingMarkBudgetSpy) markBindingStale(
ctx context.Context,
key SessionSandboxKey,
expected SessionSandboxBinding,
staleAt time.Time,
) (bool, error) {
if deadline, ok := ctx.Deadline(); ok {
s.markHadBudget = true
s.markBudget = time.Until(deadline)
}
return s.MemorySessionSandboxBindingStore.markBindingStale(ctx, key, expected, staleAt)
}
// The lock-wait cap must not double as the work budget: a mark that waited most
// of the cap for the lock would otherwise be left with a few milliseconds for
// its read plus compare-and-set, and fail with a deadline error that reads like
// a Redis fault.
func TestInvalidateGivesTheMarkItsOwnBudget(t *testing.T) {
t.Parallel()
spy := &bindingMarkBudgetSpy{MemorySessionSandboxBindingStore: NewMemorySessionSandboxBindingStore()}
ctx := context.Background()
key := SessionSandboxKey{TenantID: 42, SessionID: "session-a"}
binding := validSessionSandboxBinding(key, "sandbox-a")
binding.ConfigID = "cfg-1"
created, err := spy.Create(ctx, key, binding)
require.NoError(t, err)
require.True(t, created)
marked, err := invalidateBindingsByConfig(ctx, spy, 42, "cfg-1")
require.NoError(t, err)
require.Equal(t, 1, marked)
require.True(t, spy.markHadBudget, "the mark still has to be bounded")
require.Greater(t, spy.markBudget, bindingInvalidateLockTimeout,
"the mark must get its own budget, not what is left of the lock-wait cap")
}
// The wait for one session's lock stays capped: the caller holds the per-config
// install lock, so a session that happens to be creating a sandbox right now
// must cost only its own mark.
func TestInvalidateStopsWaitingForALockedSession(t *testing.T) {
t.Parallel()
store := NewMemorySessionSandboxBindingStore()
ctx := context.Background()
key := SessionSandboxKey{TenantID: 42, SessionID: "session-busy"}
binding := validSessionSandboxBinding(key, "sandbox-a")
binding.ConfigID = "cfg-1"
created, err := store.Create(ctx, key, binding)
require.NoError(t, err)
require.True(t, created)
held := make(chan struct{})
release := make(chan struct{})
go func() {
_ = store.WithLifecycleLock(ctx, key, func(context.Context) error {
close(held)
<-release
return nil
})
}()
<-held
defer close(release)
start := time.Now()
marked, err := store.InvalidateByConfig(ctx, 42, "cfg-1")
elapsed := time.Since(start)
require.Error(t, err, "the session that could not be marked is reported")
require.Zero(t, marked)
require.Less(t, elapsed, bindingInvalidateLockTimeout+time.Second,
"waiting on one busy session must not hold up the rest of the workspace")
require.GreaterOrEqual(t, elapsed, bindingInvalidateLockTimeout)
}
func TestMemorySessionSandboxBindingStoreInvalidatesByConfig(t *testing.T) {
t.Parallel()
testSessionSandboxBindingInvalidateByConfig(t, NewMemorySessionSandboxBindingStore())
}
func TestMemorySessionSandboxBindingStoreContract(t *testing.T) {
t.Parallel()
testSessionSandboxBindingStore(t, NewMemorySessionSandboxBindingStore())
}
func TestMemorySessionSandboxBindingStoreTurnLease(t *testing.T) {
t.Parallel()
testSessionTurnLeaseStore(t, NewMemorySessionSandboxBindingStore())
}
func testSessionTurnLeaseStore(t *testing.T, store sessionTurnLeaseStore) {
t.Helper()
ctx := context.Background()
key := SessionSandboxKey{TenantID: 42, SessionID: "session-turn"}
active, rebuildOnce, err := store.TurnState(ctx, key)
require.NoError(t, err)
require.False(t, active)
require.False(t, rebuildOnce)
require.NoError(t, store.BeginTurn(ctx, key))
active, rebuildOnce, err = store.TurnState(ctx, key)
require.NoError(t, err)
require.True(t, active)
require.True(t, rebuildOnce)
require.NoError(t, store.BeginTurn(ctx, key))
active, rebuildOnce, err = store.TurnState(ctx, key)
require.NoError(t, err)
require.True(t, active)
require.True(t, rebuildOnce, "a nested BeginTurn must not reset rebuildOnce")
require.NoError(t, store.ConsumeTurnRebuild(ctx, key))
active, rebuildOnce, err = store.TurnState(ctx, key)
require.NoError(t, err)
require.True(t, active)
require.False(t, rebuildOnce)
require.NoError(t, store.EndTurn(ctx, key))
active, rebuildOnce, err = store.TurnState(ctx, key)
require.NoError(t, err)
require.True(t, active)
require.False(t, rebuildOnce)
require.NoError(t, store.EndTurn(ctx, key))
active, rebuildOnce, err = store.TurnState(ctx, key)
require.NoError(t, err)
require.False(t, active)
require.False(t, rebuildOnce)
cancelled, cancel := context.WithCancel(ctx)
cancel()
require.Error(t, store.BeginTurn(cancelled, key))
}
func TestMemorySessionSandboxBindingStoreRewindLock(t *testing.T) {
t.Parallel()
store := NewMemorySessionSandboxBindingStore()
ctx := context.Background()
key := SessionSandboxKey{TenantID: 42, SessionID: "session-rewind"}
unlock, err := store.TryLockRewind(ctx, key)
require.NoError(t, err)
_, err = store.TryLockRewind(ctx, key)
require.ErrorIs(t, err, ErrSessionRewindLocked)
unlock()
unlock, err = store.TryLockRewind(ctx, key)
require.NoError(t, err)
unlock()
}
func TestMemorySessionSandboxBindingStoreBeginTurnFailsWhenRewindLocked(t *testing.T) {
t.Parallel()
store := NewMemorySessionSandboxBindingStore()
ctx := context.Background()
key := SessionSandboxKey{TenantID: 42, SessionID: "session-rewind-turn"}
unlock, err := store.TryLockRewind(ctx, key)
require.NoError(t, err)
held, err := store.HasRewindLock(ctx, key)
require.NoError(t, err)
require.True(t, held)
require.ErrorIs(t, store.BeginTurn(ctx, key), ErrSessionRewindLocked)
unlock()
require.NoError(t, store.BeginTurn(ctx, key))
require.NoError(t, store.EndTurn(ctx, key))
}
func TestMemorySessionSandboxBindingStoreTryLockRewindFailsWhenTurnActive(t *testing.T) {
t.Parallel()
store := NewMemorySessionSandboxBindingStore()
ctx := context.Background()
key := SessionSandboxKey{TenantID: 42, SessionID: "session-turn-rewind"}
require.NoError(t, store.BeginTurn(ctx, key))
_, err := store.TryLockRewind(ctx, key)
require.ErrorIs(t, err, ErrSessionTurnActive)
require.NoError(t, store.EndTurn(ctx, key))
unlock, err := store.TryLockRewind(ctx, key)
require.NoError(t, err)
unlock()
}
func TestMemorySessionSandboxBindingStoreSeparatesTenants(t *testing.T) {
t.Parallel()
testSessionSandboxBindingTenantIsolation(t, NewMemorySessionSandboxBindingStore())
}
func TestSessionSandboxBindingValidation(t *testing.T) {
t.Parallel()
key := SessionSandboxKey{TenantID: 42, SessionID: "session-a"}
require.NoError(t, key.Validate())
require.Error(t, (SessionSandboxKey{}).Validate())
require.Error(t, (SessionSandboxKey{TenantID: 42, SessionID: " \t"}).Validate())
require.Error(t, (SessionSandboxKey{TenantID: 42, SessionID: "bad{session"}).Validate())
require.Error(t, (SessionSandboxKey{TenantID: 42, SessionID: "bad\nsession"}).Validate())
valid := validSessionSandboxBinding(key, "sandbox-a")
require.NoError(t, valid.Validate(key))
tests := []SessionSandboxBinding{
{Version: SessionSandboxBindingVersion + 1, Provider: SandboxTypeCube, TenantID: 42, SessionID: "session-a", SandboxID: "sandbox-a"},
{Version: SessionSandboxBindingVersion, TenantID: 42, SessionID: "session-a", SandboxID: "sandbox-a"},
{Version: SessionSandboxBindingVersion, Provider: "unknown", TenantID: 42, SessionID: "session-a", SandboxID: "sandbox-a"},
{Version: SessionSandboxBindingVersion, Provider: SandboxTypeCube, TenantID: 43, SessionID: "session-a", SandboxID: "sandbox-a"},
{Version: SessionSandboxBindingVersion, Provider: SandboxTypeCube, TenantID: 42, SessionID: "other", SandboxID: "sandbox-a"},
{Version: SessionSandboxBindingVersion, Provider: SandboxTypeCube, TenantID: 42, SessionID: "session-a"},
}
for _, binding := range tests {
require.Error(t, binding.Validate(key), "binding must be rejected: %+v", binding)
}
}
// Bindings written before this field existed must stay usable: their sandboxes
// were created while inbound access was still open, so an empty token is the
// correct value rather than a corrupt one.
func TestSessionSandboxBindingWithoutTrafficTokenStaysValid(t *testing.T) {
key := SessionSandboxKey{TenantID: 1, SessionID: "session-1"}
raw := []byte(`{
"version": ` + strconv.Itoa(SessionSandboxBindingVersion) + `,
"provider": "cube",
"tenant_id": 1,
"session_id": "session-1",
"sandbox_id": "sandbox-1",
"template_id": "tpl-1",
"created_at": "2026-01-01T00:00:00Z"
}`)
var binding SessionSandboxBinding
require.NoError(t, json.Unmarshal(raw, &binding))
require.NoError(t, binding.Validate(key))
require.Empty(t, binding.TrafficAccessToken)
}
func TestSessionSandboxBindingOmitsEmptyTrafficToken(t *testing.T) {
encoded, err := json.Marshal(SessionSandboxBinding{
Version: SessionSandboxBindingVersion, Provider: SandboxTypeCube,
TenantID: 1, SessionID: "s", SandboxID: "sb", TemplateID: "tpl",
CreatedAt: time.Unix(0, 0).UTC(),
})
require.NoError(t, err)
require.NotContains(t, string(encoded), "traffic_access_token")
}
func TestSessionSandboxBindingRoundTripsTrafficToken(t *testing.T) {
const token = "traffic-token"
encoded, err := json.Marshal(SessionSandboxBinding{
Version: SessionSandboxBindingVersion, Provider: SandboxTypeCube,
TenantID: 1, SessionID: "s", SandboxID: "sb", TemplateID: "tpl",
TrafficAccessToken: token, CreatedAt: time.Unix(0, 0).UTC(),
})
require.NoError(t, err)
require.Contains(t, string(encoded), `"traffic_access_token"`)
var decoded SessionSandboxBinding
require.NoError(t, json.Unmarshal(encoded, &decoded))
require.Equal(t, token, decoded.TrafficAccessToken)
}
func TestMemoryLifecycleLockSerializesSameKey(t *testing.T) {
t.Parallel()
store := NewMemorySessionSandboxBindingStore()
key := SessionSandboxKey{TenantID: 42, SessionID: "session-a"}
var active atomic.Int32
var overlapped atomic.Bool
start := make(chan struct{})
done := make(chan error, 2)
for range 2 {
go func() {
<-start
done <- store.WithLifecycleLock(context.Background(), key, func(context.Context) error {
if active.Add(1) != 1 {
overlapped.Store(true)
}
time.Sleep(10 * time.Millisecond)
active.Add(-1)
return nil
})
}()
}
close(start)
require.NoError(t, <-done)
require.NoError(t, <-done)
require.False(t, overlapped.Load())
}
func TestMemoryLifecycleLockHonorsContextAndCallbackError(t *testing.T) {
t.Parallel()
store := NewMemorySessionSandboxBindingStore()
key := SessionSandboxKey{TenantID: 42, SessionID: "session-a"}
entered := make(chan struct{})
release := make(chan struct{})
firstDone := make(chan error, 1)
go func() {
firstDone <- store.WithLifecycleLock(context.Background(), key, func(context.Context) error {
close(entered)
<-release
return nil
})
}()
<-entered
ctx, cancel := context.WithTimeout(context.Background(), 25*time.Millisecond)
defer cancel()
called := false
err := store.WithLifecycleLock(ctx, key, func(context.Context) error {
called = true
return nil
})
require.ErrorIs(t, err, context.DeadlineExceeded)
require.False(t, called)
close(release)
require.NoError(t, <-firstDone)
want := errors.New("callback failed")
err = store.WithLifecycleLock(context.Background(), key, func(context.Context) error {
return want
})
require.ErrorIs(t, err, want)
}
const userKeySessionID = "0f8fad5b-d9cb-469f-a165-70867728950e"
func testUserMachine() allocation.UserMachine {
return allocation.UserMachine{OwnerTenantID: 42, OwnerID: "u-1", ConfigTenantID: 42, ConfigID: "cfg-1"}
}
func userMachineKey() SessionSandboxKey {
return SessionSandboxKey{TenantID: 42, User: testUserMachine()}
}
func validUserBinding(sandboxID string) SessionSandboxBinding {
m := testUserMachine()
return SessionSandboxBinding{
Version: UserSandboxBindingVersion, Provider: SandboxTypeCube, TenantID: 42,
SandboxID: sandboxID, TemplateID: "tpl", CreatedAt: time.Now().UTC(),
ConfigID: m.ConfigID, OwnerID: m.OwnerID, ConfigTenantID: m.ConfigTenantID,
}
}
func TestSessionSandboxKeyShapes(t *testing.T) {
machine := userMachineKey()
require.NoError(t, machine.Validate())
require.True(t, machine.IsUserScoped())
require.True(t, machine.IsUserMachine())
scoped := SessionSandboxKey{TenantID: 42, SessionID: userKeySessionID, User: testUserMachine()}
require.NoError(t, scoped.Validate())
require.False(t, scoped.IsUserMachine())
require.Equal(t, machine, scoped.Machine())
legacy := SessionSandboxKey{TenantID: 42, SessionID: "session-a"}
require.Equal(t, legacy, legacy.Machine())
require.False(t, legacy.IsUserScoped())
require.Error(t, SessionSandboxKey{TenantID: 43, User: testUserMachine()}.Validate(),
"the key tenant must be the machine's owner tenant")
require.Error(t, SessionSandboxKey{TenantID: 42, SessionID: "not-a-uuid", User: testUserMachine()}.Validate())
}
func TestUserBindingValidation(t *testing.T) {
key := userMachineKey()
require.NoError(t, validUserBinding("sb-1").Validate(key))
wrongVersion := validUserBinding("sb-1")
wrongVersion.Version = SessionSandboxBindingVersion
require.Error(t, wrongVersion.Validate(key))
wrongOwner := validUserBinding("sb-1")
wrongOwner.OwnerID = "u-2"
require.Error(t, wrongOwner.Validate(key))
withSession := validUserBinding("sb-1")
withSession.SessionID = userKeySessionID
require.Error(t, withSession.Validate(key))
scoped := SessionSandboxKey{TenantID: 42, SessionID: userKeySessionID, User: testUserMachine()}
require.Error(t, validUserBinding("sb-1").Validate(scoped), "bindings are addressed by the machine key only")
// A legacy binding still validates exactly as before.
legacyKey := SessionSandboxKey{TenantID: 42, SessionID: "session-a"}
require.NoError(t, validSessionSandboxBinding(legacyKey, "sb-2").Validate(legacyKey))
}
func TestMemoryStoreHoldsUserMachineBindings(t *testing.T) {
ctx := context.Background()
store := NewMemorySessionSandboxBindingStore()
key := userMachineKey()
created, err := store.Create(ctx, key, validUserBinding("sb-1"))
require.NoError(t, err)
require.True(t, created)
got, err := store.Get(ctx, key)
require.NoError(t, err)
require.Equal(t, "sb-1", got.SandboxID)
keys, err := store.listTenantBindingKeys(ctx, 42)
require.NoError(t, err)
require.Empty(t, keys, "the session-binding scan never returns user machines")
}
func TestMemoryLifecycleLockSerializesUserMachineAndItsSession(t *testing.T) {
store := NewMemorySessionSandboxBindingStore()
machine := userMachineKey()
scoped := SessionSandboxKey{TenantID: 42, SessionID: userKeySessionID, User: testUserMachine()}
var active atomic.Int32
var overlapped atomic.Bool
start := make(chan struct{})
done := make(chan error, 2)
for _, key := range []SessionSandboxKey{machine, scoped} {
go func(key SessionSandboxKey) {
<-start
done <- store.WithLifecycleLock(context.Background(), key, func(context.Context) error {
if active.Add(1) != 1 {
overlapped.Store(true)
}
time.Sleep(20 * time.Millisecond)
active.Add(-1)
return nil
})
}(key)
}
close(start)
require.NoError(t, <-done)
require.NoError(t, <-done)
require.False(t, overlapped.Load())
}
func TestMemoryGetRejectsSessionOnUserMachineBinding(t *testing.T) {
ctx := context.Background()
store := NewMemorySessionSandboxBindingStore()
created, err := store.Create(ctx, userMachineKey(), validUserBinding("sb-1"))
require.NoError(t, err)
require.True(t, created)
scoped := SessionSandboxKey{TenantID: 42, SessionID: userKeySessionID, User: testUserMachine()}
got, err := store.Get(ctx, scoped)
require.Nil(t, got)
require.ErrorContains(t, err, "validate sandbox binding: sandbox binding must be addressed by its user machine key")
}
+53
View File
@@ -0,0 +1,53 @@
package sandbox
import "context"
// SessionBootstrapper customises how ONE session's first sandbox is created.
// It exists for session fork: a forked session boots from a snapshot of its
// parent's sandbox and then rolls /workspace back to the fork point.
//
// It is optional. A nil bootstrapper leaves the lifecycle's behaviour
// unchanged, which is what every ordinary session gets.
//
// The lifecycle calls both methods inside the per-session lifecycle lock, so
// implementations need no locking of their own and cannot race with a
// concurrent resolve of the same session.
type SessionBootstrapper interface {
// TemplateOverride returns a template ID to create this session's sandbox
// from instead of the config's. An empty string means "no override".
//
// An error aborts the create: an implementation that cannot tell whether
// an override applies must not be silently treated as "no override",
// because that would boot a plain sandbox for a session the user expects
// to carry forked state.
TemplateOverride(ctx context.Context, key SessionSandboxKey) (string, error)
// AfterCreate runs once, immediately after the binding is written.
//
// Returning an error makes the lifecycle destroy the sandbox and delete
// the binding. That severity is deliberate: a half-bootstrapped fork looks
// completely normal but has the wrong baseline, and that silent wrongness
// is far worse than an honest failure the next resolve can retry from a
// clean slate.
AfterCreate(ctx context.Context, key SessionSandboxKey, handle RemoteSandboxHandle) error
}
// SessionCreateFailureHandler is an optional SessionBootstrapper extension.
//
// AfterCreate only runs when Create succeeded. A fork snapshot that the
// provider will never boot (deleted, unknown template) would otherwise stay
// on the session forever: every Resolve retries the same dead ID. The
// lifecycle calls this when Create used a TemplateOverride and still failed,
// so the bootstrapper can retire that snapshot and let the next Resolve use
// the ordinary template.
type SessionCreateFailureHandler interface {
OnCreateFailed(ctx context.Context, key SessionSandboxKey, createErr error)
}
// SessionBootstrapperWithClient rebinds a bootstrapper to the client that
// created the sandbox handle. AfterCreate runs under the session lifecycle
// lock, which is not reentrant, so implementations must talk to `client`
// (and the handle) directly instead of calling Resolve.
type SessionBootstrapperWithClient interface {
WithClient(client RemoteSandboxClient) SessionBootstrapper
}
@@ -0,0 +1,190 @@
package sandbox
import (
"context"
"errors"
"testing"
"github.com/stretchr/testify/require"
)
var testSessionKey = SessionSandboxKey{TenantID: 1, SessionID: "session-bootstrap"}
type recordingBootstrapper struct {
override string
overrideErr error
afterErr error
afterCalls int
afterHandleID string
}
func (b *recordingBootstrapper) TemplateOverride(
context.Context, SessionSandboxKey,
) (string, error) {
return b.override, b.overrideErr
}
func (b *recordingBootstrapper) AfterCreate(
_ context.Context, _ SessionSandboxKey, handle RemoteSandboxHandle,
) error {
b.afterCalls++
if handle != nil {
b.afterHandleID = handle.ID()
}
return b.afterErr
}
func newLifecycleForTest(t *testing.T) (*remoteSessionLifecycle, *fakeRemoteClient, SessionSandboxBindingStore) {
t.Helper()
client := newFakeRemoteClient(SandboxTypeCube)
store := NewMemorySessionSandboxBindingStore()
lc := newTestRemoteSessionLifecycle(
t, client, store, &fakeSessionExistenceChecker{exists: true},
)
return lc, client, store
}
func TestCreateAndBindUsesTemplateOverride(t *testing.T) {
lc, client, _ := newLifecycleForTest(t)
lc.bootstrapper = &recordingBootstrapper{override: "snap-1"}
_, err := lc.Resolve(context.Background(), testSessionKey)
require.NoError(t, err)
require.Equal(t, "snap-1", client.lastCreateRequest.TemplateID)
require.True(t, client.lastCreateRequest.FromSnapshot)
}
func TestCreateAndBindKeepsConfigTemplateWithoutOverride(t *testing.T) {
lc, client, _ := newLifecycleForTest(t)
lc.bootstrapper = &recordingBootstrapper{override: ""}
_, err := lc.Resolve(context.Background(), testSessionKey)
require.NoError(t, err)
require.Equal(t, lc.createRequest.TemplateID, client.lastCreateRequest.TemplateID)
require.False(t, client.lastCreateRequest.FromSnapshot)
}
// 最重要的一条:override 绝不能污染跨 session 复用的 l.createRequest。
func TestTemplateOverrideDoesNotMutateSharedCreateRequest(t *testing.T) {
lc, _, _ := newLifecycleForTest(t)
baseTemplate := lc.createRequest.TemplateID
lc.bootstrapper = &recordingBootstrapper{override: "snap-1"}
_, err := lc.Resolve(context.Background(), testSessionKey)
require.NoError(t, err)
require.Equal(t, baseTemplate, lc.createRequest.TemplateID,
"共享的 createRequest 被改了,同 config 下其他会话会从别人的快照启动")
}
func TestAfterCreateRunsWithTheNewHandle(t *testing.T) {
lc, _, _ := newLifecycleForTest(t)
b := &recordingBootstrapper{override: "snap-1"}
lc.bootstrapper = b
handle, err := lc.Resolve(context.Background(), testSessionKey)
require.NoError(t, err)
require.Equal(t, 1, b.afterCalls)
require.Equal(t, handle.ID(), b.afterHandleID)
}
// 全有或全无:引导失败必须销毁沙箱并删掉 binding,否则用户会在一个
// 「文件系统停在分叉时刻而不是分叉点」的沙箱里干活。
func TestAfterCreateFailureDestroysSandboxAndBinding(t *testing.T) {
lc, client, store := newLifecycleForTest(t)
lc.bootstrapper = &recordingBootstrapper{override: "snap-1", afterErr: errors.New("git reset failed")}
_, err := lc.Resolve(context.Background(), testSessionKey)
require.Error(t, err)
require.Contains(t, client.deleteIDs, client.lastCreatedID)
binding, getErr := store.Get(context.Background(), testSessionKey)
require.NoError(t, getErr)
require.Nil(t, binding, "引导失败后不得留下 binding")
}
func TestTemplateOverrideErrorAbortsCreate(t *testing.T) {
lc, client, _ := newLifecycleForTest(t)
lc.bootstrapper = &recordingBootstrapper{overrideErr: errors.New("db down")}
_, err := lc.Resolve(context.Background(), testSessionKey)
require.Error(t, err)
require.Empty(t, client.lastCreatedID, "读不到 override 就不该建沙箱")
}
type recordingCreateFailureHandler struct {
recordingBootstrapper
failedCalls int
lastFailErr error
}
func (b *recordingCreateFailureHandler) OnCreateFailed(_ context.Context, _ SessionSandboxKey, err error) {
b.failedCalls++
b.lastFailErr = err
}
func TestNilBootstrapperIsANoOp(t *testing.T) {
lc, client, _ := newLifecycleForTest(t)
lc.bootstrapper = nil
_, err := lc.Resolve(context.Background(), testSessionKey)
require.NoError(t, err)
require.Equal(t, lc.createRequest.TemplateID, client.lastCreateRequest.TemplateID)
}
// A missing fork snapshot must not be retried forever. Create using the
// override failed, so the bootstrapper has to be told — AfterCreate never
// runs, and abandon on git-reset-failure cannot fire.
func TestCreateFailureWithOverrideNotifiesBootstrapper(t *testing.T) {
lc, client, _ := newLifecycleForTest(t)
handler := &recordingCreateFailureHandler{
recordingBootstrapper: recordingBootstrapper{override: "snap-1"},
}
lc.bootstrapper = handler
client.createErr = NewRemoteError(
SandboxTypeCube, "Create", RemoteErrorKindNotFound, "template gone", nil,
)
_, err := lc.Resolve(context.Background(), testSessionKey)
require.Error(t, err)
require.Equal(t, 1, handler.failedCalls)
require.True(t, IsRemoteNotFound(handler.lastFailErr))
require.Empty(t, client.lastCreatedID)
}
func TestCreateFailureWithoutOverrideDoesNotNotifyBootstrapper(t *testing.T) {
lc, client, _ := newLifecycleForTest(t)
handler := &recordingCreateFailureHandler{}
lc.bootstrapper = handler
client.createErr = NewRemoteError(
SandboxTypeCube, "Create", RemoteErrorKindNotFound, "template gone", nil,
)
_, err := lc.Resolve(context.Background(), testSessionKey)
require.Error(t, err)
require.Zero(t, handler.failedCalls)
}
func TestTransientCreateFailureWithOverrideStillNotifiesBootstrapper(t *testing.T) {
lc, client, _ := newLifecycleForTest(t)
handler := &recordingCreateFailureHandler{
recordingBootstrapper: recordingBootstrapper{override: "snap-1"},
}
lc.bootstrapper = handler
client.createErr = NewRemoteError(
SandboxTypeCube, "Create", RemoteErrorKindUnavailable, "provider down", nil,
)
_, err := lc.Resolve(context.Background(), testSessionKey)
require.Error(t, err)
require.Equal(t, 1, handler.failedCalls)
}
Loaded 100 of 5767 files, more files were not shown because too many files have changed in this diff. Show more