diff --git a/docs/agent-skills.md b/docs/agent-skills.md index d8503308..112f7840 100644 --- a/docs/agent-skills.md +++ b/docs/agent-skills.md @@ -190,12 +190,12 @@ Docker、CubeSandbox、E2B 均通过同一套空间配置 CRUD、连接检查和 - **binding store 自动选择**:进程根据通用 `REDIS_ADDR` 是否配置自动决定绑定存储;Redis key 命名空间复用 `WEKNORA_REDIS_NAMESPACE`,未设置时为 `weknora`。 - **多机部署(生产推荐)**:配置 `REDIS_ADDR`。多副本共享同一 session 的沙箱绑定,通过 Redis SET NX + 可续租分布式锁串行化 create / recover / delete。 -- **⚠️ binding store 现在保存承载凭证,必须做访问控制**:入站关闭(默认)时,沙箱的 traffic token 随绑定一起明文存放——它是访问该沙箱公网 URL 的凭证,读到它就等于能访问那个沙箱暴露的端口。因此**存放绑定的 Redis 必须启用认证并限制网络可达范围**,不能与不受信任的服务共用实例。这里不加密是有意的:每次重连都要解密会把开销加在热路径上,而 Redis 本身的访问控制是更合适的边界。代码侧的对应约束是**绝不整体打印绑定或 handle**(日志里只出现 `sandbox_id` 与凭证的有无),改动 `session_binding.go` / 适配器日志时请一并保持。 -- **单机部署**:不配置 `REDIS_ADDR`(或 Lite 模式)时使用进程内内存 binding,仅限单实例。进程重启会丢失 session→sandbox 映射,remote 侧沙箱成为孤儿(注意:**TTL 到期只会暂停、不会销毁**,见下)。绑定丢失后,**入站关闭(默认)的 Cube / E2B 配置不会再按 metadata 领养旧沙箱**——旧沙箱的 traffic token 随绑定一起没了且 provider 不会重发,领养只会得到一个每次数据面调用都 403 的死会话。lifecycle 会直接删掉它再新建,`/workspace` 里的临时文件随之丢失。Docker 没有 traffic token 概念,照旧领养。 +- **⚠️ binding store 现在保存承载凭证,必须做访问控制**:入站一律要求凭证,Cube / E2B 的 traffic token 随绑定一起明文存放——它是访问该沙箱公网 URL 的凭证,读到它就等于能访问那个沙箱暴露的端口。因此**存放绑定的 Redis 必须启用认证并限制网络可达范围**,不能与不受信任的服务共用实例。这里不加密是有意的:每次重连都要解密会把开销加在热路径上,而 Redis 本身的访问控制是更合适的边界。代码侧的对应约束是**绝不整体打印绑定或 handle**(日志里只出现 `sandbox_id` 与凭证的有无),改动 `session_binding.go` / 适配器日志时请一并保持。 +- **单机部署**:不配置 `REDIS_ADDR`(或 Lite 模式)时使用进程内内存 binding,仅限单实例。进程重启会丢失 session→sandbox 映射,remote 侧沙箱成为孤儿(注意:**TTL 到期只会暂停、不会销毁**,见下)。绑定丢失后,**Cube / E2B 配置不会再按 metadata 领养旧沙箱**——旧沙箱的 traffic token 随绑定一起没了且 provider 不会重发,领养只会得到一个每次数据面调用都 403 的死会话。lifecycle 会直接删掉它再新建,`/workspace` 里的临时文件随之丢失。Docker 没有 traffic token 概念,照旧领养。 - **切换 provider**:不同 provider 的 sandbox ID 不通用。智能体改选配置只影响之后新建的沙箱,已有沙箱继续按 session pin 回收。 - **⚠️ 孤儿沙箱不会被 TTL 自动回收**:会话沙箱创建时使用 `onTimeout=pause` + `autoResume=true`(见 `buildSessionCreateRequest`),因此 **TTL 到期是"暂停"而非"销毁"**——保留状态本就是 pause 的目的。加上 CAS 换绑会把旧 sandboxID 从 binding store 覆盖掉,被替换的沙箱会变成**无人知晓 ID 的 paused 孤儿**,持续占用快照存储与费用。删除会话(`session.go` 的 destroyer)与 lifecycle 的惰性 orphan cleanup 都覆盖不到这种情况。生产环境需依赖按 metadata 列举并与 binding 对账的清理任务来回收(`internal/sandbox/orphan_reaper.go`),且**必须显式包含 `paused` 状态**。对账维度是 `(tenant_id, config_id)` 而非仅 `tenant_id`:同一工作区的两份配置可能指向**同一个 provider 账号**(例如同一个 E2B Key 只差模板),只按 `tenant_id` 过滤会把另一份配置的沙箱一并误删。 -- **网络策略**:每份具名沙箱配置带一块 `network` 策略,作用于该配置下所有沙箱(会话、技能安装、深度检查共用同一份)。默认**出站放行、入站关闭**——入站关闭意味着沙箱公网 URL 必须携带创建时签发的 traffic token,WeKnora 自身的 envd 链路会自动携带(Cube 由 SDK 附加,E2B 由 WeKnora 的数据面 transport 附加)。若 Cube / E2B 在入站关闭时没有签发 token,create 会失败并销毁该沙箱,而不是把空凭证写入 binding(数据面 403 会被当成 authentication,会话会永久卡住)。管理员可配置 allow / deny 列表,Cube 额外支持 CubeEgress L7 规则(scheme / sni / host / method / path + 审计 + header 注入),E2B 额外支持按 host 注入 header。Docker 只能整体开关(`bridge` / `none`)。入站在表单里不可改,保存时一律写入「要求凭证」。**改策略只影响之后新建的沙箱**:本期不做运行中热更新。 -- **⚠️ 升级行为变更**:入站默认从「公网可达」改为「要求凭证」。浏览器或外部服务若要直连沙箱端口,不能再从管理界面打开入站。 +- **网络策略**:每份具名沙箱配置带一块 `network` 策略,作用于该配置下所有沙箱(会话、技能安装、深度检查共用同一份)。默认**出站放行**;**入站一律要求凭证**——沙箱公网 URL 必须携带创建时签发的 traffic token,WeKnora 自身的 envd 链路会自动携带(Cube 由 SDK 附加,E2B 由 WeKnora 的数据面 transport 附加)。若 Cube / E2B 没有签发 token,create 会失败并销毁该沙箱,而不是把空凭证写入 binding(数据面 403 会被当成 authentication,会话会永久卡住)。管理员可配置 allow / deny 列表,Cube 额外支持 CubeEgress L7 规则(scheme / sni / host / method / path + 审计 + header 注入),E2B 额外支持按 host 注入 header。Docker 只能整体开关(`bridge` / `none`)。表单不再提供入站开关;解析忽略已存的 `allow_public_inbound`,保存时清掉该字段。**改策略只影响之后新建的沙箱**:本期不做运行中热更新。 +- **⚠️ 升级行为变更**:入站从「公网可达」改为「一律要求凭证」。浏览器或外部服务不能再直连沙箱端口;管理界面和 API 都打不开入站。 ## Agent 工具 diff --git a/frontend/src/api/system/index.ts b/frontend/src/api/system/index.ts index c8b20685..9e501ca6 100644 --- a/frontend/src/api/system/index.ts +++ b/frontend/src/api/system/index.ts @@ -817,11 +817,13 @@ export interface SandboxE2BHostRule { } /** - * Network policy for every sandbox created from this config. Every field - * absent means the default: egress allowed, inbound requires a credential. + * Network policy for every sandbox created from this config. Absent fields + * mean egress allowed. Inbound is always credential-required: + * allow_public_inbound is accepted then ignored/cleared. */ export interface SandboxNetworkPolicy { deny_egress_by_default?: boolean + /** Ignored. Inbound is always credential-required. */ allow_public_inbound?: boolean allow_out?: string[] deny_out?: string[] diff --git a/internal/sandbox/inbound_token_registry.go b/internal/sandbox/inbound_token_registry.go index d06afa95..a997aefb 100644 --- a/internal/sandbox/inbound_token_registry.go +++ b/internal/sandbox/inbound_token_registry.go @@ -1,7 +1,7 @@ // Inbound traffic-token registry. // -// A sandbox created with public inbound access closed only accepts requests -// carrying its per-sandbox traffic token. Cube's SDK attaches that header +// 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 WeKnora owns on that path: the data-plane RoundTripper. @@ -32,8 +32,8 @@ func NewInboundTokenRegistry() *InboundTokenRegistry { return &InboundTokenRegistry{} } -// Put records the token for sandboxID. An empty token means the sandbox has -// public inbound access, so nothing is stored. +// 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 @@ -66,8 +66,8 @@ func (r *InboundTokenRegistry) Delete(sandboxID string) { // 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 sandboxes WeKnora -// created with inbound closed are in it. +// fire. The registry lookup is the real authority — only Cube/E2B sandboxes +// whose token WeKnora recorded are in it. func sandboxIDFromDataPlaneHost(host string) string { host = strings.ToLower(strings.TrimSpace(host)) if host == "" { diff --git a/internal/sandbox/remote_client.go b/internal/sandbox/remote_client.go index 0464dbbf..aa6ba3b5 100644 --- a/internal/sandbox/remote_client.go +++ b/internal/sandbox/remote_client.go @@ -145,9 +145,10 @@ type RemoteCreateRequest struct { // 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. nil uses WeKnora's default of closed inbound access, -// deliberately stricter than either provider's own default; false hides -// the sandbox behind a per-sandbox traffic access token. +// 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 @@ -180,9 +181,9 @@ func (p RemoteNetworkPolicy) DeniesEgressByDefault() bool { return types.DenyOutCoversAllIPv4(p.DenyOut) } -// RemoteInboundTokenCarrier is implemented by handles whose sandbox was -// created with public inbound access closed. It is an optional capability in -// the same spirit as RemoteSnapshotManager: Docker has no such credential. +// 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 } diff --git a/internal/sandbox/session_binding.go b/internal/sandbox/session_binding.go index 50829385..28c36534 100644 --- a/internal/sandbox/session_binding.go +++ b/internal/sandbox/session_binding.go @@ -61,7 +61,7 @@ type SessionSandboxBinding struct { StaleAt *time.Time `json:"stale_at,omitempty"` // TrafficAccessToken is the per-sandbox inbound credential issued at - // create time when the config closed public inbound access. + // 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 @@ -71,8 +71,8 @@ type SessionSandboxBinding struct { // these bindings must be access-controlled — it already holds the // session-to-sandbox ownership anyway. Never log the binding payload. // - // Empty for sandboxes created with public inbound allowed, and for - // bindings written before this field existed; both are valid. + // Empty for Docker (no such credential) and for bindings written before + // this field existed; both are valid. TrafficAccessToken string `json:"traffic_access_token,omitempty"` } diff --git a/internal/sandbox/session_lifecycle.go b/internal/sandbox/session_lifecycle.go index 4edaeb36..304ea8f1 100644 --- a/internal/sandbox/session_lifecycle.go +++ b/internal/sandbox/session_lifecycle.go @@ -298,10 +298,10 @@ func persistInboundToken( } } -// inboundTokenRequired reports whether this config closed public inbound -// access, which makes the per-sandbox traffic token mandatory on every -// data-plane call. nil means the policy was never resolved (baseline configs -// and tests), and those predate the token entirely. +// inboundTokenRequired reports whether the resolved create policy requires +// the per-sandbox traffic token on every data-plane call. Production resolve +// always sets AllowPublicTraffic=false. nil means the policy was never +// resolved (baseline configs and some tests) and predates the token. func (l *remoteSessionLifecycle) inboundTokenRequired() bool { allowPublic := l.createRequest.Network.AllowPublicTraffic return allowPublic != nil && !*allowPublic diff --git a/internal/sandbox/tenant_config.go b/internal/sandbox/tenant_config.go index 70c61964..90bc1fad 100644 --- a/internal/sandbox/tenant_config.go +++ b/internal/sandbox/tenant_config.go @@ -287,12 +287,17 @@ func overrideSeconds(dst *time.Duration, seconds int) { } // resolveNetworkPolicy turns the stored, admin-facing policy into the -// provider-facing one. This is the single place the three inversions happen: +// provider-facing one. This is the single place the inversions happen: // // - DenyEgressByDefault -> AllowInternetAccess=false -// - AllowPublicInbound -> AllowPublicTraffic // - CubeEgressRule.Deny -> RemoteCubeEgressRule.Allow // +// Inbound is always closed (AllowPublicTraffic=false). Stored +// AllowPublicInbound is dropped at the persistence boundary already +// (mergeNetworkPolicyForUpdate); ignoring it again here means even a caller +// that reaches this function without going through that merge cannot open +// the sandbox URL. +// // A nil stored policy is not "unset": it resolves to WeKnora's default of // egress allowed and inbound closed, so every downstream consumer sees one // fully specified policy and nobody re-derives the default. @@ -301,7 +306,6 @@ func resolveNetworkPolicy(stored *types.SandboxNetworkPolicy) RemoteNetworkPolic inboundPublic := false if stored != nil { allowEgress = !stored.DenyEgressByDefault - inboundPublic = stored.AllowPublicInbound } policy := RemoteNetworkPolicy{ AllowInternetAccess: &allowEgress, diff --git a/internal/sandbox/tenant_config_test.go b/internal/sandbox/tenant_config_test.go index af94f67c..287b60e9 100644 --- a/internal/sandbox/tenant_config_test.go +++ b/internal/sandbox/tenant_config_test.go @@ -125,7 +125,7 @@ func TestResolveEffectiveConfigTranslatesNetworkPolicy(t *testing.T) { "DenyEgressByDefault must flip the provider's allow switch off") require.NotNil(t, got.Network.AllowPublicTraffic) require.False(t, *got.Network.AllowPublicTraffic, - "inbound stays closed unless the admin opened it") + "inbound is always credential-required") require.Equal(t, []string{"*.example.com"}, got.Network.AllowOut) require.Equal(t, []string{"0.0.0.0/0"}, got.Network.DenyOut) require.Equal(t, "api.example.com", got.Network.E2BHostRules[0].Host) @@ -199,7 +199,7 @@ func TestResolveEffectiveConfigLeavesDenyOutAloneWhenEgressOpen(t *testing.T) { require.False(t, got.Network.DeniesEgressByDefault()) } -func TestResolveEffectiveConfigAllowsPublicInboundWhenConfigured(t *testing.T) { +func TestResolveEffectiveConfigIgnoresStoredPublicInbound(t *testing.T) { tenantCfg := completeE2BTenantConfig() tenantCfg.Network = &types.SandboxNetworkPolicy{AllowPublicInbound: true} @@ -207,7 +207,8 @@ func TestResolveEffectiveConfigAllowsPublicInboundWhenConfigured(t *testing.T) { require.NoError(t, err) require.NotNil(t, got.Network.AllowPublicTraffic) - require.True(t, *got.Network.AllowPublicTraffic) + require.False(t, *got.Network.AllowPublicTraffic, + "inbound stays credential-required even if a stored row asked for public access") } func TestResolveEffectiveConfigDefaultsNetworkToEgressOpenInboundClosed(t *testing.T) { diff --git a/internal/types/config_redaction.go b/internal/types/config_redaction.go index ae3a5a3f..c7e55776 100644 --- a/internal/types/config_redaction.go +++ b/internal/types/config_redaction.go @@ -409,6 +409,9 @@ func mergeNetworkPolicyForUpdate( return nil } out := incoming.CloneWithSecrets(func(value string) string { return value }) + // Inbound is always credential-required. Accept the wire field so old + // clients still decode, then drop it so it cannot persist or reopen. + out.AllowPublicInbound = false if existing == nil { return out } diff --git a/internal/types/config_redaction_sandbox_test.go b/internal/types/config_redaction_sandbox_test.go index bf10f58b..bf438271 100644 --- a/internal/types/config_redaction_sandbox_test.go +++ b/internal/types/config_redaction_sandbox_test.go @@ -200,6 +200,19 @@ func TestMergeSandboxConfigForUpdateMatchesInjectedHeadersCaseInsensitively(t *t "host whitespace and header case must not drop the stored secret") } +func TestMergeSandboxConfigForUpdateClearsPublicInbound(t *testing.T) { + incoming := &TenantSandboxConfig{ + Network: &SandboxNetworkPolicy{AllowPublicInbound: true, AllowOut: []string{"1.1.1.1"}}, + } + + out := MergeSandboxConfigForUpdate(incoming, nil) + + require.NotNil(t, out.Network) + require.False(t, out.Network.AllowPublicInbound, + "inbound cannot be opened from a saved payload; the field is accepted then cleared") + require.Equal(t, []string{"1.1.1.1"}, out.Network.AllowOut) +} + func TestMergeSandboxConfigForUpdateDropsNetworkWhenIncomingOmitsIt(t *testing.T) { existing := &TenantSandboxConfig{ Network: &SandboxNetworkPolicy{DenyEgressByDefault: true}, diff --git a/internal/types/sandbox_network_policy.go b/internal/types/sandbox_network_policy.go index e1bc72f8..a5a89292 100644 --- a/internal/types/sandbox_network_policy.go +++ b/internal/types/sandbox_network_policy.go @@ -15,20 +15,19 @@ import ( ) // SandboxNetworkPolicy is the admin-facing network policy for one sandbox -// config. Both booleans are deliberately phrased so that the zero value IS -// the intended default — outbound open, inbound closed. That keeps a missing -// JSON block and an explicitly saved "default" policy identical, and avoids -// the tri-state pointer trap where nil would mean "allowed" for egress and -// "closed" for ingress. +// config. DenyEgressByDefault is phrased so the zero value IS the intended +// default (outbound open). Inbound is not a switch: it is always +// credential-required. AllowPublicInbound stays on the wire so old payloads +// still decode, then is cleared on save and ignored at resolve. type SandboxNetworkPolicy struct { // DenyEgressByDefault installs a 0.0.0.0/0 deny-all, after which only // AllowOut (and L7 rule targets) can reach the network. false allows // public egress, which is what skill installs need. DenyEgressByDefault bool `json:"deny_egress_by_default,omitempty"` - // AllowPublicInbound exposes the sandbox's public URL without a - // credential. false requires every inbound request to carry the - // per-sandbox traffic access token. + // AllowPublicInbound is accepted on the wire for old payloads and then + // cleared. Inbound is always credential-required; a true value has no + // runtime effect. AllowPublicInbound bool `json:"allow_public_inbound,omitempty"` // AllowOut accepts IPv4, IPv4 CIDR, a DNS name, or a single-label