From e39277a75e9457bb18e3695a1ea4bd110d6e7f32 Mon Sep 17 00:00:00 2001 From: nullptr-error <104547331+nullptr-error@users.noreply.github.com> Date: Thu, 3 Sep 2026 10:49:46 +0800 Subject: [PATCH] feat(sandbox): add tenant-configurable network policy (#2995) * feat(sandbox): add the tenant network policy with its secrets and validation Administrators need control over sandbox network access, so a named sandbox config gains a network policy block. It lives inside the existing config JSONB, so there is no schema change and old rows read back as the zero value. Both booleans are phrased so that the zero value IS the intended default -- outbound open, inbound closed. That makes "no network block" and "explicitly saved defaults" provably the same thing, and avoids a tri-state pointer where nil would have to mean "allowed" for egress and "closed" for ingress. Injected header values are credentials, so they ride the encrypt-at-rest and mask-on-read path EnvVars already uses instead of a parallel mechanism. One CloneWithSecrets traversal serves encrypt, decrypt and mask so the three directions cannot disagree about which fields are secret. Validation runs at save time because the alternative is failing at sandbox-create time, where the admin no longer has the form in front of them. It rejects both what a provider would refuse and what a provider would accept without doing what the admin meant -- a domain allowlist with no deny-all fallback still leaves every unresolved destination reachable. * feat(sandbox): apply the network policy on both providers, persist the inbound token Resolve the stored policy into one fully specified provider-neutral policy so that nothing downstream re-derives a default. Both booleans come out non-nil on every path, including the nil-tenant one, because a partially specified policy would let the adapters fall back to their providers' more permissive defaults. The three inversions (deny-egress to allow-internet, public-inbound, rule-deny to rule-allow) happen in exactly one place. Every sandbox-creating path carries it, so sessions, skill installs and the deep connectivity check all run under the same config's policy rather than each wiring its own. Inbound access defaults to CLOSED, deliberately stricter than either provider's own default: a sandbox URL reachable by anyone who learns the ID is not a reasonable default for a tenant's workspace. Closing it makes the provider issue a per-sandbox traffic token, and only at create time -- so the token is stored with the session binding and replayed through Connect on every reconnect. Without that, a sandbox that was paused on TTL or rebound after a restart would answer 403 on every exec and file read, and 403 classifies as an authentication error rather than NotFound, so the binding would never be replaced and the session would stay wedged. Connect therefore takes a request struct instead of a bare ID, which gives the token a single documented way in rather than implicit state inside an adapter. Metadata-based recovery is the one reconnect path with no binding to read the token from. Rather than adopt a sandbox that would be permanently 403, it is deleted and replaced -- but only for providers that have the credential at all, since Docker has no inbound token and its containers are still adoptable. go-e2b keeps the token and never sends it, so for E2B the data-plane RoundTripper attaches the header from a process-local registry. Cube's SDK already does this itself. * fix(sandbox): classify data-plane traffic by authority shape, not the configured domain isDataPlane suffix-matched the configured sandbox domain, which was wrong in both directions. Both required a configured proxy_url, so E2B Cloud's default usage was unaffected; the affected deployments are exactly the self-hosted and E2B-compatible ones the gateway exists for. A configured gateway could be silently ignored. sandbox_domain is optional for E2B -- MissingRequiredFields asks only for api_key and template_id -- and with it empty the check returned false for everything. The general form is worse than the empty case: go-e2b's envdBaseURL prefers the domain the control plane reported over the client-wide one, so the authority actually dialled need not appear in the config at all. The failure is quiet whenever public DNS happens to resolve the sandbox domain, and the operator believes traffic is passing through a gateway that never sees it. Control-plane calls could be sent to the gateway. E2B's own defaults put the API host under the sandbox domain (api.e2b.app beneath e2b.app), so the suffix match classified every Create, Connect and List as data-plane traffic. That is loud where the gateway does not serve the API, but where it proxies both planes it succeeds while downgrading an X-API-Key request to plaintext for an http:// gateway. Cube was immune to the first problem, since it requires both fields, but not to this one. Classify on the "-." shape both SDKs generate, using the SandboxIDFromDataPlaneHost helper that token injection on the very same request already relies on -- so routing and injection now agree by construction instead of applying two different rules. That helper exists precisely because the configured domain is unreliable here; it was simply never used for the routing half. The control host stays as an explicit exclusion. The shape test already rejects api., so this only covers an API host that itself wears the shape, such as 8080-api.example.com. One existing assertion was replaced rather than kept: the E2B pool test proved that the Cube fields were ignored by asserting a cube.app authority was not data-plane traffic, which tested the domain matching rather than the field selection. It now asserts the transport dials the E2B gateway address and not the Cube one. * feat(sandbox): add the network policy editor to the sandbox config drawer The policy sits in the runtime step, directly under the settings it constrains, rather than in a step of its own. The existing execution timeouts were compressed into a two-column grid to make room, keeping each field's own label and its own tip -- the reason they were one per row was that three unlabelled numbers sharing a footnote gave no clue which one you were editing, and two columns with per-field tips does not regress that. Provider-specific sections are shown only for the backend that has them: the Cube L7 rule cards, E2B's per-host header transforms, and for Docker just the bridge/none selector, since Docker can only express the overall switch. Injected header values are write-only. A stored one shows as configured and is preserved when the input is left blank, which is how env-var secrets already behave. Renaming a rule or a header is the case worth care: the merge indexes credentials on the rule-and-header pair, so a rename means the old value can no longer be recovered. One helper decides both the placeholder text and whether the payload re-attaches the value, so the form cannot claim a credential is kept while the save blanks it. The add buttons use keys of their own instead of reusing the env-var table's "add variable", which read wrongly under a list of network destinations and which the i18n key check cannot catch, since the key exists in every bundle. * docs(sandbox): document the network policy and its inbound default change The existing network bullet described the pre-feature state -- both providers open by default, tunable only through the neutral policy at create time -- which is no longer true of the defaults or of the admin-facing surface. Three things needed writing down rather than restating. The inbound default flips from publicly reachable to credential-required. A deployment that relies on a browser or an external service reaching a sandbox port directly, rather than going through WeKnora, has to opt back in on that config. The binding store now holds a bearer credential in plaintext. Leaving it unencrypted was a deliberate trade -- per-reconnect crypto on the hot path against Redis's own access control -- and the trade is only sound if the requirement is actually stated, along with the code-side constraint it depends on: a binding or a handle is never logged whole, only the sandbox ID and whether a credential is present. On binding loss, a closed-inbound Cube or E2B config no longer adopts its old sandbox by metadata. The token went with the binding and the provider will not reissue it, so adoption would produce a session that answers 403 on every data-plane call with no way back. The sandbox is deleted and rebuilt, which costs the /workspace scratch. Docker has no such credential and still adopts. * fix(sandbox): fail closed when a closed-inbound create has no traffic token A Cube/E2B sandbox created without the inbound token would be bound anyway, then 403 on every data-plane call as an unreplaceable authentication error. Refuse the create, destroy the sandbox, and stop Docker from persisting inbound/egress radios it cannot honour. Canonicalize IPv4 /0 deny-all onto 0.0.0.0/0 and reject CR/LF in injected header names and values. * fix(sandbox): satisfy pre-push lint on the network policy files Unexport the data-plane host parser, drop file-level package docs that revive rejected, and lowercase error-string prefixes that staticcheck ST1005 treats as capitalized English. * fix(sandbox): persist rotated inbound tokens and stop misreporting restricted egress Connect can reissue the traffic token after pause/resume; write it back onto the binding so a restart does not restore a stale credential that 403s and cannot be replaced. Restore the volume-support i18n key, map Docker network_mode=none onto deny-egress, inject the E2B inbound header without a gateway pool, and fold header names when merging redacted secrets. --------- Co-authored-by: hailongzhao Co-authored-by: wizardchen --- docs/agent-skills.md | 6 +- frontend/src/api/system/index.ts | 44 ++ ...SandboxConfigEditorDrawer.network.test.mjs | 358 +++++++++ .../components/SandboxConfigEditorDrawer.vue | 692 ++++++++++++++++-- frontend/src/i18n/locales/en-US.ts | 49 +- frontend/src/i18n/locales/ko-KR.ts | 51 +- frontend/src/i18n/locales/ru-RU.ts | 51 +- frontend/src/i18n/locales/zh-CN.ts | 49 +- .../service/tenant_sandbox_config.go | 21 + .../service/tenant_sandbox_config_test.go | 39 + internal/handler/sandbox_check.go | 47 +- internal/handler/sandbox_check_test.go | 97 +++ internal/sandbox/cube_integration_test.go | 2 +- internal/sandbox/cube_mock_test.go | 20 +- internal/sandbox/cube_remote_client.go | 106 ++- internal/sandbox/cube_remote_client_test.go | 164 ++++- internal/sandbox/docker_integration_test.go | 4 +- internal/sandbox/docker_remote_client.go | 8 +- internal/sandbox/docker_remote_client_test.go | 6 +- internal/sandbox/e2b_remote_client.go | 101 ++- internal/sandbox/e2b_remote_client_test.go | 127 +++- internal/sandbox/gateway_transport.go | 135 +++- internal/sandbox/gateway_transport_test.go | 101 ++- internal/sandbox/inbound_token_registry.go | 91 +++ .../sandbox/inbound_token_registry_test.go | 171 +++++ internal/sandbox/langfuse.go | 6 +- internal/sandbox/remote_client.go | 119 ++- internal/sandbox/remote_client_test.go | 2 +- internal/sandbox/remote_fake_test.go | 108 ++- internal/sandbox/sandbox.go | 7 + internal/sandbox/session_binding.go | 58 ++ internal/sandbox/session_binding_redis.go | 56 ++ .../sandbox/session_binding_redis_test.go | 5 + internal/sandbox/session_binding_test.go | 93 +++ internal/sandbox/session_lifecycle.go | 139 +++- internal/sandbox/session_lifecycle_test.go | 267 +++++++ internal/sandbox/session_manager.go | 12 +- internal/sandbox/session_manager_test.go | 28 + internal/sandbox/tenant_config.go | 103 +++ internal/sandbox/tenant_config_test.go | 268 ++++++- internal/types/config_redaction.go | 73 ++ .../types/config_redaction_sandbox_test.go | 144 ++++ internal/types/sandbox_network_policy.go | 551 ++++++++++++++ internal/types/sandbox_network_policy_test.go | 486 ++++++++++++ internal/types/tenant.go | 27 +- 45 files changed, 4837 insertions(+), 255 deletions(-) create mode 100644 frontend/src/components/SandboxConfigEditorDrawer.network.test.mjs create mode 100644 internal/sandbox/inbound_token_registry.go create mode 100644 internal/sandbox/inbound_token_registry_test.go create mode 100644 internal/types/sandbox_network_policy.go create mode 100644 internal/types/sandbox_network_policy_test.go diff --git a/docs/agent-skills.md b/docs/agent-skills.md index 0d27e950..7b84b294 100644 --- a/docs/agent-skills.md +++ b/docs/agent-skills.md @@ -190,10 +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。 -- **单机部署**:不配置 `REDIS_ADDR`(或 Lite 模式)时使用进程内内存 binding,仅限单实例。进程重启会丢失 session→sandbox 映射,remote 侧沙箱成为孤儿(注意:**TTL 到期只会暂停、不会销毁**,见下)。 +- **⚠️ 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 概念,照旧领养。 - **切换 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` 过滤会把另一份配置的沙箱一并误删。 -- **网络策略**:`cube` 与 `e2b` 默认开启公网出口和 public traffic,可在 create 时通过 provider-neutral `RemoteNetworkPolicy`(`AllowInternetAccess` / `AllowPublicTraffic` / `AllowOut` / `DenyOut`)精细化配置;两个 adapter 都实现了同一契约。 +- **网络策略**:每份具名沙箱配置带一块 `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`),表单不展示入站/出站 radio,避免切到 Cube/E2B 时把「公网可访问」带过去。**改策略只影响之后新建的沙箱**:本期不做运行中热更新。 +- **⚠️ 升级行为变更**:入站默认从「公网可达」改为「要求凭证」。如果某个部署依赖浏览器直连沙箱端口(而不是经 WeKnora 代理),需要在该沙箱配置的「网络策略 → 入站访问」里改成「公网可访问」。 ## Agent 工具 diff --git a/frontend/src/api/system/index.ts b/frontend/src/api/system/index.ts index 5b5e6434..c8b20685 100644 --- a/frontend/src/api/system/index.ts +++ b/frontend/src/api/system/index.ts @@ -766,6 +766,7 @@ export interface SandboxConfig { volume_mount?: SandboxVolumeMountConfig skill_image?: SandboxSkillImage skill_rollout?: 'next_turn' | 'new_session' + network?: SandboxNetworkPolicy cube?: SandboxCubeConfig e2b?: SandboxE2BConfig docker?: SandboxDockerConfig @@ -785,6 +786,49 @@ export interface SandboxDockerConfig { http_timeout_sec?: number } +/** One injected credential header on a Cube L7 rule. */ +export interface SandboxCubeHeaderInject { + header: string + /** Masked as '***' in responses; send the placeholder back to keep it. */ + secret?: string + /** Defaults to '${SECRET}' server-side. */ + format?: string +} + +/** One CubeEgress L7 rule. Match fields are AND-ed; methods are OR-ed. */ +export interface SandboxCubeEgressRule { + name: string + scheme?: string + sni?: string + host?: string + methods?: string[] + path?: string + /** Absent means allow. A deny rule still needs host or sni. */ + deny?: boolean + audit?: string + inject?: SandboxCubeHeaderInject[] +} + +/** One E2B per-host request transform. host must also be in allow_out. */ +export interface SandboxE2BHostRule { + host: string + /** Values are masked as '***' in responses. */ + headers?: Record +} + +/** + * Network policy for every sandbox created from this config. Every field + * absent means the default: egress allowed, inbound requires a credential. + */ +export interface SandboxNetworkPolicy { + deny_egress_by_default?: boolean + allow_public_inbound?: boolean + allow_out?: string[] + deny_out?: string[] + cube_rules?: SandboxCubeEgressRule[] + e2b_host_rules?: SandboxE2BHostRule[] +} + /** `ok: null` means the probe was not executed in this run. */ export interface SandboxCheckItem { name: string diff --git a/frontend/src/components/SandboxConfigEditorDrawer.network.test.mjs b/frontend/src/components/SandboxConfigEditorDrawer.network.test.mjs new file mode 100644 index 00000000..18e4ffc6 --- /dev/null +++ b/frontend/src/components/SandboxConfigEditorDrawer.network.test.mjs @@ -0,0 +1,358 @@ +import assert from 'node:assert/strict' +import { readFileSync } from 'node:fs' +import test from 'node:test' + +const source = readFileSync( + new URL('./SandboxConfigEditorDrawer.vue', import.meta.url), 'utf8') + +test('network policy lives in the runtime step, right below the runtime config', () => { + const runtimeSections = source.indexOf("currentStepKey === 'runtime'") + const networkSection = source.indexOf('settings.sandbox.sectionNetwork') + const envSection = source.indexOf('settings.sandbox.sectionEnvironment') + + assert.ok(runtimeSections !== -1, 'runtime step must exist') + assert.ok(networkSection !== -1, 'network policy section must exist') + assert.ok( + networkSection > runtimeSections && networkSection < envSection, + 'network policy must sit between the runtime config and the env vars', + ) + assert.ok( + !source.includes("currentStepKey === 'network'"), + 'network policy must not become a fourth wizard step', + ) +}) + +test('runtime numbers are laid out two per row with per-field tips', () => { + const runtimeBlock = source.slice( + source.indexOf('settings.sandbox.sectionRuntime'), + source.indexOf('settings.sandbox.sectionNetwork'), + ) + assert.ok( + runtimeBlock.includes('form-grid form-grid--two'), + 'timeouts must be compressed into the two-column grid', + ) + // Each number keeps its own sentence; the previous layout put those in + // block paragraphs, which is what made the step so tall. + assert.ok( + runtimeBlock.includes(":tips=\"$t('settings.sandbox.httpTimeoutHelp')\""), + 'http timeout keeps its own explanation, now inline', + ) + assert.ok( + runtimeBlock.includes(":tips=\"$t('settings.sandbox.sandboxTtlHelp')\""), + 'sandbox TTL keeps its own explanation, now inline', + ) + for (const key of [ + 'dockerCpuLimitHelp', + 'dockerMemoryLimitHelp', + 'dockerPidsLimitHelp', + ]) { + assert.ok( + runtimeBlock.includes(`:tips="$t('settings.sandbox.${key}')"`), + `${key} must remain attached to its compressed field`, + ) + } +}) + +test('docker network mode moved into the network policy section', () => { + const networkBlock = source.slice(source.indexOf('settings.sandbox.sectionNetwork')) + assert.ok( + networkBlock.includes('settings.sandbox.dockerNetworkMode'), + 'the docker bridge/none selector belongs with the other network controls', + ) + const runtimeBlock = source.slice( + source.indexOf('settings.sandbox.sectionRuntime'), + source.indexOf('settings.sandbox.sectionNetwork'), + ) + assert.ok( + !runtimeBlock.includes('settings.sandbox.dockerNetworkMode'), + 'and must no longer be duplicated in the runtime config', + ) +}) + +test('inbound defaults to credential-required and egress to allowed', () => { + assert.match( + source, + /const allowPublicInbound = ref\(false\)/, + 'inbound closed is the default', + ) + assert.match( + source, + /const denyEgressByDefault = ref\(false\)/, + 'egress allowed is the default', + ) +}) + +test('injected header values are password inputs and survive an untouched edit', () => { + const payloadBlock = source.slice( + source.indexOf('function collectNetworkPolicy'), + source.indexOf('function close'), + ) + const templateBlock = source.slice(0, source.indexOf('