fix(sandbox): hide inbound controls and let Cube L7 rules be reordered

The editor no longer exposes inbound access; saves omit
allow_public_inbound so the zero value (require credentials) is stored.
Cube L7 rules can be moved so first-match-wins order is explicit.
main
hailongzhao 2026-09-03 12:04:55 +08:00 committed by lyingbug
parent efb7e2aea2
commit 52d1551165
7 changed files with 123 additions and 66 deletions

View File

@ -194,8 +194,8 @@ Docker、CubeSandbox、E2B 均通过同一套空间配置 CRUD、连接检查和
- **单机部署**:不配置 `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`),表单不展示入站/出站 radio,避免切到 Cube/E2B 时把「公网可访问」带过去。**改策略只影响之后新建的沙箱**:本期不做运行中热更新。
- **⚠️ 升级行为变更**:入站默认从「公网可达」改为「要求凭证」。如果某个部署依赖浏览器直连沙箱端口(而不是经 WeKnora 代理),需要在该沙箱配置的「网络策略 → 入站访问」里改成「公网可访问」。
- **网络策略**:每份具名沙箱配置带一块 `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`)。入站在表单里不可改,保存时一律写入「要求凭证」。**改策略只影响之后新建的沙箱**:本期不做运行中热更新。
- **⚠️ 升级行为变更**:入站默认从「公网可达」改为「要求凭证」。浏览器或外部服务若要直连沙箱端口,不能再从管理界面打开入站。
## Agent 工具

View File

@ -69,11 +69,25 @@ test('docker network mode moved into the network policy section', () => {
)
})
test('inbound defaults to credential-required and egress to allowed', () => {
assert.match(
test('inbound is always credential-required and never shown', () => {
assert.doesNotMatch(
source,
/const allowPublicInbound = ref\(false\)/,
'inbound closed is the default',
/settings\.sandbox\.inboundAccess/,
'the inbound radio must not appear in the form',
)
assert.doesNotMatch(
source,
/allowPublicInbound/,
'the form must not keep a public-inbound control',
)
const payloadBlock = source.slice(
source.indexOf('function collectNetworkPolicy'),
source.indexOf('function close'),
)
assert.doesNotMatch(
payloadBlock,
/allow_public_inbound/,
'saves must omit allow_public_inbound so the zero value (require credentials) is stored',
)
assert.match(
source,
@ -206,20 +220,15 @@ test('docker payload omits hidden allow and deny lists', () => {
)
})
test('docker hides inbound and egress radios that it cannot honour', () => {
test('docker hides egress radios that it cannot honour', () => {
const networkBlock = source.slice(
source.indexOf('settings.sandbox.sectionNetwork'),
source.indexOf('settings.sandbox.sectionEnvironment'),
)
assert.match(
networkBlock,
/v-if="backend !== 'docker'"[\s\S]*settings\.sandbox\.inboundAccess[\s\S]*settings\.sandbox\.egressDefault/,
'inbound and egress radios must not render for Docker',
)
assert.match(
source,
/function selectBackend[\s\S]*crossingDocker[\s\S]*allowPublicInbound\.value = false/,
'switching across Docker must not carry a public-inbound flag into Cube/E2B',
/v-if="backend !== 'docker'"[\s\S]*settings\.sandbox\.egressDefault/,
'egress radios must not render for Docker',
)
})
@ -274,6 +283,35 @@ test('cube L7 rules collapse to a name bar', () => {
false,
'E2B expanded body must not grow with a second delete control',
)
assert.match(
cubeRulesBlock,
/:key="rule\.key"/,
'Cube rules must key on a stable id so reorder does not remount the open card',
)
assert.match(
cubeRulesBlock,
/moveCubeRule\(index, -1\)/,
'the name bar must offer move-up',
)
assert.match(
cubeRulesBlock,
/moveCubeRule\(index, 1\)/,
'the name bar must offer move-down',
)
const mover = source.match(
/function moveCubeRule\(index: number, delta: number\) \{\n([\s\S]*?)\n\}/,
)
assert.ok(mover, 'moveCubeRule must exist')
const move = new Function('cubeRules', 'index', 'delta', `${mover[1]}`)
const rules = [{ key: 'a' }, { key: 'b' }, { key: 'c' }]
move({ value: rules }, 2, -1)
assert.deepEqual(rules.map((row) => row.key), ['a', 'c', 'b'])
move({ value: rules }, 0, -1)
assert.deepEqual(rules.map((row) => row.key), ['a', 'c', 'b'], 'the first row cannot move up')
move({ value: rules }, 2, 1)
assert.deepEqual(rules.map((row) => row.key), ['a', 'c', 'b'], 'the last row cannot move down')
assert.match(
source,
/for \(const rule of cubeRules\.value\) rule\.expanded = false/,

View File

@ -432,14 +432,6 @@
</p>
<template v-if="backend !== 'docker'">
<t-form-item :label="$t('settings.sandbox.inboundAccess')"
:tips="$t('settings.sandbox.inboundAccessHelp')">
<t-radio-group v-model="allowPublicInbound">
<t-radio :value="false">{{ $t('settings.sandbox.inboundTokenRequired') }}</t-radio>
<t-radio :value="true">{{ $t('settings.sandbox.inboundPublic') }}</t-radio>
</t-radio-group>
</t-form-item>
<t-form-item :label="$t('settings.sandbox.egressDefault')"
:tips="$t('settings.sandbox.egressPrecedence')">
<t-radio-group v-model="denyEgressByDefault">
@ -511,7 +503,7 @@
</t-button>
</div>
<p class="section-help">{{ $t('settings.sandbox.cubeL7RulesHelp') }}</p>
<div v-for="(rule, index) in cubeRules" :key="`cube-rule-${index}`"
<div v-for="(rule, index) in cubeRules" :key="rule.key"
class="net-rule net-rule--collapsible" :class="{ 'is-open': rule.expanded }">
<div class="net-rule__bar">
<button
@ -528,10 +520,24 @@
{{ rule.name.trim() || $t('settings.sandbox.ruleUntitled') }}
</span>
</button>
<button type="button" class="net-rule__remove"
:aria-label="$t('common.delete')" @click="cubeRules.splice(index, 1)">
<t-icon name="close" size="14px" />
</button>
<div class="net-rule__actions">
<button type="button" class="net-rule__move"
:disabled="index === 0"
:aria-label="$t('settings.sandbox.moveRuleUp')"
@click="moveCubeRule(index, -1)">
<t-icon name="chevron-up" size="14px" />
</button>
<button type="button" class="net-rule__move"
:disabled="index === cubeRules.length - 1"
:aria-label="$t('settings.sandbox.moveRuleDown')"
@click="moveCubeRule(index, 1)">
<t-icon name="chevron-down" size="14px" />
</button>
<button type="button" class="net-rule__remove"
:aria-label="$t('common.delete')" @click="cubeRules.splice(index, 1)">
<t-icon name="close" size="14px" />
</button>
</div>
</div>
<div v-if="rule.expanded" class="net-rule__body">
<div class="form-grid form-grid--two">
@ -821,13 +827,13 @@ const storedSecrets = reactive({ cube: false, e2b: false })
const envRows = ref<{ key: string; value: string; stored?: boolean }[]>([])
const skillRollout = ref<'next_turn' | 'new_session'>('next_turn')
// Both defaults are the zero value on the server too: egress allowed, inbound
// requiring the per-sandbox credential.
// requiring the per-sandbox credential. Inbound is not editable in this form.
const denyEgressByDefault = ref(false)
const allowPublicInbound = ref(false)
const allowOutRows = ref<string[]>([])
const denyOutRows = ref<string[]>([])
type CubeRuleForm = {
key: string
name: string
scheme?: string
sni?: string
@ -859,6 +865,12 @@ type E2BRuleForm = {
}
const cubeRules = ref<CubeRuleForm[]>([])
const e2bHostRules = ref<E2BRuleForm[]>([])
let cubeRuleKeySeq = 0
function newCubeRuleKey(): string {
cubeRuleKeySeq += 1
return `cube-rule-${cubeRuleKeySeq}`
}
function isStoredNetworkSecretRecoverable(
row: { stored?: boolean },
@ -875,11 +887,19 @@ function isStoredNetworkSecretRecoverable(
function addCubeRule() {
for (const rule of cubeRules.value) rule.expanded = false
cubeRules.value.push({
key: newCubeRuleKey(),
name: '', scheme: 'https', sni: '', host: '',
methodsText: '', path: '', deny: false, audit: '', expanded: true, inject: [],
})
}
function moveCubeRule(index: number, delta: number) {
const next = index + delta
if (next < 0 || next >= cubeRules.value.length) return
const [row] = cubeRules.value.splice(index, 1)
cubeRules.value.splice(next, 0, row)
}
function addE2BHostRule() {
for (const rule of e2bHostRules.value) rule.expanded = false
e2bHostRules.value.push({ host: '', expanded: true, headers: [] })
@ -1124,10 +1144,10 @@ function reset() {
skillRollout.value = cfg.skill_rollout === 'new_session' ? 'new_session' : 'next_turn'
const net = cfg.network || {}
denyEgressByDefault.value = net.deny_egress_by_default === true
allowPublicInbound.value = net.allow_public_inbound === true
allowOutRows.value = [...(net.allow_out || [])]
denyOutRows.value = [...(net.deny_out || [])]
cubeRules.value = (net.cube_rules || []).map((rule) => ({
key: newCubeRuleKey(),
name: rule.name || '',
scheme: rule.scheme || '',
sni: rule.sni || '',
@ -1172,17 +1192,10 @@ function reset() {
function selectBackend(value: string) {
if (backend.value === value) return
const crossingDocker = backend.value === 'docker' || value === 'docker'
backend.value = value
if (value === 'docker' && !docker.image) {
docker.image = defaultDockerImage
}
if (crossingDocker) {
// Docker has no inbound token. Leaving this true while the radio is
// hidden, then switching to Cube/E2B, would create a publicly reachable
// sandbox under a control the admin never saw on the docker form.
allowPublicInbound.value = false
}
onBackendChange()
}
@ -1463,14 +1476,12 @@ function collectPayload(): SandboxConfig {
// admin never touched serializes to the same thing as a fresh default.
function collectNetworkPolicy(): SandboxNetworkPolicy {
const policy: SandboxNetworkPolicy = {}
// Docker can only honour network_mode on the docker block. Sending the
// Cube/E2B radios would persist a public-inbound flag that becomes real
// the moment the admin switches backend.
// Docker can only honour network_mode on the docker block.
if (backend.value === 'docker') {
return policy
}
if (denyEgressByDefault.value) policy.deny_egress_by_default = true
if (allowPublicInbound.value) policy.allow_public_inbound = true
// Inbound stays the zero value: require the per-sandbox credential.
if (backend.value !== 'docker') {
const allowOut = allowOutRows.value.map((row) => row.trim()).filter(Boolean)
@ -2218,12 +2229,17 @@ onUnmounted(stopTemplatePolling)
.net-rule__bar {
display: grid;
grid-template-columns: minmax(0, 1fr) 22px;
grid-template-columns: minmax(0, 1fr) auto;
align-items: center;
min-height: 26px;
padding: 0 2px;
}
.net-rule__actions {
display: flex;
align-items: center;
}
.net-rule__toggle {
display: flex;
align-items: center;
@ -2258,6 +2274,7 @@ onUnmounted(stopTemplatePolling)
color: var(--td-text-color-placeholder);
}
.net-rule__move,
.net-rule__remove {
display: flex;
align-items: center;
@ -2272,6 +2289,16 @@ onUnmounted(stopTemplatePolling)
border-radius: 4px;
}
.net-rule__move:hover:not(:disabled) {
color: var(--td-text-color-primary);
background: var(--td-bg-color-container-hover);
}
.net-rule__move:disabled {
opacity: 0.35;
cursor: default;
}
.net-rule__remove:hover {
color: var(--td-error-color);
background: var(--td-bg-color-container-hover);

View File

@ -1129,11 +1129,7 @@ export default {
sectionRuntime: 'Execution settings',
sectionNetwork: 'Network policy',
sectionEnvironment: 'Environment variables',
networkHint: 'Controls inbound and outbound networking for every sandbox using this configuration. Changes affect only newly created sandboxes; existing sandboxes keep their policy until reclaimed.',
inboundAccess: 'Inbound access',
inboundAccessHelp: 'Credentials are required by default: the public sandbox URL must carry the token issued at creation.',
inboundTokenRequired: 'Require credentials (default)',
inboundPublic: 'Publicly accessible',
networkHint: 'Controls outbound networking for every sandbox using this configuration. Changes affect only newly created sandboxes; existing sandboxes keep their policy until reclaimed.',
egressDefault: 'Default egress',
egressAllowAll: 'Allow public network (default)',
egressDenyAll: 'Deny by default',
@ -1146,12 +1142,14 @@ export default {
denyOutHelp: 'Deny rules match destination IP only, so domains are not supported.',
domainAllowNeedsDenyAll: 'When allowed destinations contain a domain, also choose “Deny by default” or add 0.0.0.0/0 to denied destinations; otherwise the allowlist is ineffective.',
cubeL7Rules: 'HTTP access rules (L7)',
cubeL7RulesHelp: 'Every rule requires host or sni; the network layer derives allowed targets only from those fields. Fields are AND-ed and methods are OR-ed. Applies only to HTTP 80 / HTTPS 443.',
cubeL7RulesHelp: 'Every rule requires host or sni; the network layer derives allowed targets only from those fields. Fields are AND-ed and methods are OR-ed. Applies only to HTTP 80 / HTTPS 443. Rules are first-match-wins from top to bottom.',
e2bHostRules: 'Host request transforms',
e2bHostRulesHelp: 'Inject headers by host. A rule does not authorize egress; its host must also appear in allowed destinations.',
ruleUntitled: 'Untitled rule',
expandRule: 'Expand rule',
collapseRule: 'Collapse rule',
moveRuleUp: 'Move rule up',
moveRuleDown: 'Move rule down',
ruleName: 'Rule name',
ruleScheme: 'Scheme',
ruleSni: 'SNI',

View File

@ -5073,11 +5073,7 @@ export default {
sectionRuntime: 'Execution settings',
sectionNetwork: 'Network policy',
sectionEnvironment: 'Environment variables',
networkHint: 'Controls inbound and outbound networking for every sandbox using this configuration. Changes affect only newly created sandboxes; existing sandboxes keep their policy until reclaimed.',
inboundAccess: 'Inbound access',
inboundAccessHelp: 'Credentials are required by default: the public sandbox URL must carry the token issued at creation.',
inboundTokenRequired: 'Require credentials (default)',
inboundPublic: 'Publicly accessible',
networkHint: 'Controls outbound networking for every sandbox using this configuration. Changes affect only newly created sandboxes; existing sandboxes keep their policy until reclaimed.',
egressDefault: 'Default egress',
egressAllowAll: 'Allow public network (default)',
egressDenyAll: 'Deny by default',
@ -5090,12 +5086,14 @@ export default {
denyOutHelp: 'Deny rules match destination IP only, so domains are not supported.',
domainAllowNeedsDenyAll: 'When allowed destinations contain a domain, also choose “Deny by default” or add 0.0.0.0/0 to denied destinations; otherwise the allowlist is ineffective.',
cubeL7Rules: 'HTTP access rules (L7)',
cubeL7RulesHelp: 'Every rule requires host or sni; the network layer derives allowed targets only from those fields. Fields are AND-ed and methods are OR-ed. Applies only to HTTP 80 / HTTPS 443.',
cubeL7RulesHelp: 'Every rule requires host or sni; the network layer derives allowed targets only from those fields. Fields are AND-ed and methods are OR-ed. Applies only to HTTP 80 / HTTPS 443. Rules are first-match-wins from top to bottom.',
e2bHostRules: 'Host request transforms',
e2bHostRulesHelp: 'Inject headers by host. A rule does not authorize egress; its host must also appear in allowed destinations.',
ruleUntitled: 'Untitled rule',
expandRule: 'Expand rule',
collapseRule: 'Collapse rule',
moveRuleUp: 'Move rule up',
moveRuleDown: 'Move rule down',
ruleName: 'Rule name',
ruleScheme: 'Scheme',
ruleSni: 'SNI',

View File

@ -5073,11 +5073,7 @@ export default {
sectionRuntime: 'Execution settings',
sectionNetwork: 'Network policy',
sectionEnvironment: 'Environment variables',
networkHint: 'Controls inbound and outbound networking for every sandbox using this configuration. Changes affect only newly created sandboxes; existing sandboxes keep their policy until reclaimed.',
inboundAccess: 'Inbound access',
inboundAccessHelp: 'Credentials are required by default: the public sandbox URL must carry the token issued at creation.',
inboundTokenRequired: 'Require credentials (default)',
inboundPublic: 'Publicly accessible',
networkHint: 'Controls outbound networking for every sandbox using this configuration. Changes affect only newly created sandboxes; existing sandboxes keep their policy until reclaimed.',
egressDefault: 'Default egress',
egressAllowAll: 'Allow public network (default)',
egressDenyAll: 'Deny by default',
@ -5090,12 +5086,14 @@ export default {
denyOutHelp: 'Deny rules match destination IP only, so domains are not supported.',
domainAllowNeedsDenyAll: 'When allowed destinations contain a domain, also choose “Deny by default” or add 0.0.0.0/0 to denied destinations; otherwise the allowlist is ineffective.',
cubeL7Rules: 'HTTP access rules (L7)',
cubeL7RulesHelp: 'Every rule requires host or sni; the network layer derives allowed targets only from those fields. Fields are AND-ed and methods are OR-ed. Applies only to HTTP 80 / HTTPS 443.',
cubeL7RulesHelp: 'Every rule requires host or sni; the network layer derives allowed targets only from those fields. Fields are AND-ed and methods are OR-ed. Applies only to HTTP 80 / HTTPS 443. Rules are first-match-wins from top to bottom.',
e2bHostRules: 'Host request transforms',
e2bHostRulesHelp: 'Inject headers by host. A rule does not authorize egress; its host must also appear in allowed destinations.',
ruleUntitled: 'Untitled rule',
expandRule: 'Expand rule',
collapseRule: 'Collapse rule',
moveRuleUp: 'Move rule up',
moveRuleDown: 'Move rule down',
ruleName: 'Rule name',
ruleScheme: 'Scheme',
ruleSni: 'SNI',

View File

@ -5075,11 +5075,7 @@ export default {
sectionRuntime: '执行设置',
sectionNetwork: '网络策略',
sectionEnvironment: '环境变量',
networkHint: '控制该配置下所有沙箱的出入网。改动只影响之后新建的沙箱,已有沙箱按原策略运行到回收。',
inboundAccess: '入站访问',
inboundAccessHelp: '默认要求凭证:沙箱公网 URL 必须携带创建时签发的 token。',
inboundTokenRequired: '要求凭证(默认)',
inboundPublic: '公网可访问',
networkHint: '控制该配置下所有沙箱的出网。改动只影响之后新建的沙箱,已有沙箱按原策略运行到回收。',
egressDefault: '出站默认',
egressAllowAll: '允许公网(默认)',
egressDenyAll: '默认拒绝',
@ -5092,12 +5088,14 @@ export default {
denyOutHelp: '拒绝只按目的 IP 匹配,因此不支持域名。',
domainAllowNeedsDenyAll: '放行目标里有域名时,必须同时选择「默认拒绝」或在拒绝目标中加入 0.0.0.0/0,否则白名单不生效。',
cubeL7Rules: 'HTTP 访问规则(L7)',
cubeL7RulesHelp: '每条规则必须填 host 或 sni,网络层只从这两个字段提取放行目标。字段之间是 AND,method 列表内部是 OR。仅 HTTP 80 / HTTPS 443 生效。',
cubeL7RulesHelp: '每条规则必须填 host 或 sni,网络层只从这两个字段提取放行目标。字段之间是 AND,method 列表内部是 OR。仅 HTTP 80 / HTTPS 443 生效。规则从上到下先匹配先生效。',
e2bHostRules: 'Host 请求变换',
e2bHostRulesHelp: '按 host 注入 header。规则本身不授权出网,host 必须同时出现在放行目标里。',
ruleUntitled: '未命名规则',
expandRule: '展开规则',
collapseRule: '收起规则',
moveRuleUp: '上移规则',
moveRuleDown: '下移规则',
ruleName: '规则名',
ruleScheme: '协议',
ruleSni: 'SNI',