feat(sandbox): add tenant-configurable network policy (#2995)
* feat(sandbox): add the tenant network policy with its secrets and validation Administrators need control over sandbox network access, so a named sandbox config gains a network policy block. It lives inside the existing config JSONB, so there is no schema change and old rows read back as the zero value. Both booleans are phrased so that the zero value IS the intended default -- outbound open, inbound closed. That makes "no network block" and "explicitly saved defaults" provably the same thing, and avoids a tri-state pointer where nil would have to mean "allowed" for egress and "closed" for ingress. Injected header values are credentials, so they ride the encrypt-at-rest and mask-on-read path EnvVars already uses instead of a parallel mechanism. One CloneWithSecrets traversal serves encrypt, decrypt and mask so the three directions cannot disagree about which fields are secret. Validation runs at save time because the alternative is failing at sandbox-create time, where the admin no longer has the form in front of them. It rejects both what a provider would refuse and what a provider would accept without doing what the admin meant -- a domain allowlist with no deny-all fallback still leaves every unresolved destination reachable. * feat(sandbox): apply the network policy on both providers, persist the inbound token Resolve the stored policy into one fully specified provider-neutral policy so that nothing downstream re-derives a default. Both booleans come out non-nil on every path, including the nil-tenant one, because a partially specified policy would let the adapters fall back to their providers' more permissive defaults. The three inversions (deny-egress to allow-internet, public-inbound, rule-deny to rule-allow) happen in exactly one place. Every sandbox-creating path carries it, so sessions, skill installs and the deep connectivity check all run under the same config's policy rather than each wiring its own. Inbound access defaults to CLOSED, deliberately stricter than either provider's own default: a sandbox URL reachable by anyone who learns the ID is not a reasonable default for a tenant's workspace. Closing it makes the provider issue a per-sandbox traffic token, and only at create time -- so the token is stored with the session binding and replayed through Connect on every reconnect. Without that, a sandbox that was paused on TTL or rebound after a restart would answer 403 on every exec and file read, and 403 classifies as an authentication error rather than NotFound, so the binding would never be replaced and the session would stay wedged. Connect therefore takes a request struct instead of a bare ID, which gives the token a single documented way in rather than implicit state inside an adapter. Metadata-based recovery is the one reconnect path with no binding to read the token from. Rather than adopt a sandbox that would be permanently 403, it is deleted and replaced -- but only for providers that have the credential at all, since Docker has no inbound token and its containers are still adoptable. go-e2b keeps the token and never sends it, so for E2B the data-plane RoundTripper attaches the header from a process-local registry. Cube's SDK already does this itself. * fix(sandbox): classify data-plane traffic by authority shape, not the configured domain isDataPlane suffix-matched the configured sandbox domain, which was wrong in both directions. Both required a configured proxy_url, so E2B Cloud's default usage was unaffected; the affected deployments are exactly the self-hosted and E2B-compatible ones the gateway exists for. A configured gateway could be silently ignored. sandbox_domain is optional for E2B -- MissingRequiredFields asks only for api_key and template_id -- and with it empty the check returned false for everything. The general form is worse than the empty case: go-e2b's envdBaseURL prefers the domain the control plane reported over the client-wide one, so the authority actually dialled need not appear in the config at all. The failure is quiet whenever public DNS happens to resolve the sandbox domain, and the operator believes traffic is passing through a gateway that never sees it. Control-plane calls could be sent to the gateway. E2B's own defaults put the API host under the sandbox domain (api.e2b.app beneath e2b.app), so the suffix match classified every Create, Connect and List as data-plane traffic. That is loud where the gateway does not serve the API, but where it proxies both planes it succeeds while downgrading an X-API-Key request to plaintext for an http:// gateway. Cube was immune to the first problem, since it requires both fields, but not to this one. Classify on the "<port>-<sandboxID>.<domain>" shape both SDKs generate, using the SandboxIDFromDataPlaneHost helper that token injection on the very same request already relies on -- so routing and injection now agree by construction instead of applying two different rules. That helper exists precisely because the configured domain is unreliable here; it was simply never used for the routing half. The control host stays as an explicit exclusion. The shape test already rejects api.<domain>, so this only covers an API host that itself wears the shape, such as 8080-api.example.com. One existing assertion was replaced rather than kept: the E2B pool test proved that the Cube fields were ignored by asserting a cube.app authority was not data-plane traffic, which tested the domain matching rather than the field selection. It now asserts the transport dials the E2B gateway address and not the Cube one. * feat(sandbox): add the network policy editor to the sandbox config drawer The policy sits in the runtime step, directly under the settings it constrains, rather than in a step of its own. The existing execution timeouts were compressed into a two-column grid to make room, keeping each field's own label and its own tip -- the reason they were one per row was that three unlabelled numbers sharing a footnote gave no clue which one you were editing, and two columns with per-field tips does not regress that. Provider-specific sections are shown only for the backend that has them: the Cube L7 rule cards, E2B's per-host header transforms, and for Docker just the bridge/none selector, since Docker can only express the overall switch. Injected header values are write-only. A stored one shows as configured and is preserved when the input is left blank, which is how env-var secrets already behave. Renaming a rule or a header is the case worth care: the merge indexes credentials on the rule-and-header pair, so a rename means the old value can no longer be recovered. One helper decides both the placeholder text and whether the payload re-attaches the value, so the form cannot claim a credential is kept while the save blanks it. The add buttons use keys of their own instead of reusing the env-var table's "add variable", which read wrongly under a list of network destinations and which the i18n key check cannot catch, since the key exists in every bundle. * docs(sandbox): document the network policy and its inbound default change The existing network bullet described the pre-feature state -- both providers open by default, tunable only through the neutral policy at create time -- which is no longer true of the defaults or of the admin-facing surface. Three things needed writing down rather than restating. The inbound default flips from publicly reachable to credential-required. A deployment that relies on a browser or an external service reaching a sandbox port directly, rather than going through WeKnora, has to opt back in on that config. The binding store now holds a bearer credential in plaintext. Leaving it unencrypted was a deliberate trade -- per-reconnect crypto on the hot path against Redis's own access control -- and the trade is only sound if the requirement is actually stated, along with the code-side constraint it depends on: a binding or a handle is never logged whole, only the sandbox ID and whether a credential is present. On binding loss, a closed-inbound Cube or E2B config no longer adopts its old sandbox by metadata. The token went with the binding and the provider will not reissue it, so adoption would produce a session that answers 403 on every data-plane call with no way back. The sandbox is deleted and rebuilt, which costs the /workspace scratch. Docker has no such credential and still adopts. * fix(sandbox): fail closed when a closed-inbound create has no traffic token A Cube/E2B sandbox created without the inbound token would be bound anyway, then 403 on every data-plane call as an unreplaceable authentication error. Refuse the create, destroy the sandbox, and stop Docker from persisting inbound/egress radios it cannot honour. Canonicalize IPv4 /0 deny-all onto 0.0.0.0/0 and reject CR/LF in injected header names and values. * fix(sandbox): satisfy pre-push lint on the network policy files Unexport the data-plane host parser, drop file-level package docs that revive rejected, and lowercase error-string prefixes that staticcheck ST1005 treats as capitalized English. * fix(sandbox): persist rotated inbound tokens and stop misreporting restricted egress Connect can reissue the traffic token after pause/resume; write it back onto the binding so a restart does not restore a stale credential that 403s and cannot be replaced. Restore the volume-support i18n key, map Docker network_mode=none onto deny-egress, inject the E2B inbound header without a gateway pool, and fold header names when merging redacted secrets. --------- Co-authored-by: hailongzhao <hailongzhao@tencent.com> Co-authored-by: wizardchen <wizardchen@tencent.com>main
parent
22489ba663
commit
e39277a75e
|
|
@ -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 工具
|
||||
|
||||
|
|
|
|||
|
|
@ -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<string, string>
|
||||
}
|
||||
|
||||
/**
|
||||
* 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
|
||||
|
|
|
|||
|
|
@ -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('<script setup'))
|
||||
assert.match(
|
||||
source,
|
||||
/<t-input v-model="inject\.secret" type="password"/,
|
||||
'Cube injected credentials must not be rendered in clear text',
|
||||
)
|
||||
assert.match(
|
||||
source,
|
||||
/<t-input v-model="header\.value" type="password"/,
|
||||
'E2B injected credentials must not be rendered in clear text',
|
||||
)
|
||||
assert.match(
|
||||
payloadBlock,
|
||||
/isStoredNetworkSecretRecoverable\(\s*inject,\s*inject\.originalRuleName,\s*inject\.originalHeader,\s*rule\.name,\s*inject\.header,\s*\)[\s\S]*?inject\.secret === ''[\s\S]*?\? secretPlaceholder/,
|
||||
'Cube payload preservation must use the shared recoverability decision',
|
||||
)
|
||||
assert.match(
|
||||
payloadBlock,
|
||||
/isStoredNetworkSecretRecoverable\(\s*header,\s*header\.originalHost,\s*header\.originalName,\s*rule\.host,\s*header\.name,\s*\)[\s\S]*?header\.value === ''[\s\S]*?\? secretPlaceholder/,
|
||||
'E2B payload preservation must use the shared recoverability decision',
|
||||
)
|
||||
assert.match(
|
||||
templateBlock,
|
||||
/isStoredNetworkSecretRecoverable\(\s*inject,\s*inject\.originalRuleName,\s*inject\.originalHeader,\s*rule\.name,\s*inject\.header,\s*\)[\s\S]*?\$t\('settings\.sandbox\.secretKeepHint'\)/,
|
||||
'Cube configured placeholder must use the shared recoverability decision',
|
||||
)
|
||||
assert.match(
|
||||
templateBlock,
|
||||
/isStoredNetworkSecretRecoverable\(\s*header,\s*header\.originalHost,\s*header\.originalName,\s*rule\.host,\s*header\.name,\s*\)[\s\S]*?\$t\('settings\.sandbox\.secretKeepHint'\)/,
|
||||
'E2B configured placeholder must use the shared recoverability decision',
|
||||
)
|
||||
})
|
||||
|
||||
test('stored network secret recoverability requires the loaded identity', () => {
|
||||
const helper = source.match(
|
||||
/function isStoredNetworkSecretRecoverable\([\s\S]*?\): boolean \{\n([\s\S]*?)\n\}/,
|
||||
)
|
||||
assert.ok(helper, 'the shared recoverability helper must exist')
|
||||
const isRecoverable = new Function(
|
||||
'row',
|
||||
'originalParentIdentity',
|
||||
'originalChildIdentity',
|
||||
'currentParentIdentity',
|
||||
'currentChildIdentity',
|
||||
helper[1],
|
||||
)
|
||||
const storedRow = { stored: true }
|
||||
|
||||
assert.equal(
|
||||
isRecoverable(storedRow, 'rule-a', 'Authorization', 'rule-a', 'Authorization'),
|
||||
true,
|
||||
'a stored row under its loaded identity keeps the placeholder',
|
||||
)
|
||||
assert.equal(
|
||||
isRecoverable(storedRow, 'rule-a', 'Authorization', 'rule-b', 'Authorization'),
|
||||
false,
|
||||
'a renamed row must request a new value',
|
||||
)
|
||||
})
|
||||
|
||||
test('domain allow without deny-all is warned about in place', () => {
|
||||
const classifierBlock = source.slice(
|
||||
source.indexOf('const domainAllowNeedsDenyAll'),
|
||||
source.indexOf('const inFlightFromSkills'),
|
||||
)
|
||||
assert.match(
|
||||
source,
|
||||
/<t-alert v-if="domainAllowNeedsDenyAll"[\s\S]*?:message="\$t\('settings\.sandbox\.domainAllowNeedsDenyAll'\)"/,
|
||||
'the in-place warning alert must remain rendered',
|
||||
)
|
||||
assert.match(
|
||||
classifierBlock,
|
||||
/if \(denyEgressByDefault\.value\) return false/,
|
||||
'deny-by-default must suppress the warning',
|
||||
)
|
||||
assert.match(
|
||||
classifierBlock,
|
||||
/denyOutRows\.value\.some\(\(row\) => denyOutRowCoversAllIPv4\(row\)\)\) return false/,
|
||||
'an explicit deny-all row must suppress the warning',
|
||||
)
|
||||
assert.match(
|
||||
source,
|
||||
/function denyOutRowCoversAllIPv4\(row: string\): boolean \{[\s\S]*\\\/0\$/,
|
||||
'any IPv4 /0 CIDR must count as deny-all, matching the backend validator',
|
||||
)
|
||||
assert.match(
|
||||
classifierBlock,
|
||||
/return !\/\^\[0-9\.\/\]\+\$\/\.test\(value\)/,
|
||||
'only non-IP/CIDR allow rows must trigger the warning',
|
||||
)
|
||||
|
||||
const helper = source.match(
|
||||
/function denyOutRowCoversAllIPv4\(row: string\): boolean \{\n([\s\S]*?)\n\}/,
|
||||
)
|
||||
assert.ok(helper, 'the deny-all classifier must exist')
|
||||
const coversAll = new Function('row', helper[1])
|
||||
assert.equal(coversAll('0.0.0.0/0'), true)
|
||||
assert.equal(coversAll(' 1.2.3.4/0 '), true)
|
||||
assert.equal(coversAll('10.0.0.0/8'), false)
|
||||
assert.equal(coversAll('0.0.0.0/32'), false)
|
||||
})
|
||||
|
||||
test('docker payload omits hidden allow and deny lists', () => {
|
||||
const payloadBlock = source.slice(
|
||||
source.indexOf('function collectNetworkPolicy'),
|
||||
source.indexOf('function close'),
|
||||
)
|
||||
assert.match(
|
||||
payloadBlock,
|
||||
/if \(backend\.value === 'docker'\) \{\s*return policy/,
|
||||
'Docker must not persist Cube/E2B radios or allow/deny rows',
|
||||
)
|
||||
assert.match(
|
||||
payloadBlock,
|
||||
/if \(backend\.value !== 'docker'\) \{[^}]*policy\.allow_out = allowOut[^}]*policy\.deny_out = denyOut[^}]*\}/,
|
||||
'Docker must not send allow/deny rows that its form hides',
|
||||
)
|
||||
})
|
||||
|
||||
test('docker hides inbound and 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',
|
||||
)
|
||||
})
|
||||
|
||||
test('cube L7 rules collapse to a name bar', () => {
|
||||
const templateBlock = source.slice(0, source.indexOf('<script setup'))
|
||||
const cubeBlock = templateBlock.slice(templateBlock.indexOf('settings.sandbox.cubeL7Rules'))
|
||||
const e2bBlock = cubeBlock.slice(cubeBlock.indexOf('settings.sandbox.e2bHostRules'))
|
||||
const cubeRulesBlock = cubeBlock.slice(0, cubeBlock.indexOf('settings.sandbox.e2bHostRules'))
|
||||
|
||||
assert.match(
|
||||
cubeRulesBlock,
|
||||
/class="net-rule net-rule--collapsible"/,
|
||||
'Cube L7 rules use the compact collapsible card, not the always-open padding',
|
||||
)
|
||||
assert.match(
|
||||
cubeRulesBlock,
|
||||
/class="net-rule__bar"/,
|
||||
'each Cube L7 rule must render a compact name bar',
|
||||
)
|
||||
assert.match(
|
||||
cubeRulesBlock,
|
||||
/rule\.expanded \? 'chevron-down' : 'chevron-right'/,
|
||||
'the left control must expand and collapse the rule',
|
||||
)
|
||||
assert.match(
|
||||
cubeRulesBlock,
|
||||
/v-if="rule\.expanded"/,
|
||||
'rule details must stay hidden until the bar is expanded',
|
||||
)
|
||||
assert.equal(
|
||||
cubeRulesBlock.includes("settings.sandbox.removeRule"),
|
||||
false,
|
||||
'the expanded body must not grow with a second delete control',
|
||||
)
|
||||
assert.match(
|
||||
e2bBlock,
|
||||
/class="net-rule net-rule--collapsible"/,
|
||||
'E2B host rules use the same compact collapsible card',
|
||||
)
|
||||
assert.match(
|
||||
e2bBlock,
|
||||
/class="net-rule__bar"/,
|
||||
'each E2B host rule must render a compact name bar',
|
||||
)
|
||||
assert.match(
|
||||
e2bBlock,
|
||||
/v-if="rule\.expanded"/,
|
||||
'E2B rule details must stay hidden until the bar is expanded',
|
||||
)
|
||||
assert.equal(
|
||||
e2bBlock.includes("settings.sandbox.removeRule"),
|
||||
false,
|
||||
'E2B expanded body must not grow with a second delete control',
|
||||
)
|
||||
assert.match(
|
||||
source,
|
||||
/for \(const rule of cubeRules\.value\) rule\.expanded = false/,
|
||||
'adding a Cube rule must collapse the others so the list stays a stack of name bars',
|
||||
)
|
||||
assert.match(
|
||||
source,
|
||||
/for \(const rule of e2bHostRules\.value\) rule\.expanded = false/,
|
||||
'adding an E2B rule must collapse the others so the list stays a stack of name bars',
|
||||
)
|
||||
assert.match(
|
||||
source,
|
||||
/expanded: true, inject: \[\]/,
|
||||
'the Cube rule just added stays open so it can be filled in',
|
||||
)
|
||||
assert.match(
|
||||
source,
|
||||
/host: '', expanded: true, headers: \[\]/,
|
||||
'the E2B rule just added stays open so it can be filled in',
|
||||
)
|
||||
const cubeLoadBlock = source.slice(
|
||||
source.indexOf('cubeRules.value = (net.cube_rules || []).map'),
|
||||
source.indexOf('e2bHostRules.value = (net.e2b_host_rules || []).map'),
|
||||
)
|
||||
const e2bLoadBlock = source.slice(
|
||||
source.indexOf('e2bHostRules.value = (net.e2b_host_rules || []).map'),
|
||||
source.indexOf('checkResult.value = null'),
|
||||
)
|
||||
assert.match(
|
||||
cubeLoadBlock,
|
||||
/expanded: false/,
|
||||
'Cube rules loaded from a saved config start collapsed',
|
||||
)
|
||||
assert.match(
|
||||
e2bLoadBlock,
|
||||
/expanded: false/,
|
||||
'E2B rules loaded from a saved config start collapsed',
|
||||
)
|
||||
})
|
||||
|
||||
test('deny rules omit hidden injected secrets', () => {
|
||||
const payloadBlock = source.slice(
|
||||
source.indexOf('function collectNetworkPolicy'),
|
||||
source.indexOf('function close'),
|
||||
)
|
||||
assert.match(
|
||||
payloadBlock,
|
||||
/inject: rule\.deny[\s\S]*?\? undefined[\s\S]*?: rule\.inject/,
|
||||
'a deny rule must not send inject entries hidden by the form',
|
||||
)
|
||||
})
|
||||
|
||||
test('policy-restricted egress does not claim full outbound verification', () => {
|
||||
assert.match(
|
||||
source,
|
||||
/EGRESS_RESTRICTED_REASON = 'egress_restricted_by_policy'/,
|
||||
'the hint must recognize the skip reason the check API returns',
|
||||
)
|
||||
assert.match(
|
||||
source,
|
||||
/settings\.sandbox\.checkScopePolicyRestricted/,
|
||||
'deny-by-default must not reuse the "outbound was verified" copy',
|
||||
)
|
||||
const hintBlock = source.slice(
|
||||
source.indexOf('const checkScopeHint = computed'),
|
||||
source.indexOf('function checkDetail'),
|
||||
)
|
||||
const restrictedAt = hintBlock.indexOf('checkScopePolicyRestricted')
|
||||
const fullAt = hintBlock.indexOf('checkScopeFull')
|
||||
assert.ok(
|
||||
restrictedAt !== -1 && fullAt !== -1 && restrictedAt < fullAt,
|
||||
'policy-restricted copy must win over the full-verification claim',
|
||||
)
|
||||
})
|
||||
|
||||
test('volume-incapable backends still have a warning string to show', () => {
|
||||
assert.match(
|
||||
source,
|
||||
/settings\.sandbox\.noVolumeSupport/,
|
||||
'SupportsVolumes=false must not render a missing i18n key',
|
||||
)
|
||||
})
|
||||
|
|
@ -365,61 +365,302 @@
|
|||
|
||||
<section v-if="currentStepKey === 'runtime'" class="setting-drawer__section">
|
||||
<h4 class="setting-drawer__section-title">{{ $t('settings.sandbox.sectionRuntime') }}</h4>
|
||||
<!--
|
||||
Three unlabelled numbers side by side shared one footnote, so nobody
|
||||
could tell which limit they were raising. Each gets its own row and
|
||||
its own sentence naming what it bounds and what happens on expiry.
|
||||
-->
|
||||
<div class="runtime-fields">
|
||||
<template v-if="isRemoteBackend">
|
||||
<t-form-item :label="$t('settings.sandbox.httpTimeout')">
|
||||
<t-input-number v-if="backend === 'cube'" v-model="cube.http_timeout_sec" :min="0" theme="column"
|
||||
placeholder="30" />
|
||||
<t-input-number v-else v-model="e2b.http_timeout_sec" :min="0" theme="column" placeholder="30" />
|
||||
</t-form-item>
|
||||
<p class="section-help section-help--field">{{ $t('settings.sandbox.httpTimeoutHelp') }}</p>
|
||||
<t-form-item :label="$t('settings.sandbox.sandboxTtl')">
|
||||
<t-input-number v-if="backend === 'cube'" v-model="cube.cube_sandbox_ttl_seconds" :min="0"
|
||||
theme="column" placeholder="1800" />
|
||||
<t-input-number v-else v-model="e2b.e2b_sandbox_ttl_seconds" :min="0" theme="column"
|
||||
placeholder="300" />
|
||||
</t-form-item>
|
||||
<p class="section-help section-help--field">{{ $t('settings.sandbox.sandboxTtlHelp') }}</p>
|
||||
</template>
|
||||
<!--
|
||||
Docker has no provider-side timeout at all: an abandoned container
|
||||
keeps its memory and CPU share on the daemon host until WeKnora
|
||||
reclaims it, so the idle TTL and the resource caps are the only
|
||||
things bounding what one workspace can hold.
|
||||
Each number keeps its own label and its own sentence — the reason
|
||||
these were one-per-row originally was that three unlabelled numbers
|
||||
side by side shared a single footnote. Moving the sentence into the
|
||||
field's own tips keeps that fixed while halving the height.
|
||||
-->
|
||||
<template v-if="backend === 'docker'">
|
||||
<t-form-item :label="$t('settings.sandbox.dockerIdleTtl')">
|
||||
<t-input-number v-model="docker.idle_ttl_seconds" :min="0" theme="column" placeholder="1800" />
|
||||
<div class="form-grid form-grid--two">
|
||||
<template v-if="isRemoteBackend">
|
||||
<t-form-item :label="$t('settings.sandbox.httpTimeout')"
|
||||
:tips="$t('settings.sandbox.httpTimeoutHelp')">
|
||||
<t-input-number v-if="backend === 'cube'" v-model="cube.http_timeout_sec" :min="0"
|
||||
theme="column" placeholder="30" />
|
||||
<t-input-number v-else v-model="e2b.http_timeout_sec" :min="0" theme="column"
|
||||
placeholder="30" />
|
||||
</t-form-item>
|
||||
<t-form-item :label="$t('settings.sandbox.sandboxTtl')"
|
||||
:tips="$t('settings.sandbox.sandboxTtlHelp')">
|
||||
<t-input-number v-if="backend === 'cube'" v-model="cube.cube_sandbox_ttl_seconds"
|
||||
:min="0" theme="column" placeholder="1800" />
|
||||
<t-input-number v-else v-model="e2b.e2b_sandbox_ttl_seconds" :min="0"
|
||||
theme="column" placeholder="300" />
|
||||
</t-form-item>
|
||||
</template>
|
||||
<!--
|
||||
Docker has no provider-side timeout at all: an abandoned container
|
||||
keeps its memory and CPU share on the daemon host until WeKnora
|
||||
reclaims it, so the idle TTL and the resource caps are the only
|
||||
things bounding what one workspace can hold.
|
||||
-->
|
||||
<template v-if="backend === 'docker'">
|
||||
<t-form-item :label="$t('settings.sandbox.dockerIdleTtl')"
|
||||
:tips="$t('settings.sandbox.dockerIdleTtlHelp')">
|
||||
<t-input-number v-model="docker.idle_ttl_seconds" :min="0" theme="column"
|
||||
placeholder="1800" />
|
||||
</t-form-item>
|
||||
<t-form-item :label="$t('settings.sandbox.dockerCpuLimit')"
|
||||
:tips="$t('settings.sandbox.dockerCpuLimitHelp')">
|
||||
<t-input-number v-model="docker.cpu_limit" :min="0" :step="0.5" theme="column"
|
||||
placeholder="2" />
|
||||
</t-form-item>
|
||||
<t-form-item :label="$t('settings.sandbox.dockerMemoryLimit')"
|
||||
:tips="$t('settings.sandbox.dockerMemoryLimitHelp')">
|
||||
<t-input-number v-model="docker.memory_limit_mb" :min="0" theme="column"
|
||||
placeholder="2048" />
|
||||
</t-form-item>
|
||||
<t-form-item :label="$t('settings.sandbox.dockerPidsLimit')"
|
||||
:tips="$t('settings.sandbox.dockerPidsLimitHelp')">
|
||||
<t-input-number v-model="docker.pids_limit" :min="0" theme="column"
|
||||
placeholder="512" />
|
||||
</t-form-item>
|
||||
</template>
|
||||
<t-form-item :label="$t('settings.sandbox.defaultTimeout')"
|
||||
:tips="$t('settings.sandbox.defaultTimeoutHelp')">
|
||||
<t-input-number v-model="defaultTimeoutSec" :min="0" theme="column" placeholder="60" />
|
||||
</t-form-item>
|
||||
<p class="section-help section-help--field">{{ $t('settings.sandbox.dockerIdleTtlHelp') }}</p>
|
||||
<t-form-item :label="$t('settings.sandbox.dockerCpuLimit')">
|
||||
<t-input-number v-model="docker.cpu_limit" :min="0" :step="0.5" theme="column" placeholder="2" />
|
||||
</t-form-item>
|
||||
<t-form-item :label="$t('settings.sandbox.dockerMemoryLimit')">
|
||||
<t-input-number v-model="docker.memory_limit_mb" :min="0" theme="column" placeholder="2048" />
|
||||
</t-form-item>
|
||||
<t-form-item :label="$t('settings.sandbox.dockerPidsLimit')">
|
||||
<t-input-number v-model="docker.pids_limit" :min="0" theme="column" placeholder="512" />
|
||||
</t-form-item>
|
||||
<p class="section-help section-help--field">{{ $t('settings.sandbox.dockerResourceHelp') }}</p>
|
||||
<t-form-item :label="$t('settings.sandbox.dockerNetworkMode')">
|
||||
<t-select v-model="docker.network_mode" :placeholder="$t('settings.sandbox.dockerNetworkBridge')"
|
||||
clearable>
|
||||
<t-option value="bridge" :label="$t('settings.sandbox.dockerNetworkBridge')" />
|
||||
<t-option value="none" :label="$t('settings.sandbox.dockerNetworkNone')" />
|
||||
</t-select>
|
||||
</t-form-item>
|
||||
<p class="section-help section-help--field">{{ $t('settings.sandbox.dockerNetworkModeHelp') }}</p>
|
||||
</template>
|
||||
<t-form-item :label="$t('settings.sandbox.defaultTimeout')">
|
||||
<t-input-number v-model="defaultTimeoutSec" :min="0" theme="column" placeholder="60" />
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section v-if="currentStepKey === 'runtime'" class="setting-drawer__section">
|
||||
<h4 class="setting-drawer__section-title">{{ $t('settings.sandbox.sectionNetwork') }}</h4>
|
||||
<p class="section-help section-help--under-title">
|
||||
{{ $t('settings.sandbox.networkHint') }}
|
||||
</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>
|
||||
<p class="section-help section-help--field">{{ $t('settings.sandbox.defaultTimeoutHelp') }}</p>
|
||||
|
||||
<t-form-item :label="$t('settings.sandbox.egressDefault')"
|
||||
:tips="$t('settings.sandbox.egressPrecedence')">
|
||||
<t-radio-group v-model="denyEgressByDefault">
|
||||
<t-radio :value="false">{{ $t('settings.sandbox.egressAllowAll') }}</t-radio>
|
||||
<t-radio :value="true">{{ $t('settings.sandbox.egressDenyAll') }}</t-radio>
|
||||
</t-radio-group>
|
||||
</t-form-item>
|
||||
</template>
|
||||
|
||||
<template v-if="backend === 'docker'">
|
||||
<t-form-item :label="$t('settings.sandbox.dockerNetworkMode')"
|
||||
:tips="$t('settings.sandbox.dockerNetworkModeHelp')">
|
||||
<t-select v-model="docker.network_mode"
|
||||
:placeholder="$t('settings.sandbox.dockerNetworkBridge')" clearable>
|
||||
<t-option value="bridge" :label="$t('settings.sandbox.dockerNetworkBridge')" />
|
||||
<t-option value="none" :label="$t('settings.sandbox.dockerNetworkNone')" />
|
||||
</t-select>
|
||||
</t-form-item>
|
||||
</template>
|
||||
|
||||
<template v-else>
|
||||
<div class="net-list">
|
||||
<div class="section-title-row">
|
||||
<span class="net-list__title">{{ $t('settings.sandbox.allowOut') }}</span>
|
||||
<t-button variant="text" size="small" @click="allowOutRows.push('')">
|
||||
<template #icon><t-icon name="add" /></template>
|
||||
{{ $t('settings.sandbox.addTarget') }}
|
||||
</t-button>
|
||||
</div>
|
||||
<div v-for="(_, index) in allowOutRows" :key="`allow-${index}`" class="net-row">
|
||||
<t-input v-model="allowOutRows[index]"
|
||||
:placeholder="$t('settings.sandbox.allowOutPlaceholder')" />
|
||||
<t-button variant="text" shape="square" size="small"
|
||||
:aria-label="$t('common.delete')" @click="allowOutRows.splice(index, 1)">
|
||||
<t-icon name="close" />
|
||||
</t-button>
|
||||
</div>
|
||||
<p class="section-help">{{ $t('settings.sandbox.allowOutHelp') }}</p>
|
||||
<t-alert v-if="domainAllowNeedsDenyAll" theme="warning" class="compact-alert"
|
||||
:message="$t('settings.sandbox.domainAllowNeedsDenyAll')" />
|
||||
</div>
|
||||
|
||||
<div class="net-list">
|
||||
<div class="section-title-row">
|
||||
<span class="net-list__title">{{ $t('settings.sandbox.denyOut') }}</span>
|
||||
<t-button variant="text" size="small" @click="denyOutRows.push('')">
|
||||
<template #icon><t-icon name="add" /></template>
|
||||
{{ $t('settings.sandbox.addTarget') }}
|
||||
</t-button>
|
||||
</div>
|
||||
<div v-for="(_, index) in denyOutRows" :key="`deny-${index}`" class="net-row">
|
||||
<t-input v-model="denyOutRows[index]"
|
||||
:placeholder="$t('settings.sandbox.denyOutPlaceholder')" />
|
||||
<t-button variant="text" shape="square" size="small"
|
||||
:aria-label="$t('common.delete')" @click="denyOutRows.splice(index, 1)">
|
||||
<t-icon name="close" />
|
||||
</t-button>
|
||||
</div>
|
||||
<p class="section-help">{{ $t('settings.sandbox.denyOutHelp') }}</p>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<div v-if="backend === 'cube'" class="net-list">
|
||||
<div class="section-title-row">
|
||||
<span class="net-list__title">{{ $t('settings.sandbox.cubeL7Rules') }}</span>
|
||||
<t-button variant="text" size="small" @click="addCubeRule()">
|
||||
<template #icon><t-icon name="add" /></template>
|
||||
{{ $t('settings.sandbox.addRule') }}
|
||||
</t-button>
|
||||
</div>
|
||||
<p class="section-help">{{ $t('settings.sandbox.cubeL7RulesHelp') }}</p>
|
||||
<div v-for="(rule, index) in cubeRules" :key="`cube-rule-${index}`"
|
||||
class="net-rule net-rule--collapsible" :class="{ 'is-open': rule.expanded }">
|
||||
<div class="net-rule__bar">
|
||||
<button
|
||||
type="button"
|
||||
class="net-rule__toggle"
|
||||
:aria-expanded="rule.expanded"
|
||||
:aria-label="rule.expanded
|
||||
? $t('settings.sandbox.collapseRule')
|
||||
: $t('settings.sandbox.expandRule')"
|
||||
@click="rule.expanded = !rule.expanded"
|
||||
>
|
||||
<t-icon :name="rule.expanded ? 'chevron-down' : 'chevron-right'" size="14px" />
|
||||
<span class="net-rule__name" :class="{ 'is-empty': !rule.name.trim() }">
|
||||
{{ 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>
|
||||
<div v-if="rule.expanded" class="net-rule__body">
|
||||
<div class="form-grid form-grid--two">
|
||||
<t-form-item :label="$t('settings.sandbox.ruleName')">
|
||||
<t-input v-model="rule.name" placeholder="allow-payment-api" />
|
||||
</t-form-item>
|
||||
<t-form-item :label="$t('settings.sandbox.ruleScheme')">
|
||||
<t-select v-model="rule.scheme" clearable>
|
||||
<t-option value="https" label="https" />
|
||||
<t-option value="http" label="http" />
|
||||
</t-select>
|
||||
</t-form-item>
|
||||
<t-form-item :label="$t('settings.sandbox.ruleSni')">
|
||||
<t-input v-model="rule.sni" placeholder="api.example.com" />
|
||||
</t-form-item>
|
||||
<t-form-item :label="$t('settings.sandbox.ruleHost')">
|
||||
<t-input v-model="rule.host" placeholder="api.example.com" />
|
||||
</t-form-item>
|
||||
<t-form-item :label="$t('settings.sandbox.ruleMethods')">
|
||||
<t-input v-model="rule.methodsText" placeholder="POST, GET" />
|
||||
</t-form-item>
|
||||
<t-form-item :label="$t('settings.sandbox.rulePath')">
|
||||
<t-input v-model="rule.path" placeholder="/v1/*" />
|
||||
</t-form-item>
|
||||
<t-form-item :label="$t('settings.sandbox.ruleAction')">
|
||||
<t-select v-model="rule.deny">
|
||||
<t-option :value="false" :label="$t('settings.sandbox.ruleAllow')" />
|
||||
<t-option :value="true" :label="$t('settings.sandbox.ruleDeny')" />
|
||||
</t-select>
|
||||
</t-form-item>
|
||||
<t-form-item :label="$t('settings.sandbox.ruleAudit')">
|
||||
<t-select v-model="rule.audit" clearable>
|
||||
<t-option value="metadata" label="metadata" />
|
||||
<t-option value="full" label="full" />
|
||||
<t-option value="none" label="none" />
|
||||
</t-select>
|
||||
</t-form-item>
|
||||
</div>
|
||||
<div v-if="!rule.deny" class="net-inject">
|
||||
<span class="net-list__title">{{ $t('settings.sandbox.ruleInject') }}</span>
|
||||
<div v-for="(inject, injectIndex) in rule.inject" :key="`inject-${injectIndex}`"
|
||||
class="net-row net-row--triple">
|
||||
<t-input v-model="inject.header" :placeholder="$t('settings.sandbox.headerName')" />
|
||||
<t-input v-model="inject.secret" type="password"
|
||||
:placeholder="isStoredNetworkSecretRecoverable(
|
||||
inject,
|
||||
inject.originalRuleName,
|
||||
inject.originalHeader,
|
||||
rule.name,
|
||||
inject.header,
|
||||
)
|
||||
? $t('settings.sandbox.secretKeepHint')
|
||||
: $t('settings.sandbox.headerValue')" />
|
||||
<t-input v-model="inject.format" placeholder="Bearer ${SECRET}" />
|
||||
<t-button variant="text" shape="square" size="small"
|
||||
:aria-label="$t('common.delete')" @click="rule.inject.splice(injectIndex, 1)">
|
||||
<t-icon name="close" />
|
||||
</t-button>
|
||||
</div>
|
||||
<t-button variant="text" size="small"
|
||||
@click="rule.inject.push({ header: '', secret: '', format: '' })">
|
||||
<template #icon><t-icon name="add" /></template>
|
||||
{{ $t('settings.sandbox.addHeader') }}
|
||||
</t-button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-if="backend === 'e2b'" class="net-list">
|
||||
<div class="section-title-row">
|
||||
<span class="net-list__title">{{ $t('settings.sandbox.e2bHostRules') }}</span>
|
||||
<t-button variant="text" size="small" @click="addE2BHostRule()">
|
||||
<template #icon><t-icon name="add" /></template>
|
||||
{{ $t('settings.sandbox.addRule') }}
|
||||
</t-button>
|
||||
</div>
|
||||
<p class="section-help">{{ $t('settings.sandbox.e2bHostRulesHelp') }}</p>
|
||||
<div v-for="(rule, index) in e2bHostRules" :key="`e2b-rule-${index}`"
|
||||
class="net-rule net-rule--collapsible" :class="{ 'is-open': rule.expanded }">
|
||||
<div class="net-rule__bar">
|
||||
<button
|
||||
type="button"
|
||||
class="net-rule__toggle"
|
||||
:aria-expanded="rule.expanded"
|
||||
:aria-label="rule.expanded
|
||||
? $t('settings.sandbox.collapseRule')
|
||||
: $t('settings.sandbox.expandRule')"
|
||||
@click="rule.expanded = !rule.expanded"
|
||||
>
|
||||
<t-icon :name="rule.expanded ? 'chevron-down' : 'chevron-right'" size="14px" />
|
||||
<span class="net-rule__name" :class="{ 'is-empty': !rule.host.trim() }">
|
||||
{{ rule.host.trim() || $t('settings.sandbox.ruleUntitled') }}
|
||||
</span>
|
||||
</button>
|
||||
<button type="button" class="net-rule__remove"
|
||||
:aria-label="$t('common.delete')" @click="e2bHostRules.splice(index, 1)">
|
||||
<t-icon name="close" size="14px" />
|
||||
</button>
|
||||
</div>
|
||||
<div v-if="rule.expanded" class="net-rule__body">
|
||||
<t-form-item :label="$t('settings.sandbox.ruleHost')">
|
||||
<t-input v-model="rule.host" placeholder="api.example.com" />
|
||||
</t-form-item>
|
||||
<div v-for="(header, headerIndex) in rule.headers" :key="`header-${headerIndex}`"
|
||||
class="net-row net-row--double">
|
||||
<t-input v-model="header.name" :placeholder="$t('settings.sandbox.headerName')" />
|
||||
<t-input v-model="header.value" type="password"
|
||||
:placeholder="isStoredNetworkSecretRecoverable(
|
||||
header,
|
||||
header.originalHost,
|
||||
header.originalName,
|
||||
rule.host,
|
||||
header.name,
|
||||
)
|
||||
? $t('settings.sandbox.secretKeepHint')
|
||||
: $t('settings.sandbox.headerValue')" />
|
||||
<t-button variant="text" shape="square" size="small"
|
||||
:aria-label="$t('common.delete')" @click="rule.headers.splice(headerIndex, 1)">
|
||||
<t-icon name="close" />
|
||||
</t-button>
|
||||
</div>
|
||||
<t-button variant="text" size="small"
|
||||
@click="rule.headers.push({ name: '', value: '' })">
|
||||
<template #icon><t-icon name="add" /></template>
|
||||
{{ $t('settings.sandbox.addHeader') }}
|
||||
</t-button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
|
|
@ -512,6 +753,7 @@ import {
|
|||
type SandboxCubeConfig,
|
||||
type SandboxE2BConfig,
|
||||
type SandboxDockerConfig,
|
||||
type SandboxNetworkPolicy,
|
||||
type SandboxTemplate,
|
||||
isNamedSandboxBackend,
|
||||
NAMED_SANDBOX_BACKEND_TYPES,
|
||||
|
|
@ -581,6 +823,92 @@ const docker = reactive<SandboxDockerConfig>({})
|
|||
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.
|
||||
const denyEgressByDefault = ref(false)
|
||||
const allowPublicInbound = ref(false)
|
||||
const allowOutRows = ref<string[]>([])
|
||||
const denyOutRows = ref<string[]>([])
|
||||
|
||||
type CubeRuleForm = {
|
||||
name: string
|
||||
scheme?: string
|
||||
sni?: string
|
||||
host?: string
|
||||
methodsText: string
|
||||
path?: string
|
||||
deny: boolean
|
||||
audit?: string
|
||||
expanded: boolean
|
||||
inject: {
|
||||
header: string
|
||||
secret: string
|
||||
format: string
|
||||
stored?: boolean
|
||||
originalRuleName?: string
|
||||
originalHeader?: string
|
||||
}[]
|
||||
}
|
||||
type E2BRuleForm = {
|
||||
host: string
|
||||
expanded: boolean
|
||||
headers: {
|
||||
name: string
|
||||
value: string
|
||||
stored?: boolean
|
||||
originalHost?: string
|
||||
originalName?: string
|
||||
}[]
|
||||
}
|
||||
const cubeRules = ref<CubeRuleForm[]>([])
|
||||
const e2bHostRules = ref<E2BRuleForm[]>([])
|
||||
|
||||
function isStoredNetworkSecretRecoverable(
|
||||
row: { stored?: boolean },
|
||||
originalParentIdentity: string | undefined,
|
||||
originalChildIdentity: string | undefined,
|
||||
currentParentIdentity: string,
|
||||
currentChildIdentity: string,
|
||||
): boolean {
|
||||
return row.stored === true
|
||||
&& originalParentIdentity === currentParentIdentity.trim()
|
||||
&& originalChildIdentity === currentChildIdentity.trim()
|
||||
}
|
||||
|
||||
function addCubeRule() {
|
||||
for (const rule of cubeRules.value) rule.expanded = false
|
||||
cubeRules.value.push({
|
||||
name: '', scheme: 'https', sni: '', host: '',
|
||||
methodsText: '', path: '', deny: false, audit: '', expanded: true, inject: [],
|
||||
})
|
||||
}
|
||||
|
||||
function addE2BHostRule() {
|
||||
for (const rule of e2bHostRules.value) rule.expanded = false
|
||||
e2bHostRules.value.push({ host: '', expanded: true, headers: [] })
|
||||
}
|
||||
|
||||
// Both providers refuse a domain allow-list without a deny-all fallback, and
|
||||
// for a good reason: destinations never resolved through the sandbox's DNS
|
||||
// stay reachable, so the list would be decorative. Warn here rather than
|
||||
// letting the save round-trip fail.
|
||||
const domainAllowNeedsDenyAll = computed(() => {
|
||||
if (denyEgressByDefault.value) return false
|
||||
if (denyOutRows.value.some((row) => denyOutRowCoversAllIPv4(row))) return false
|
||||
return allowOutRows.value.some((row) => {
|
||||
const value = row.trim()
|
||||
if (!value) return false
|
||||
return !/^[0-9./]+$/.test(value)
|
||||
})
|
||||
})
|
||||
|
||||
// Mirrors types.DenyOutCoversAllIPv4: net.ParseCIDR collapses any IPv4 /0
|
||||
// onto 0.0.0.0/0, so 1.2.3.4/0 is a real deny-all, not a false warning.
|
||||
function denyOutRowCoversAllIPv4(row: string): boolean {
|
||||
const value = row.trim()
|
||||
if (value === '0.0.0.0/0') return true
|
||||
return /^\d{1,3}(?:\.\d{1,3}){3}\/0$/.test(value)
|
||||
}
|
||||
const inFlightFromSkills = ref(false)
|
||||
const templates = ref<SandboxTemplate[]>([])
|
||||
const templatesLoading = ref(false)
|
||||
|
|
@ -686,11 +1014,19 @@ const pendingCheckNames = computed(() => (checkResult.value?.checks || [])
|
|||
.filter((item) => item.ok === null && item.reason === PENDING_SKIP_REASON)
|
||||
.map((item) => checkLabel(item.name)))
|
||||
|
||||
const EGRESS_RESTRICTED_REASON = 'egress_restricted_by_policy'
|
||||
const egressRestrictedByPolicy = computed(() => (checkResult.value?.checks || []).some(
|
||||
(item) => item.reason === EGRESS_RESTRICTED_REASON,
|
||||
))
|
||||
|
||||
// Says which layer the verdict covers, so "检测通过" is not read as "everything
|
||||
// works" after a connection-only probe.
|
||||
const checkScopeHint = computed(() => (pendingCheckNames.value.length
|
||||
? t('settings.sandbox.checkScopeConnection')
|
||||
: t('settings.sandbox.checkScopeFull')))
|
||||
// works" after a connection-only probe, or after egress was skipped because
|
||||
// the config denies outbound access by policy.
|
||||
const checkScopeHint = computed(() => {
|
||||
if (pendingCheckNames.value.length) return t('settings.sandbox.checkScopeConnection')
|
||||
if (egressRestrictedByPolicy.value) return t('settings.sandbox.checkScopePolicyRestricted')
|
||||
return t('settings.sandbox.checkScopeFull')
|
||||
})
|
||||
|
||||
function checkDetail(item: SandboxCheckItem): string {
|
||||
if (item.message) return item.message
|
||||
|
|
@ -789,6 +1125,43 @@ function reset() {
|
|||
isMaskedSecret(value) ? { key, value: '', stored: true } : { key, value }
|
||||
))
|
||||
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) => ({
|
||||
name: rule.name || '',
|
||||
scheme: rule.scheme || '',
|
||||
sni: rule.sni || '',
|
||||
host: rule.host || '',
|
||||
methodsText: (rule.methods || []).join(', '),
|
||||
path: rule.path || '',
|
||||
deny: rule.deny === true,
|
||||
audit: rule.audit || '',
|
||||
expanded: false,
|
||||
inject: (rule.inject || []).map((inject) => ({
|
||||
header: inject.header || '',
|
||||
// A stored secret arrives masked; keep the input empty and say
|
||||
// "configured", exactly like the env var rows do.
|
||||
secret: isMaskedSecret(inject.secret) ? '' : (inject.secret || ''),
|
||||
format: inject.format || '',
|
||||
stored: isMaskedSecret(inject.secret),
|
||||
originalRuleName: rule.name?.trim() || '',
|
||||
originalHeader: inject.header?.trim() || '',
|
||||
})),
|
||||
}))
|
||||
e2bHostRules.value = (net.e2b_host_rules || []).map((rule) => ({
|
||||
host: rule.host || '',
|
||||
expanded: false,
|
||||
headers: Object.entries(rule.headers || {}).map(([name, value]) => ({
|
||||
name,
|
||||
value: isMaskedSecret(value) ? '' : value,
|
||||
stored: isMaskedSecret(value),
|
||||
originalHost: rule.host?.trim() || '',
|
||||
originalName: name.trim(),
|
||||
})),
|
||||
}))
|
||||
checkResult.value = null
|
||||
conflict.value = null
|
||||
nameError.value = ''
|
||||
|
|
@ -802,10 +1175,17 @@ 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()
|
||||
}
|
||||
|
||||
|
|
@ -1072,6 +1452,7 @@ function collectPayload(): SandboxConfig {
|
|||
allow_private_endpoints: allowPrivateEndpoints.value || undefined,
|
||||
env_vars: envVars,
|
||||
skill_rollout: skillRollout.value,
|
||||
network: collectNetworkPolicy(),
|
||||
}
|
||||
// Send only the selected backend's block so an unused one cannot fail
|
||||
// validation (e.g. a stale private URL left in the other tab).
|
||||
|
|
@ -1081,6 +1462,84 @@ function collectPayload(): SandboxConfig {
|
|||
return payload
|
||||
}
|
||||
|
||||
// Sends the policy as its own block. Empty lists are dropped so a config the
|
||||
// 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.
|
||||
if (backend.value === 'docker') {
|
||||
return policy
|
||||
}
|
||||
if (denyEgressByDefault.value) policy.deny_egress_by_default = true
|
||||
if (allowPublicInbound.value) policy.allow_public_inbound = true
|
||||
|
||||
if (backend.value !== 'docker') {
|
||||
const allowOut = allowOutRows.value.map((row) => row.trim()).filter(Boolean)
|
||||
const denyOut = denyOutRows.value.map((row) => row.trim()).filter(Boolean)
|
||||
if (allowOut.length) policy.allow_out = allowOut
|
||||
if (denyOut.length) policy.deny_out = denyOut
|
||||
}
|
||||
|
||||
if (backend.value === 'cube' && cubeRules.value.length) {
|
||||
policy.cube_rules = cubeRules.value.map((rule) => ({
|
||||
name: rule.name.trim(),
|
||||
scheme: rule.scheme || undefined,
|
||||
sni: rule.sni?.trim() || undefined,
|
||||
host: rule.host?.trim() || undefined,
|
||||
methods: rule.methodsText
|
||||
.split(',')
|
||||
.map((method) => method.trim().toUpperCase())
|
||||
.filter(Boolean),
|
||||
path: rule.path?.trim() || undefined,
|
||||
deny: rule.deny || undefined,
|
||||
audit: rule.audit || undefined,
|
||||
inject: rule.deny
|
||||
? undefined
|
||||
: rule.inject
|
||||
.filter((inject) => inject.header.trim())
|
||||
.map((inject) => ({
|
||||
header: inject.header.trim(),
|
||||
// Re-attach the placeholder only while the server-side lookup key
|
||||
// remains the identity under which this credential was loaded.
|
||||
secret: isStoredNetworkSecretRecoverable(
|
||||
inject,
|
||||
inject.originalRuleName,
|
||||
inject.originalHeader,
|
||||
rule.name,
|
||||
inject.header,
|
||||
)
|
||||
&& inject.secret === ''
|
||||
? secretPlaceholder
|
||||
: inject.secret,
|
||||
format: inject.format?.trim() || undefined,
|
||||
})),
|
||||
}))
|
||||
}
|
||||
if (backend.value === 'e2b' && e2bHostRules.value.length) {
|
||||
policy.e2b_host_rules = e2bHostRules.value.map((rule) => {
|
||||
const headers: Record<string, string> = {}
|
||||
for (const header of rule.headers) {
|
||||
const name = header.name.trim()
|
||||
if (!name) continue
|
||||
headers[name] = isStoredNetworkSecretRecoverable(
|
||||
header,
|
||||
header.originalHost,
|
||||
header.originalName,
|
||||
rule.host,
|
||||
header.name,
|
||||
)
|
||||
&& header.value === ''
|
||||
? secretPlaceholder
|
||||
: header.value
|
||||
}
|
||||
return { host: rule.host.trim(), headers }
|
||||
})
|
||||
}
|
||||
return policy
|
||||
}
|
||||
|
||||
function close() {
|
||||
stopTemplatePolling()
|
||||
emit('update:visible', false)
|
||||
|
|
@ -1707,26 +2166,127 @@ onUnmounted(stopTemplatePolling)
|
|||
}
|
||||
}
|
||||
|
||||
.runtime-fields {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.runtime-fields :deep(.t-form__item) {
|
||||
margin-bottom: 0;
|
||||
}
|
||||
|
||||
.runtime-fields :deep(.t-input-number) {
|
||||
width: 100%;
|
||||
max-width: 240px;
|
||||
}
|
||||
|
||||
.runtime-fields .section-help--field {
|
||||
margin-bottom: 16px;
|
||||
.net-list {
|
||||
margin-top: 16px;
|
||||
}
|
||||
|
||||
&:last-child {
|
||||
margin-bottom: 0;
|
||||
}
|
||||
.net-list__title {
|
||||
font-size: 13px;
|
||||
font-weight: 600;
|
||||
color: var(--td-text-color-primary);
|
||||
}
|
||||
|
||||
.net-row {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 1fr) 32px;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
|
||||
.net-row--double {
|
||||
grid-template-columns: minmax(140px, 0.7fr) minmax(160px, 1.3fr) 32px;
|
||||
}
|
||||
|
||||
.net-row--triple {
|
||||
grid-template-columns: minmax(120px, 0.6fr) minmax(140px, 1fr) minmax(120px, 0.8fr) 32px;
|
||||
}
|
||||
|
||||
.net-rule {
|
||||
border: 1px solid var(--td-component-border);
|
||||
border-radius: 6px;
|
||||
padding: 12px;
|
||||
margin-bottom: 12px;
|
||||
}
|
||||
|
||||
.net-rule--collapsible {
|
||||
padding: 0;
|
||||
margin-bottom: 2px;
|
||||
border: 0;
|
||||
border-radius: 4px;
|
||||
}
|
||||
|
||||
.net-rule--collapsible.is-open {
|
||||
margin-bottom: 6px;
|
||||
border: 1px solid var(--td-component-border);
|
||||
}
|
||||
|
||||
.net-rule__bar {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 1fr) 22px;
|
||||
align-items: center;
|
||||
min-height: 26px;
|
||||
padding: 0 2px;
|
||||
}
|
||||
|
||||
.net-rule__toggle {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
min-width: 0;
|
||||
height: 26px;
|
||||
padding: 0 4px;
|
||||
border: 0;
|
||||
background: transparent;
|
||||
color: var(--td-text-color-secondary);
|
||||
cursor: pointer;
|
||||
border-radius: 4px;
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
.net-rule__toggle:hover {
|
||||
background: var(--td-bg-color-container-hover);
|
||||
color: var(--td-text-color-primary);
|
||||
}
|
||||
|
||||
.net-rule__name {
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
font-size: 12px;
|
||||
line-height: 18px;
|
||||
color: var(--td-text-color-primary);
|
||||
}
|
||||
|
||||
.net-rule__name.is-empty {
|
||||
color: var(--td-text-color-placeholder);
|
||||
}
|
||||
|
||||
.net-rule__remove {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 22px;
|
||||
height: 22px;
|
||||
padding: 0;
|
||||
border: 0;
|
||||
background: transparent;
|
||||
color: var(--td-text-color-placeholder);
|
||||
cursor: pointer;
|
||||
border-radius: 4px;
|
||||
}
|
||||
|
||||
.net-rule__remove:hover {
|
||||
color: var(--td-error-color);
|
||||
background: var(--td-bg-color-container-hover);
|
||||
}
|
||||
|
||||
.net-rule__body {
|
||||
padding: 8px 10px 10px;
|
||||
border-top: 1px solid var(--td-component-border);
|
||||
}
|
||||
|
||||
.net-inject {
|
||||
margin-top: 8px;
|
||||
}
|
||||
|
||||
.env-rows {
|
||||
|
|
@ -1767,7 +2327,7 @@ onUnmounted(stopTemplatePolling)
|
|||
|
||||
&--under-title {
|
||||
margin-top: 5px;
|
||||
max-width: 470px;
|
||||
max-width: 540px;
|
||||
}
|
||||
|
||||
/* Sits under an input inside the same form item. */
|
||||
|
|
|
|||
|
|
@ -1127,7 +1127,48 @@ export default {
|
|||
sectionRuntimeEnvironment: 'Runtime environment',
|
||||
sectionTemplate: 'Runtime template',
|
||||
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',
|
||||
egressDefault: 'Default egress',
|
||||
egressAllowAll: 'Allow public network (default)',
|
||||
egressDenyAll: 'Deny by default',
|
||||
egressPrecedence: 'Evaluation order: allow, deny, then the default. Allow rules take precedence over deny rules.',
|
||||
allowOut: 'Allowed destinations',
|
||||
allowOutPlaceholder: 'Domain / IP / CIDR, for example *.example.com',
|
||||
allowOutHelp: 'Supports IPv4, CIDR, domains, and single-label wildcards such as *.example.com (which do not match the root domain).',
|
||||
denyOut: 'Denied destinations',
|
||||
denyOutPlaceholder: 'IP / CIDR only, for example 169.254.169.254/32',
|
||||
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.',
|
||||
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',
|
||||
ruleName: 'Rule name',
|
||||
ruleScheme: 'Scheme',
|
||||
ruleSni: 'SNI',
|
||||
ruleHost: 'Host',
|
||||
ruleMethods: 'HTTP methods',
|
||||
rulePath: 'Path',
|
||||
ruleAction: 'Action',
|
||||
ruleAllow: 'Allow',
|
||||
ruleDeny: 'Deny',
|
||||
ruleAudit: 'Audit level',
|
||||
ruleInject: 'Inject headers',
|
||||
headerName: 'Header name',
|
||||
headerValue: 'Header value',
|
||||
addTarget: 'Add destination',
|
||||
addRule: 'Add rule',
|
||||
addHeader: 'Add header',
|
||||
removeRule: 'Remove rule',
|
||||
noConfigs: 'No sandbox yet. Agents without a workspace configuration will not run skill scripts.',
|
||||
identityFieldHint: 'While this config owns sandboxes, these cannot be changed: backend type, API endpoint, API key, sandbox domain, proxy endpoint.',
|
||||
connectionLockedBySkills: 'This sandbox already has skills. Connection, credentials, and DNS would retarget the skill snapshot, and DNS only applies after a template rebuild. Create a new sandbox instead.',
|
||||
|
|
@ -1257,7 +1298,7 @@ export default {
|
|||
httpTimeout: 'HTTP timeout (s)',
|
||||
httpTimeoutHelp: 'How long a management call to the backend may take before the endpoint counts as unreachable. Empty means 30 seconds.',
|
||||
sandboxTtl: 'Sandbox TTL (s)',
|
||||
sandboxTtlHelp: 'How long an idle sandbox survives before the provider reclaims it. Too short and a resumed session has to rebuild it; too long and idle instances keep billing. Empty means the backend default.',
|
||||
sandboxTtlHelp: 'How long until the sandbox is paused',
|
||||
dockerImage: 'Docker image',
|
||||
dockerHost: 'Docker daemon endpoint',
|
||||
dockerHostHelp: 'Empty follows the local docker CLI (DOCKER_HOST or the current docker context), so you do not have to type /var/run/docker.sock. For a remote daemon use tcp://host:2376, fill in the TLS certificate directory, and turn on "allow private endpoints" for RFC1918 addresses.',
|
||||
|
|
@ -1266,9 +1307,11 @@ export default {
|
|||
dockerIdleTtl: 'Idle reclaim (seconds)',
|
||||
dockerIdleTtlHelp: 'The Docker daemon has no idle timeout of its own. A container that runs no command for this long is reclaimed by WeKnora and rebuilt when the session continues. Empty means 1800 seconds.',
|
||||
dockerCpuLimit: 'CPU cores',
|
||||
dockerCpuLimitHelp: 'CPU cores available to one sandbox; 0 uses the built-in default.',
|
||||
dockerMemoryLimit: 'Memory limit (MB)',
|
||||
dockerMemoryLimitHelp: 'Memory limit in MB for one sandbox; 0 uses the built-in default.',
|
||||
dockerPidsLimit: 'Process limit',
|
||||
dockerResourceHelp: 'Caps for one sandbox container. Empty means 2 cores / 2048 MB / 512 processes.',
|
||||
dockerPidsLimitHelp: 'Maximum processes one sandbox can create; 0 uses the built-in default.',
|
||||
dockerNetworkMode: 'Network mode',
|
||||
dockerNetworkModeHelp: 'Defaults to bridge, which skills need to install packages. Choose none for no egress at all. Docker filters by network only; per-domain rules are not possible here.',
|
||||
dockerNetworkBridge: 'bridge (egress allowed)',
|
||||
|
|
@ -1294,6 +1337,7 @@ export default {
|
|||
checkFailed: 'Some checks failed',
|
||||
checkScopeConnection: 'Only the control plane was verified: the endpoint responds and the credential is valid. Whether a script actually runs is still unverified.',
|
||||
checkScopeFull: 'Endpoint, credential, template, in-sandbox execution and outbound network were all verified for real.',
|
||||
checkScopePolicyRestricted: 'Outbound access is restricted by policy, so egress was not probed. Endpoint, credential, template and in-sandbox execution were verified.',
|
||||
checkPendingHint: '{names} can only be confirmed by a full verification, which creates a throwaway sandbox, runs one script and destroys it.',
|
||||
noVolumeSupport: 'This backend does not support volume mounts; skills relying on a shared volume will be unavailable.',
|
||||
skipReasons: {
|
||||
|
|
@ -1301,6 +1345,7 @@ export default {
|
|||
control_plane_unreachable: 'Skipped: control plane unreachable',
|
||||
sandbox_not_created: 'Skipped: sandbox was not created',
|
||||
sandbox_exec_failed: 'Skipped: in-sandbox execution failed',
|
||||
egress_restricted_by_policy: 'Restricted by network policy (this config denies egress by default)',
|
||||
},
|
||||
checks: {
|
||||
client_build: 'Client construction',
|
||||
|
|
|
|||
|
|
@ -5071,7 +5071,48 @@ export default {
|
|||
sectionRuntimeEnvironment: 'Runtime environment',
|
||||
sectionTemplate: 'Runtime template',
|
||||
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',
|
||||
egressDefault: 'Default egress',
|
||||
egressAllowAll: 'Allow public network (default)',
|
||||
egressDenyAll: 'Deny by default',
|
||||
egressPrecedence: 'Evaluation order: allow, deny, then the default. Allow rules take precedence over deny rules.',
|
||||
allowOut: 'Allowed destinations',
|
||||
allowOutPlaceholder: 'Domain / IP / CIDR, for example *.example.com',
|
||||
allowOutHelp: 'Supports IPv4, CIDR, domains, and single-label wildcards such as *.example.com (which do not match the root domain).',
|
||||
denyOut: 'Denied destinations',
|
||||
denyOutPlaceholder: 'IP / CIDR only, for example 169.254.169.254/32',
|
||||
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.',
|
||||
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',
|
||||
ruleName: 'Rule name',
|
||||
ruleScheme: 'Scheme',
|
||||
ruleSni: 'SNI',
|
||||
ruleHost: 'Host',
|
||||
ruleMethods: 'HTTP methods',
|
||||
rulePath: 'Path',
|
||||
ruleAction: 'Action',
|
||||
ruleAllow: 'Allow',
|
||||
ruleDeny: 'Deny',
|
||||
ruleAudit: 'Audit level',
|
||||
ruleInject: 'Inject headers',
|
||||
headerName: 'Header name',
|
||||
headerValue: 'Header value',
|
||||
addTarget: 'Add destination',
|
||||
addRule: 'Add rule',
|
||||
addHeader: 'Add header',
|
||||
removeRule: 'Remove rule',
|
||||
noConfigs: '아직 샌드박스가 없습니다. 워크스페이스 설정을 선택하지 않은 에이전트는 스킬 스크립트를 실행하지 않습니다.',
|
||||
identityFieldHint: 'While this config owns sandboxes, these cannot be changed: backend type, API endpoint, API key, sandbox domain, proxy endpoint.',
|
||||
connectionLockedBySkills: '이 샌드박스에는 이미 Skill이 있습니다. 연결, 자격 증명, DNS를 바꾸면 스킬 스냅샷의 환경이 달라지고, DNS는 템플릿을 재구축해야 적용됩니다. 새 샌드박스를 만드세요.',
|
||||
|
|
@ -5201,7 +5242,7 @@ export default {
|
|||
httpTimeout: 'HTTP timeout (s)',
|
||||
httpTimeoutHelp: '백엔드 관리 API 호출을 기다리는 상한입니다. 초과하면 엔드포인트를 사용할 수 없는 것으로 간주합니다. 비워 두면 30초입니다.',
|
||||
sandboxTtl: 'Sandbox TTL (s)',
|
||||
sandboxTtlHelp: '유휴 샌드박스가 회수되기까지의 시간입니다. 너무 짧으면 세션을 이어갈 때 다시 만들어야 하고, 너무 길면 유휴 인스턴스에 계속 요금이 발생합니다. 비워 두면 백엔드 기본값을 사용합니다.',
|
||||
sandboxTtlHelp: '샌드박스가 일시 중지되기까지의 시간',
|
||||
dockerImage: 'Docker image',
|
||||
dockerHost: 'Docker daemon endpoint',
|
||||
dockerHostHelp: 'Empty follows the local docker CLI (DOCKER_HOST or the current docker context), so you do not have to type /var/run/docker.sock. For a remote daemon use tcp://host:2376, fill in the TLS certificate directory, and turn on "allow private endpoints" for RFC1918 addresses.',
|
||||
|
|
@ -5210,9 +5251,11 @@ export default {
|
|||
dockerIdleTtl: 'Idle reclaim (seconds)',
|
||||
dockerIdleTtlHelp: 'The Docker daemon has no idle timeout of its own. A container that runs no command for this long is reclaimed by WeKnora and rebuilt when the session continues. Empty means 1800 seconds.',
|
||||
dockerCpuLimit: 'CPU cores',
|
||||
dockerCpuLimitHelp: 'CPU cores available to one sandbox; 0 uses the built-in default.',
|
||||
dockerMemoryLimit: 'Memory limit (MB)',
|
||||
dockerMemoryLimitHelp: 'Memory limit in MB for one sandbox; 0 uses the built-in default.',
|
||||
dockerPidsLimit: 'Process limit',
|
||||
dockerResourceHelp: 'Caps for one sandbox container. Empty means 2 cores / 2048 MB / 512 processes.',
|
||||
dockerPidsLimitHelp: 'Maximum processes one sandbox can create; 0 uses the built-in default.',
|
||||
dockerNetworkMode: 'Network mode',
|
||||
dockerNetworkModeHelp: 'Defaults to bridge, which skills need to install packages. Choose none for no egress at all. Docker filters by network only; per-domain rules are not possible here.',
|
||||
dockerNetworkBridge: 'bridge (egress allowed)',
|
||||
|
|
@ -5238,14 +5281,16 @@ export default {
|
|||
checkFailed: 'Some checks failed',
|
||||
checkScopeConnection: '이번에는 컨트롤 플레인만 확인했습니다. 엔드포인트는 응답하고 자격 증명도 유효하지만, 스크립트가 실제로 실행되는지는 아직 확인되지 않았습니다.',
|
||||
checkScopeFull: '엔드포인트, 자격 증명, 템플릿, 샌드박스 내 실행, 외부 통신까지 모두 실제로 검증했습니다.',
|
||||
checkScopePolicyRestricted: '네트워크 정책으로 외부 통신이 제한되어 외부 연결은 실제로 확인하지 않았습니다. 엔드포인트, 자격 증명, 템플릿, 샌드박스 내 실행은 검증했습니다.',
|
||||
checkPendingHint: '{names}은(는) 전체 검증으로만 확인할 수 있습니다. 임시 샌드박스를 실제로 만들어 스크립트를 한 번 실행한 뒤 삭제합니다.',
|
||||
noVolumeSupport: 'This backend does not support volume mounts; skills relying on a shared volume will be unavailable.',
|
||||
skipReasons: {
|
||||
needs_deep_check: '전체 검증 필요',
|
||||
control_plane_unreachable: '컨트롤 플레인에 연결할 수 없어 건너뜀',
|
||||
sandbox_not_created: '샌드박스가 생성되지 않아 건너뜀',
|
||||
sandbox_exec_failed: '샌드박스 내 실행 실패로 건너뜀',
|
||||
egress_restricted_by_policy: '네트워크 정책에 의해 제한됨(이 구성은 기본적으로 외부 통신을 차단함)',
|
||||
},
|
||||
noVolumeSupport: 'This backend does not support volume mounts; skills relying on a shared volume will be unavailable.',
|
||||
checks: {
|
||||
client_build: 'Client construction',
|
||||
api_url_reachable: 'Endpoint reachability',
|
||||
|
|
|
|||
|
|
@ -5071,7 +5071,48 @@ export default {
|
|||
sectionRuntimeEnvironment: 'Runtime environment',
|
||||
sectionTemplate: 'Runtime template',
|
||||
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',
|
||||
egressDefault: 'Default egress',
|
||||
egressAllowAll: 'Allow public network (default)',
|
||||
egressDenyAll: 'Deny by default',
|
||||
egressPrecedence: 'Evaluation order: allow, deny, then the default. Allow rules take precedence over deny rules.',
|
||||
allowOut: 'Allowed destinations',
|
||||
allowOutPlaceholder: 'Domain / IP / CIDR, for example *.example.com',
|
||||
allowOutHelp: 'Supports IPv4, CIDR, domains, and single-label wildcards such as *.example.com (which do not match the root domain).',
|
||||
denyOut: 'Denied destinations',
|
||||
denyOutPlaceholder: 'IP / CIDR only, for example 169.254.169.254/32',
|
||||
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.',
|
||||
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',
|
||||
ruleName: 'Rule name',
|
||||
ruleScheme: 'Scheme',
|
||||
ruleSni: 'SNI',
|
||||
ruleHost: 'Host',
|
||||
ruleMethods: 'HTTP methods',
|
||||
rulePath: 'Path',
|
||||
ruleAction: 'Action',
|
||||
ruleAllow: 'Allow',
|
||||
ruleDeny: 'Deny',
|
||||
ruleAudit: 'Audit level',
|
||||
ruleInject: 'Inject headers',
|
||||
headerName: 'Header name',
|
||||
headerValue: 'Header value',
|
||||
addTarget: 'Add destination',
|
||||
addRule: 'Add rule',
|
||||
addHeader: 'Add header',
|
||||
removeRule: 'Remove rule',
|
||||
noConfigs: 'Песочниц пока нет. Агенты без конфигурации пространства не выполняют скрипты навыков.',
|
||||
identityFieldHint: 'While this config owns sandboxes, these cannot be changed: backend type, API endpoint, API key, sandbox domain, proxy endpoint.',
|
||||
connectionLockedBySkills: 'В этой песочнице уже установлены навыки. Смена подключения, учётных данных или DNS меняет среду снимка, а DNS применяется только после пересборки шаблона. Создайте новую песочницу.',
|
||||
|
|
@ -5201,7 +5242,7 @@ export default {
|
|||
httpTimeout: 'HTTP timeout (s)',
|
||||
httpTimeoutHelp: 'Сколько ждать ответа от управляющего API бэкенда, прежде чем считать эндпоинт недоступным. Пусто — 30 секунд.',
|
||||
sandboxTtl: 'Sandbox TTL (s)',
|
||||
sandboxTtlHelp: 'Сколько простаивающая песочница живёт до освобождения провайдером. Слишком мало — при продолжении сессии её придётся создавать заново, слишком много — простаивающие экземпляры продолжают тарифицироваться. Пусто — значение бэкенда по умолчанию.',
|
||||
sandboxTtlHelp: 'Через сколько песочница будет приостановлена',
|
||||
dockerImage: 'Docker image',
|
||||
dockerHost: 'Docker daemon endpoint',
|
||||
dockerHostHelp: 'Empty follows the local docker CLI (DOCKER_HOST or the current docker context), so you do not have to type /var/run/docker.sock. For a remote daemon use tcp://host:2376, fill in the TLS certificate directory, and turn on "allow private endpoints" for RFC1918 addresses.',
|
||||
|
|
@ -5210,9 +5251,11 @@ export default {
|
|||
dockerIdleTtl: 'Idle reclaim (seconds)',
|
||||
dockerIdleTtlHelp: 'The Docker daemon has no idle timeout of its own. A container that runs no command for this long is reclaimed by WeKnora and rebuilt when the session continues. Empty means 1800 seconds.',
|
||||
dockerCpuLimit: 'CPU cores',
|
||||
dockerCpuLimitHelp: 'CPU cores available to one sandbox; 0 uses the built-in default.',
|
||||
dockerMemoryLimit: 'Memory limit (MB)',
|
||||
dockerMemoryLimitHelp: 'Memory limit in MB for one sandbox; 0 uses the built-in default.',
|
||||
dockerPidsLimit: 'Process limit',
|
||||
dockerResourceHelp: 'Caps for one sandbox container. Empty means 2 cores / 2048 MB / 512 processes.',
|
||||
dockerPidsLimitHelp: 'Maximum processes one sandbox can create; 0 uses the built-in default.',
|
||||
dockerNetworkMode: 'Network mode',
|
||||
dockerNetworkModeHelp: 'Defaults to bridge, which skills need to install packages. Choose none for no egress at all. Docker filters by network only; per-domain rules are not possible here.',
|
||||
dockerNetworkBridge: 'bridge (egress allowed)',
|
||||
|
|
@ -5238,14 +5281,16 @@ export default {
|
|||
checkFailed: 'Some checks failed',
|
||||
checkScopeConnection: 'Проверена только плоскость управления: эндпоинт отвечает, ключ действителен. Запустится ли скрипт на самом деле — пока не проверено.',
|
||||
checkScopeFull: 'Эндпоинт, ключ, шаблон, выполнение внутри песочницы и исходящая сеть проверены по-настоящему.',
|
||||
checkScopePolicyRestricted: 'Исходящий доступ ограничен политикой, поэтому исходящая сеть не зондировалась. Эндпоинт, ключ, шаблон и выполнение внутри песочницы проверены.',
|
||||
checkPendingHint: '{names} можно подтвердить только полной проверкой: она создаёт временную песочницу, запускает один скрипт и удаляет её.',
|
||||
noVolumeSupport: 'This backend does not support volume mounts; skills relying on a shared volume will be unavailable.',
|
||||
skipReasons: {
|
||||
needs_deep_check: 'Нужна полная проверка',
|
||||
control_plane_unreachable: 'Пропущено: плоскость управления недоступна',
|
||||
sandbox_not_created: 'Пропущено: песочница не создана',
|
||||
sandbox_exec_failed: 'Пропущено: выполнение в песочнице не удалось',
|
||||
egress_restricted_by_policy: 'Ограничено сетевой политикой (эта конфигурация по умолчанию запрещает исходящий трафик)',
|
||||
},
|
||||
noVolumeSupport: 'This backend does not support volume mounts; skills relying on a shared volume will be unavailable.',
|
||||
checks: {
|
||||
client_build: 'Client construction',
|
||||
api_url_reachable: 'Endpoint reachability',
|
||||
|
|
|
|||
|
|
@ -5073,7 +5073,48 @@ export default {
|
|||
sectionRuntimeEnvironment: '运行环境',
|
||||
sectionTemplate: '运行模板',
|
||||
sectionRuntime: '执行设置',
|
||||
sectionNetwork: '网络策略',
|
||||
sectionEnvironment: '环境变量',
|
||||
networkHint: '控制该配置下所有沙箱的出入网。改动只影响之后新建的沙箱,已有沙箱按原策略运行到回收。',
|
||||
inboundAccess: '入站访问',
|
||||
inboundAccessHelp: '默认要求凭证:沙箱公网 URL 必须携带创建时签发的 token。',
|
||||
inboundTokenRequired: '要求凭证(默认)',
|
||||
inboundPublic: '公网可访问',
|
||||
egressDefault: '出站默认',
|
||||
egressAllowAll: '允许公网(默认)',
|
||||
egressDenyAll: '默认拒绝',
|
||||
egressPrecedence: '判定顺序:放行 → 拒绝 → 默认值。放行优先于拒绝。',
|
||||
allowOut: '放行目标',
|
||||
allowOutPlaceholder: '域名 / IP / CIDR,例如 *.example.com',
|
||||
allowOutHelp: '支持 IPv4、CIDR、域名和单层通配 *.example.com(通配不匹配主域)。',
|
||||
denyOut: '拒绝目标',
|
||||
denyOutPlaceholder: '仅支持 IP / CIDR,例如 169.254.169.254/32',
|
||||
denyOutHelp: '拒绝只按目的 IP 匹配,因此不支持域名。',
|
||||
domainAllowNeedsDenyAll: '放行目标里有域名时,必须同时选择「默认拒绝」或在拒绝目标中加入 0.0.0.0/0,否则白名单不生效。',
|
||||
cubeL7Rules: 'HTTP 访问规则(L7)',
|
||||
cubeL7RulesHelp: '每条规则必须填 host 或 sni,网络层只从这两个字段提取放行目标。字段之间是 AND,method 列表内部是 OR。仅 HTTP 80 / HTTPS 443 生效。',
|
||||
e2bHostRules: 'Host 请求变换',
|
||||
e2bHostRulesHelp: '按 host 注入 header。规则本身不授权出网,host 必须同时出现在放行目标里。',
|
||||
ruleUntitled: '未命名规则',
|
||||
expandRule: '展开规则',
|
||||
collapseRule: '收起规则',
|
||||
ruleName: '规则名',
|
||||
ruleScheme: '协议',
|
||||
ruleSni: 'SNI',
|
||||
ruleHost: 'Host',
|
||||
ruleMethods: 'HTTP 方法',
|
||||
rulePath: '路径',
|
||||
ruleAction: '动作',
|
||||
ruleAllow: '放行',
|
||||
ruleDeny: '拒绝',
|
||||
ruleAudit: '审计级别',
|
||||
ruleInject: '注入 Header',
|
||||
headerName: 'Header 名称',
|
||||
headerValue: 'Header 值',
|
||||
addTarget: '添加目标',
|
||||
addRule: '添加规则',
|
||||
addHeader: '添加 Header',
|
||||
removeRule: '删除该规则',
|
||||
noConfigs: '还没有沙箱配置。智能体未选择空间配置时不会执行技能脚本。',
|
||||
identityFieldHint: '该配置下有沙箱运行时,以下项无法修改:后端类型、API 端点、API Key、沙箱域名、Proxy 端点。',
|
||||
connectionLockedBySkills: '该沙箱已安装 Skill。连接地址、凭据和 DNS 会改变技能快照所属环境,且 DNS 需重建模板才能生效;请新建一份沙箱。',
|
||||
|
|
@ -5203,7 +5244,7 @@ export default {
|
|||
httpTimeout: 'HTTP 超时(秒)',
|
||||
httpTimeoutHelp: '调用沙箱管理接口的等待上限,超过即视为端点不可用。留空按 30 秒。',
|
||||
sandboxTtl: '沙箱 TTL(秒)',
|
||||
sandboxTtlHelp: '沙箱空闲多久后被远端回收。设得太短,会话继续时要重建沙箱;设得太长,闲置实例会一直计费。留空按后端默认值。',
|
||||
sandboxTtlHelp: '沙箱多久之后会暂停',
|
||||
dockerImage: 'Docker 镜像',
|
||||
dockerHost: 'Docker 守护进程地址',
|
||||
dockerHostHelp: '留空跟随本机 docker CLI(DOCKER_HOST 或当前 docker context),不必手填 /var/run/docker.sock。远程守护进程填 tcp://host:2376,必须同时填写 TLS 证书目录,私网地址还要开启「允许访问私网地址」。',
|
||||
|
|
@ -5212,9 +5253,11 @@ export default {
|
|||
dockerIdleTtl: '空闲回收(秒)',
|
||||
dockerIdleTtlHelp: 'Docker 守护进程本身没有空闲超时。容器多久没有执行任何命令就会被 WeKnora 回收,会话继续时重建。留空按 1800 秒。',
|
||||
dockerCpuLimit: 'CPU 核数上限',
|
||||
dockerCpuLimitHelp: '单个沙箱可用的 CPU 核数,0 使用内置默认。',
|
||||
dockerMemoryLimit: '内存上限(MB)',
|
||||
dockerMemoryLimitHelp: '单个沙箱的内存上限(MB),0 使用内置默认。',
|
||||
dockerPidsLimit: '进程数上限',
|
||||
dockerResourceHelp: '单个沙箱容器的资源上限。留空按 2 核 / 2048 MB / 512 进程。',
|
||||
dockerPidsLimitHelp: '单个沙箱可创建的进程数上限,0 使用内置默认。',
|
||||
dockerNetworkMode: '网络模式',
|
||||
dockerNetworkModeHelp: '默认 bridge,技能安装依赖需要出网。选择 none 表示完全禁止出网。Docker 只能按网络隔离,无法按域名放行。',
|
||||
dockerNetworkBridge: 'bridge(允许出网)',
|
||||
|
|
@ -5240,6 +5283,7 @@ export default {
|
|||
checkFailed: '检测未通过',
|
||||
checkScopeConnection: '本次只验证了控制面:端点可达且凭据有效。是否真的能跑起脚本还没有验证。',
|
||||
checkScopeFull: '端点、凭据、模板、沙箱内执行与出网均已真实验证。',
|
||||
checkScopePolicyRestricted: '出网按策略受限,未做真实出网探测;端点、凭据、模板与沙箱内执行已验证。',
|
||||
checkPendingHint: '{names} 需要「完整验证」才能确认:会真实创建一个临时沙箱、执行一次脚本再销毁。',
|
||||
noVolumeSupport: '该后端不支持挂载卷,依赖共享卷的技能将不可用。',
|
||||
skipReasons: {
|
||||
|
|
@ -5247,6 +5291,7 @@ export default {
|
|||
control_plane_unreachable: '控制面不可达,已跳过',
|
||||
sandbox_not_created: '沙箱未创建,已跳过',
|
||||
sandbox_exec_failed: '沙箱内执行失败,已跳过',
|
||||
egress_restricted_by_policy: '按网络策略受限(该配置默认拒绝出网)',
|
||||
},
|
||||
checks: {
|
||||
client_build: '客户端构建',
|
||||
|
|
|
|||
|
|
@ -356,6 +356,11 @@ func SanitizeSandboxConfig(
|
|||
}
|
||||
merged.Cube.DNSServers = dns
|
||||
}
|
||||
// Rejected here rather than at sandbox-create time: the provider's own
|
||||
// error arrives minutes later, on a screen the admin has already left.
|
||||
if err := types.ValidateSandboxNetworkPolicy(merged); err != nil {
|
||||
return nil, apperrors.NewBadRequestError(err.Error())
|
||||
}
|
||||
for _, endpoint := range sandboxConfigEndpoints(merged) {
|
||||
if err := sandbox.ValidateOutboundURLWithPolicy(endpoint, sandbox.OutboundURLPolicy{
|
||||
AllowPrivate: merged.AllowPrivateEndpoints,
|
||||
|
|
@ -1516,5 +1521,21 @@ func sandboxConfigHasSecrets(cfg *types.TenantSandboxConfig) bool {
|
|||
return true
|
||||
}
|
||||
}
|
||||
if cfg.Network != nil {
|
||||
for _, rule := range cfg.Network.CubeRules {
|
||||
for _, inject := range rule.Inject {
|
||||
if inject.Secret != "" {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, rule := range cfg.Network.E2BHostRules {
|
||||
for _, value := range rule.Headers {
|
||||
if value != "" {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
|
|
|||
|
|
@ -34,6 +34,31 @@ func testGlobalSandboxConfig() *sandbox.Config {
|
|||
return cfg
|
||||
}
|
||||
|
||||
func TestSandboxConfigHasSecretsIncludesInjectedHeaders(t *testing.T) {
|
||||
cfg := &types.TenantSandboxConfig{
|
||||
Network: &types.SandboxNetworkPolicy{
|
||||
CubeRules: []types.CubeEgressRule{{
|
||||
Inject: []types.CubeHeaderInject{{Secret: "cube-secret"}},
|
||||
}},
|
||||
},
|
||||
}
|
||||
require.True(t, sandboxConfigHasSecrets(cfg))
|
||||
|
||||
cfg.Network.CubeRules = nil
|
||||
cfg.Network.E2BHostRules = []types.E2BHostRule{{
|
||||
Headers: map[string]string{"X-Key": "e2b-secret"},
|
||||
}}
|
||||
require.True(t, sandboxConfigHasSecrets(cfg))
|
||||
|
||||
cfg.Network = &types.SandboxNetworkPolicy{
|
||||
DenyEgressByDefault: true,
|
||||
CubeRules: []types.CubeEgressRule{{
|
||||
Inject: []types.CubeHeaderInject{{Header: "X-Key"}},
|
||||
}},
|
||||
}
|
||||
require.False(t, sandboxConfigHasSecrets(cfg))
|
||||
}
|
||||
|
||||
func e2bCfg(key, url, domain, template string, ttl int) *types.TenantSandboxConfig {
|
||||
return &types.TenantSandboxConfig{
|
||||
SandboxType: "e2b",
|
||||
|
|
@ -1297,6 +1322,20 @@ func TestSanitizeSandboxConfigPreservesRedactedSecret(t *testing.T) {
|
|||
require.Equal(t, "stored-key", out.E2B.APIKey)
|
||||
}
|
||||
|
||||
func TestSanitizeSandboxConfigRejectsDomainAllowWithoutDenyAll(t *testing.T) {
|
||||
_, err := SanitizeSandboxConfig(&types.TenantSandboxConfig{
|
||||
SandboxType: "cube",
|
||||
Cube: &types.CubeSandboxConfig{
|
||||
APIURL: "https://cube.example.com", ProxyURL: "https://cube.example.com",
|
||||
SandboxDomain: "cube.app", TemplateID: "tpl-1",
|
||||
},
|
||||
Network: &types.SandboxNetworkPolicy{AllowOut: []string{"api.example.com"}},
|
||||
}, nil)
|
||||
|
||||
require.Error(t, err)
|
||||
require.Contains(t, err.Error(), "0.0.0.0/0")
|
||||
}
|
||||
|
||||
func TestSanitizeSandboxConfigPreservesSkillImage(t *testing.T) {
|
||||
t.Setenv("SYSTEM_AES_KEY", strings.Repeat("k", 32))
|
||||
existing := &types.TenantSandboxConfig{
|
||||
|
|
|
|||
|
|
@ -56,6 +56,9 @@ const (
|
|||
skipReasonControlPlaneUnreachable = "control_plane_unreachable"
|
||||
skipReasonSandboxNotCreated = "sandbox_not_created"
|
||||
skipReasonSandboxExecFailed = "sandbox_exec_failed"
|
||||
// The config denies egress by default, so a probe that cannot reach the
|
||||
// internet is the policy working as configured, not a fault.
|
||||
skipReasonEgressRestrictedByPolicy = "egress_restricted_by_policy"
|
||||
)
|
||||
|
||||
// SandboxCheckResponse aggregates the probes for one sandbox configuration.
|
||||
|
|
@ -267,6 +270,9 @@ func (h *SystemHandler) runDeepSandboxCheck(
|
|||
|
||||
handle, err := client.Create(probeCtx, sandbox.RemoteCreateRequest{
|
||||
TemplateID: sandbox.EffectiveTemplateID(cfg),
|
||||
// Probe under the admin's policy: the point of this check is whether
|
||||
// THIS config works, not whether the provider's default does.
|
||||
Network: cfg.Network,
|
||||
Timeout: sandbox.RemoteTimeoutPolicy{
|
||||
Mode: sandbox.RemoteTimeoutExplicit,
|
||||
Value: 2 * time.Minute,
|
||||
|
|
@ -334,7 +340,7 @@ func (h *SystemHandler) runDeepSandboxCheck(
|
|||
result.add("sandbox_exec", true, "", latency)
|
||||
}
|
||||
|
||||
h.probeSandboxEgress(probeCtx, client, handle, result)
|
||||
h.probeSandboxEgress(probeCtx, client, handle, cfg.Network, result)
|
||||
}
|
||||
|
||||
// egressProbeTargets are tried in order; the first reachable one passes
|
||||
|
|
@ -355,6 +361,7 @@ func (h *SystemHandler) probeSandboxEgress(
|
|||
ctx context.Context,
|
||||
client sandbox.RemoteSandboxClient,
|
||||
handle sandbox.RemoteSandboxHandle,
|
||||
policy sandbox.RemoteNetworkPolicy,
|
||||
result *SandboxCheckResponse,
|
||||
) {
|
||||
// Echo which target succeeded so the UI message is actionable when
|
||||
|
|
@ -377,11 +384,11 @@ func (h *SystemHandler) probeSandboxEgress(
|
|||
latency := time.Since(start).Milliseconds()
|
||||
switch {
|
||||
case err != nil:
|
||||
result.add("egress_available", false, sandboxCheckReason(err), latency)
|
||||
reportEgressProbe(result, policy, false, sandboxCheckReason(err), latency)
|
||||
case execResult == nil:
|
||||
result.add("egress_available", false, "出网探测无返回", latency)
|
||||
reportEgressProbe(result, policy, false, "出网探测无返回", latency)
|
||||
case execResult.Killed:
|
||||
result.add("egress_available", false, "出网探测超时", latency)
|
||||
reportEgressProbe(result, policy, false, "出网探测超时", latency)
|
||||
case execResult.ExitCode != 0:
|
||||
msg := strings.TrimSpace(execResult.Stderr)
|
||||
if msg == "" {
|
||||
|
|
@ -390,16 +397,44 @@ func (h *SystemHandler) probeSandboxEgress(
|
|||
if msg == "" {
|
||||
msg = "国内与国际探测目标均不可达"
|
||||
}
|
||||
result.add("egress_available", false, msg, latency)
|
||||
reportEgressProbe(result, policy, false, msg, latency)
|
||||
default:
|
||||
hit := strings.TrimSpace(execResult.Stdout)
|
||||
if hit == "" {
|
||||
hit = "ok"
|
||||
}
|
||||
result.add("egress_available", true, "reachable via "+hit, latency)
|
||||
reportEgressProbe(result, policy, true, "reachable via "+hit, latency)
|
||||
}
|
||||
}
|
||||
|
||||
// reportEgressProbe records the outbound-connectivity probe. Under a
|
||||
// deny-by-default policy a blocked probe is the expected outcome — the probe
|
||||
// target is not on the admin's allow list — so it is reported as "restricted
|
||||
// by policy" instead of failing the whole check. Only a config that allows
|
||||
// public egress can fail this probe.
|
||||
func reportEgressProbe(
|
||||
result *SandboxCheckResponse,
|
||||
policy sandbox.RemoteNetworkPolicy,
|
||||
reachable bool,
|
||||
detail string,
|
||||
latencyMS int64,
|
||||
) {
|
||||
if reachable {
|
||||
result.add("egress_available", true, detail, latencyMS)
|
||||
return
|
||||
}
|
||||
if !policy.DeniesEgressByDefault() {
|
||||
result.add("egress_available", false, detail, latencyMS)
|
||||
return
|
||||
}
|
||||
result.Checks = append(result.Checks, SandboxCheckItem{
|
||||
Name: "egress_available",
|
||||
OK: nil,
|
||||
Reason: skipReasonEgressRestrictedByPolicy,
|
||||
LatencyMS: latencyMS,
|
||||
})
|
||||
}
|
||||
|
||||
// explainSandboxCreateFailure turns a failed sandbox creation into a cause the
|
||||
// operator can act on.
|
||||
//
|
||||
|
|
|
|||
|
|
@ -38,3 +38,100 @@ func TestRunStatelessSandboxCheckRemovedWithLocalBackend(t *testing.T) {
|
|||
|
||||
require.ErrorIs(t, err, sandbox.ErrUnsupportedSandboxType)
|
||||
}
|
||||
|
||||
// The probe has to run under the policy the admin configured, or
|
||||
// egress_available answers a question nobody asked: whether the provider's
|
||||
// default allows egress.
|
||||
func TestDeepSandboxCheckUsesConfiguredNetworkPolicy(t *testing.T) {
|
||||
incoming := &types.TenantSandboxConfig{
|
||||
SandboxType: "cube",
|
||||
Cube: &types.CubeSandboxConfig{
|
||||
APIURL: "https://203.0.113.20", ProxyURL: "https://203.0.113.20",
|
||||
SandboxDomain: "cube.app", TemplateID: "tpl-1",
|
||||
},
|
||||
Network: &types.SandboxNetworkPolicy{
|
||||
DenyEgressByDefault: true,
|
||||
AllowOut: []string{"api.example.com"},
|
||||
},
|
||||
}
|
||||
|
||||
effective, err := sandbox.ResolveEffectiveConfig(incoming, sandbox.DefaultConfig())
|
||||
require.NoError(t, err)
|
||||
|
||||
require.NotNil(t, effective.Network.AllowInternetAccess)
|
||||
require.False(t, *effective.Network.AllowInternetAccess)
|
||||
require.Equal(t, []string{"api.example.com"}, effective.Network.AllowOut)
|
||||
}
|
||||
|
||||
// Under a deny-by-default policy a blocked probe is the policy working, not a
|
||||
// misconfiguration, so it must not be reported as a failure.
|
||||
func TestDeepSandboxCheckReportsEgressRestrictedRatherThanFailed(t *testing.T) {
|
||||
result := &SandboxCheckResponse{OK: true, Provider: "cube"}
|
||||
denied := false
|
||||
|
||||
reportEgressProbe(result, sandbox.RemoteNetworkPolicy{
|
||||
AllowInternetAccess: &denied,
|
||||
AllowOut: []string{"api.example.com"},
|
||||
}, false, "curl: (28) timeout", 0)
|
||||
|
||||
require.True(t, result.OK, "a policy-blocked probe must not fail the check")
|
||||
item := result.Checks[len(result.Checks)-1]
|
||||
require.Equal(t, "egress_available", item.Name)
|
||||
require.Nil(t, item.OK)
|
||||
require.Equal(t, skipReasonEgressRestrictedByPolicy, item.Reason)
|
||||
require.Empty(t, item.Message, "skip reasons are localized by the UI")
|
||||
}
|
||||
|
||||
// ValidateSandboxNetworkPolicy accepts two equivalent spellings of the
|
||||
// deny-all fallback — "默认拒绝" and a 0.0.0.0/0 entry in deny_out — and the
|
||||
// drawer offers both. A config that used the second one is behaving exactly as
|
||||
// designed when the probe is blocked, so reporting a hard failure would cry
|
||||
// wolf over a correct configuration.
|
||||
func TestDeepSandboxCheckReportsEgressRestrictedForDenyOutSpelling(t *testing.T) {
|
||||
result := &SandboxCheckResponse{OK: true, Provider: "cube"}
|
||||
allowed := true
|
||||
|
||||
reportEgressProbe(result, sandbox.RemoteNetworkPolicy{
|
||||
AllowInternetAccess: &allowed,
|
||||
AllowOut: []string{"api.example.com"},
|
||||
DenyOut: []string{"0.0.0.0/0"},
|
||||
}, false, "curl: (28) timeout", 0)
|
||||
|
||||
require.True(t, result.OK, "a policy-blocked probe must not fail the check")
|
||||
item := result.Checks[len(result.Checks)-1]
|
||||
require.Equal(t, "egress_available", item.Name)
|
||||
require.Nil(t, item.OK)
|
||||
require.Equal(t, skipReasonEgressRestrictedByPolicy, item.Reason)
|
||||
require.Empty(t, item.Message, "skip reasons are localized by the UI")
|
||||
}
|
||||
|
||||
// A deny list that does not cover everything leaves the probe target reachable
|
||||
// by default, so a blocked probe there is a genuine failure.
|
||||
func TestDeepSandboxCheckStillFailsEgressWhenDenyListIsPartial(t *testing.T) {
|
||||
result := &SandboxCheckResponse{OK: true, Provider: "cube"}
|
||||
allowed := true
|
||||
|
||||
reportEgressProbe(result, sandbox.RemoteNetworkPolicy{
|
||||
AllowInternetAccess: &allowed,
|
||||
DenyOut: []string{"10.0.0.0/8"},
|
||||
}, false, "curl: (28) timeout", 0)
|
||||
|
||||
require.False(t, result.OK)
|
||||
item := result.Checks[len(result.Checks)-1]
|
||||
require.NotNil(t, item.OK)
|
||||
require.False(t, *item.OK)
|
||||
}
|
||||
|
||||
func TestDeepSandboxCheckStillFailsEgressWhenPolicyAllowsAll(t *testing.T) {
|
||||
result := &SandboxCheckResponse{OK: true, Provider: "cube"}
|
||||
allowed := true
|
||||
|
||||
reportEgressProbe(result, sandbox.RemoteNetworkPolicy{
|
||||
AllowInternetAccess: &allowed,
|
||||
}, false, "curl: (28) timeout", 120)
|
||||
|
||||
require.False(t, result.OK)
|
||||
item := result.Checks[len(result.Checks)-1]
|
||||
require.NotNil(t, item.OK)
|
||||
require.False(t, *item.OK)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -211,7 +211,7 @@ func TestIntegrationCubeClient_CreateConnectRoundTrip(t *testing.T) {
|
|||
|
||||
// Reconnect to the same sandbox — this is the critical path that
|
||||
// exercises CubeAPI's /sandboxes/{id}/connect endpoint.
|
||||
reattached, err := client.Connect(ctx, sandboxID)
|
||||
reattached, err := client.Connect(ctx, RemoteConnectRequest{SandboxID: sandboxID})
|
||||
if err != nil {
|
||||
t.Fatalf("Connect existing sandbox via real CubeAPI: %v", err)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -35,6 +35,8 @@ type cubeMockServer struct {
|
|||
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
|
||||
|
|
@ -130,32 +132,42 @@ func (m *cubeMockServer) handleCreate(w http.ResponseWriter, r *http.Request) {
|
|||
"startedAt": time.Now().UTC().Format(time.RFC3339),
|
||||
}
|
||||
m.files[id] = map[string][]byte{}
|
||||
trafficAccessToken := m.trafficAccessToken
|
||||
m.mu.Unlock()
|
||||
|
||||
writeJSON(w, http.StatusCreated, map[string]any{
|
||||
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
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
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) {
|
||||
|
|
|
|||
|
|
@ -115,6 +115,16 @@ func (h *cubeRemoteHandle) Metadata() map[string]string {
|
|||
return cloneMetadata(h.metadata)
|
||||
}
|
||||
|
||||
// TrafficAccessToken implements RemoteInboundTokenCarrier. Cube issues this
|
||||
// only at create time and never repeats it on connect or resume, so the
|
||||
// lifecycle has to persist it alongside the binding.
|
||||
func (h *cubeRemoteHandle) TrafficAccessToken() string {
|
||||
if h == nil || h.sb == nil {
|
||||
return ""
|
||||
}
|
||||
return h.sb.TrafficAccessToken
|
||||
}
|
||||
|
||||
// --- RemoteSandboxClient ------------------------------------------------------
|
||||
|
||||
func (c *CubeRemoteClient) Provider() RemoteProvider { return SandboxTypeCube }
|
||||
|
|
@ -458,33 +468,18 @@ func (c *CubeRemoteClient) Create(
|
|||
nil,
|
||||
)
|
||||
}
|
||||
// Cube honours two independent switches for outbound reachability and
|
||||
// both must be on for "curl https://example.com" to work from inside
|
||||
// the VM:
|
||||
//
|
||||
// * AllowInternetAccess (top-level, cluster egress switch): when
|
||||
// nil the SDK omits the field and the server falls back to the
|
||||
// template's default. Setting it explicitly makes the intent
|
||||
// obvious to anyone reading a captured payload and keeps
|
||||
// behaviour identical when the template default flips.
|
||||
// * Network.AllowPublicTraffic (per-sandbox routing switch): tells
|
||||
// CubeProxy to attach the public-egress interface to this MicroVM.
|
||||
// Without it the VM has no outbound route regardless of the
|
||||
// cluster-level allow.
|
||||
//
|
||||
// Callers can override either switch via cubeCreateRequest.Network.
|
||||
// The permissive (both on) defaults preserve the pre-refactor
|
||||
// behaviour for callers that leave the policy unset.
|
||||
//
|
||||
// See docs/guide/network-policy.md ("示例 7: 混合 L3 allow 和 L7 rules").
|
||||
network := request.Network
|
||||
if network.AllowInternetAccess == nil {
|
||||
defaultOn := true
|
||||
network.AllowInternetAccess = &defaultOn
|
||||
}
|
||||
// Deliberately the opposite of Cube's own default. Cube leaves the
|
||||
// sandbox URL reachable by anyone who knows the ID; WeKnora closes it and
|
||||
// relies on the per-sandbox traffic token, which the SDK attaches to
|
||||
// data-plane requests for us. Do not change this to true.
|
||||
if network.AllowPublicTraffic == nil {
|
||||
defaultOn := true
|
||||
network.AllowPublicTraffic = &defaultOn
|
||||
defaultClosed := false
|
||||
network.AllowPublicTraffic = &defaultClosed
|
||||
}
|
||||
opts := cubesandbox.CreateOptions{
|
||||
TemplateID: request.TemplateID,
|
||||
|
|
@ -496,14 +491,22 @@ func (c *CubeRemoteClient) Create(
|
|||
AllowPublicTraffic: network.AllowPublicTraffic,
|
||||
AllowOut: append([]string(nil), network.AllowOut...),
|
||||
DenyOut: append([]string(nil), network.DenyOut...),
|
||||
Rules: toCubeEgressRules(network.CubeRules),
|
||||
},
|
||||
}
|
||||
// The SDK omits allowInternetAccess for any non-false value, in which
|
||||
// case the server falls back to the template's default. Keep the
|
||||
// adapter's provider-positive default explicit on the wire.
|
||||
if *network.AllowInternetAccess {
|
||||
opts.Extra = map[string]any{"allowInternetAccess": true}
|
||||
}
|
||||
if action != "" {
|
||||
opts.Extra = map[string]any{
|
||||
"lifecycle": map[string]any{
|
||||
"onTimeout": string(action),
|
||||
"autoResume": autoResume,
|
||||
},
|
||||
if opts.Extra == nil {
|
||||
opts.Extra = make(map[string]any)
|
||||
}
|
||||
opts.Extra["lifecycle"] = map[string]any{
|
||||
"onTimeout": string(action),
|
||||
"autoResume": autoResume,
|
||||
}
|
||||
}
|
||||
sb, err := c.client.Create(ctx, opts)
|
||||
|
|
@ -522,9 +525,10 @@ func (c *CubeRemoteClient) Create(
|
|||
|
||||
func (c *CubeRemoteClient) Connect(
|
||||
ctx context.Context,
|
||||
sandboxID string,
|
||||
request RemoteConnectRequest,
|
||||
) (RemoteSandboxHandle, error) {
|
||||
if strings.TrimSpace(sandboxID) == "" {
|
||||
sandboxID := strings.TrimSpace(request.SandboxID)
|
||||
if sandboxID == "" {
|
||||
return nil, cubeInvalidRequest("Connect", "sandbox ID is required", nil)
|
||||
}
|
||||
sb, err := c.client.Connect(ctx, sandboxID)
|
||||
|
|
@ -537,6 +541,11 @@ func (c *CubeRemoteClient) Connect(
|
|||
"cube returned an empty sandbox handle", nil,
|
||||
)
|
||||
}
|
||||
// Cube does not repeat the traffic token on connect, so without this the
|
||||
// SDK would stop sending the header and every exec would 403.
|
||||
if sb.TrafficAccessToken == "" {
|
||||
sb.TrafficAccessToken = request.TrafficAccessToken
|
||||
}
|
||||
return &cubeRemoteHandle{sb: sb}, nil
|
||||
}
|
||||
|
||||
|
|
@ -1200,9 +1209,42 @@ func cubeCredentialPresence(value string) string {
|
|||
return "present"
|
||||
}
|
||||
|
||||
// toCubeEgressRules maps the neutral L7 rules onto the SDK's shape. Deny rules
|
||||
// are forwarded too: sending them is what makes the target reachable by
|
||||
// CubeEgress, which is the only component that can answer a request-level 403.
|
||||
func toCubeEgressRules(rules []RemoteCubeEgressRule) []cubesandbox.Rule {
|
||||
if len(rules) == 0 {
|
||||
return nil
|
||||
}
|
||||
out := make([]cubesandbox.Rule, 0, len(rules))
|
||||
for _, rule := range rules {
|
||||
converted := cubesandbox.Rule{
|
||||
Name: rule.Name,
|
||||
Match: cubesandbox.Match{
|
||||
SNI: rule.SNI,
|
||||
Host: rule.Host,
|
||||
Method: append([]string(nil), rule.Methods...),
|
||||
Path: rule.Path,
|
||||
Scheme: rule.Scheme,
|
||||
},
|
||||
Action: cubesandbox.Action{Allow: rule.Allow, Audit: rule.Audit},
|
||||
}
|
||||
for _, inject := range rule.Inject {
|
||||
converted.Action.Inject = append(converted.Action.Inject, cubesandbox.Inject{
|
||||
Header: inject.Header,
|
||||
Secret: inject.Secret,
|
||||
Format: inject.Format,
|
||||
})
|
||||
}
|
||||
out = append(out, converted)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
var (
|
||||
_ RemoteSandboxClient = (*CubeRemoteClient)(nil)
|
||||
_ RemoteSnapshotManager = (*CubeRemoteClient)(nil)
|
||||
_ RemoteTemplateCatalog = (*CubeRemoteClient)(nil)
|
||||
_ RemoteSandboxHandle = (*cubeRemoteHandle)(nil)
|
||||
_ RemoteSandboxClient = (*CubeRemoteClient)(nil)
|
||||
_ RemoteSnapshotManager = (*CubeRemoteClient)(nil)
|
||||
_ RemoteTemplateCatalog = (*CubeRemoteClient)(nil)
|
||||
_ RemoteSandboxHandle = (*cubeRemoteHandle)(nil)
|
||||
_ RemoteInboundTokenCarrier = (*cubeRemoteHandle)(nil)
|
||||
)
|
||||
|
|
|
|||
|
|
@ -9,6 +9,7 @@ import (
|
|||
|
||||
cubesandbox "github.com/tencentcloud/CubeSandbox/sdk/go"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
|
|
@ -160,20 +161,69 @@ func TestCubeRemoteClientCreateWritesLifecyclePayload(t *testing.T) {
|
|||
}, 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, err := NewCubeRemoteClient(testConfig(t, mock))
|
||||
require.NoError(t, err)
|
||||
client := newTestCubeRemoteClient(t, mock)
|
||||
deny := false
|
||||
privateSandbox := false
|
||||
|
||||
_, err = client.Create(context.Background(), RemoteCreateRequest{
|
||||
_, 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)
|
||||
|
|
@ -187,6 +237,109 @@ func TestCubeRemoteClientCreateForwardsNetworkPolicy(t *testing.T) {
|
|||
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"])
|
||||
}
|
||||
|
||||
// WeKnora'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 WeKnora 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) {
|
||||
|
|
@ -252,6 +405,7 @@ func TestCubeRemoteClientCreatePreservesTimeoutModes(t *testing.T) {
|
|||
|
||||
func TestCubeRemoteClientLifecycleRoundTrip(t *testing.T) {
|
||||
mock := newCubeMockServer(t)
|
||||
mock.trafficAccessToken = "create-only-traffic-token"
|
||||
client := newTestCubeRemoteClient(t, mock)
|
||||
ctx := context.Background()
|
||||
|
||||
|
|
@ -277,9 +431,11 @@ func TestCubeRemoteClientLifecycleRoundTrip(t *testing.T) {
|
|||
require.Len(t, list, 1)
|
||||
require.Equal(t, handle.ID(), list[0].ID)
|
||||
|
||||
reconnected, err := client.Connect(ctx, handle.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())
|
||||
|
|
|
|||
|
|
@ -306,7 +306,7 @@ func TestDockerBackendScriptExecutionRefreshesActivityMarkerIntegration(t *testi
|
|||
if err != nil || len(summaries) != 1 {
|
||||
t.Fatalf("expected exactly one container: %v %#v", err, summaries)
|
||||
}
|
||||
handle, err := client.Connect(ctx, summaries[0].ID)
|
||||
handle, err := client.Connect(ctx, RemoteConnectRequest{SandboxID: summaries[0].ID})
|
||||
if err != nil {
|
||||
t.Fatalf("Connect: %v", err)
|
||||
}
|
||||
|
|
@ -468,7 +468,7 @@ func TestDockerBackendArtifactBootstrapDoesNotFollowSymlinkIntegration(t *testin
|
|||
if err != nil || len(summaries) != 1 {
|
||||
t.Fatalf("expected exactly one container for the session: %v %#v", err, summaries)
|
||||
}
|
||||
handle, err := client.Connect(ctx, summaries[0].ID)
|
||||
handle, err := client.Connect(ctx, RemoteConnectRequest{SandboxID: summaries[0].ID})
|
||||
if err != nil {
|
||||
t.Fatalf("Connect: %v", err)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -360,7 +360,8 @@ var dockerInitProcess = true
|
|||
// RemoteNetworkPolicy cannot be honoured here; the one thing that maps
|
||||
// cleanly is "no egress at all", which AllowInternetAccess=false expresses.
|
||||
// Domain rules are silently not applied — the config surface refuses them
|
||||
// before they get this far (see RequireCompleteConfig).
|
||||
// before they get this far (see types.ValidateSandboxNetworkPolicy, which
|
||||
// rejects any allow/deny list or L7 rule on a docker config at save time).
|
||||
func (c *DockerRemoteClient) networkMode(policy RemoteNetworkPolicy) string {
|
||||
if policy.AllowInternetAccess != nil && !*policy.AllowInternetAccess {
|
||||
return "none"
|
||||
|
|
@ -377,8 +378,11 @@ func (c *DockerRemoteClient) networkMode(policy RemoteNetworkPolicy) string {
|
|||
// left off instead of losing everything it installed.
|
||||
func (c *DockerRemoteClient) Connect(
|
||||
ctx context.Context,
|
||||
sandboxID string,
|
||||
request RemoteConnectRequest,
|
||||
) (RemoteSandboxHandle, error) {
|
||||
// Docker containers are not fronted by a provider gateway, so there is no
|
||||
// inbound credential to restore; TrafficAccessToken is ignored.
|
||||
sandboxID := request.SandboxID
|
||||
inspected, err := c.api.ContainerInspect(ctx, sandboxID, client.ContainerInspectOptions{})
|
||||
if err != nil {
|
||||
return nil, dockerError("Connect", err)
|
||||
|
|
|
|||
|
|
@ -602,7 +602,7 @@ func TestDockerClientConnectRestartsStoppedContainer(t *testing.T) {
|
|||
}
|
||||
docker := newTestDockerClient(t, engine)
|
||||
|
||||
handle, err := docker.Connect(context.Background(), "container-1")
|
||||
handle, err := docker.Connect(context.Background(), RemoteConnectRequest{SandboxID: "container-1"})
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "container-1", handle.ID())
|
||||
require.Equal(t, []string{"container-1"}, engine.started)
|
||||
|
|
@ -618,7 +618,7 @@ func TestDockerClientConnectUnpausesPausedContainer(t *testing.T) {
|
|||
}
|
||||
docker := newTestDockerClient(t, engine)
|
||||
|
||||
_, err := docker.Connect(context.Background(), "container-1")
|
||||
_, err := docker.Connect(context.Background(), RemoteConnectRequest{SandboxID: "container-1"})
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, []string{"container-1"}, engine.unpaused)
|
||||
require.Empty(t, engine.started)
|
||||
|
|
@ -628,7 +628,7 @@ func TestDockerClientConnectUnpausesPausedContainer(t *testing.T) {
|
|||
// session instead of failing every execution forever.
|
||||
func TestDockerClientConnectMissingContainerIsReplaceable(t *testing.T) {
|
||||
docker := newTestDockerClient(t, newFakeDockerEngine())
|
||||
_, err := docker.Connect(context.Background(), "container-gone")
|
||||
_, err := docker.Connect(context.Background(), RemoteConnectRequest{SandboxID: "container-gone"})
|
||||
require.Error(t, err)
|
||||
require.True(t, CanReplaceRemoteBinding(err))
|
||||
}
|
||||
|
|
|
|||
|
|
@ -23,7 +23,8 @@ import (
|
|||
|
||||
// E2BRemoteClient implements RemoteSandboxClient on top of the go-e2b client.
|
||||
type E2BRemoteClient struct {
|
||||
client *e2b.Client
|
||||
client *e2b.Client
|
||||
inboundTokens *InboundTokenRegistry
|
||||
|
||||
templateID string
|
||||
timeout time.Duration
|
||||
|
|
@ -46,9 +47,9 @@ func NewE2BRemoteClientWithTransport(
|
|||
transport *http.Transport,
|
||||
) (*E2BRemoteClient, error) {
|
||||
if transport == nil {
|
||||
return newE2BRemoteClient(cfg, nil)
|
||||
return newE2BRemoteClient(cfg, nil, NewInboundTokenRegistry())
|
||||
}
|
||||
return newE2BRemoteClient(cfg, transport)
|
||||
return newE2BRemoteClient(cfg, transport, NewInboundTokenRegistry())
|
||||
}
|
||||
|
||||
// NewE2BRemoteClientWithPool builds the client on top of the shared gateway
|
||||
|
|
@ -61,14 +62,15 @@ func NewE2BRemoteClientWithPool(
|
|||
pool *SandboxGatewayTransportPool,
|
||||
) (*E2BRemoteClient, error) {
|
||||
if pool == nil {
|
||||
return newE2BRemoteClient(cfg, nil)
|
||||
return newE2BRemoteClient(cfg, nil, NewInboundTokenRegistry())
|
||||
}
|
||||
return newE2BRemoteClient(cfg, pool.RoundTripperFor(cfg))
|
||||
return newE2BRemoteClient(cfg, pool.RoundTripperFor(cfg), pool.InboundTokens())
|
||||
}
|
||||
|
||||
func newE2BRemoteClient(
|
||||
cfg *Config,
|
||||
transport http.RoundTripper,
|
||||
inboundTokens *InboundTokenRegistry,
|
||||
) (*E2BRemoteClient, error) {
|
||||
if cfg == nil {
|
||||
return nil, errors.New("e2b remote client config is required")
|
||||
|
|
@ -80,6 +82,12 @@ func newE2BRemoteClient(
|
|||
if timeout <= 0 {
|
||||
timeout = DefaultE2BHTTPTimeout
|
||||
}
|
||||
// Attach the inbound-token injector even when the caller did not go
|
||||
// through the gateway pool. go-e2b stores TrafficAccessToken but never
|
||||
// sends the header; without this wrap, NewE2BRemoteClient / WithTransport
|
||||
// would register tokens that no HTTP stack consults. A pool-built split
|
||||
// that already owns the same registry is left as-is.
|
||||
transport = attachInboundTokenTransport(transport, inboundTokens)
|
||||
// Every E2B client speaks to envd through the compatibility shim, whether
|
||||
// or not a gateway is configured: the two details it rewrites belong to the
|
||||
// envd protocol itself, not to any one deployment. See envd_compat_transport.go.
|
||||
|
|
@ -102,9 +110,10 @@ func newE2BRemoteClient(
|
|||
ttl = DefaultE2BSandboxTTL
|
||||
}
|
||||
return &E2BRemoteClient{
|
||||
client: client,
|
||||
templateID: strings.TrimSpace(cfg.E2BTemplate),
|
||||
timeout: ttl,
|
||||
client: client,
|
||||
inboundTokens: inboundTokens,
|
||||
templateID: strings.TrimSpace(cfg.E2BTemplate),
|
||||
timeout: ttl,
|
||||
}, nil
|
||||
}
|
||||
|
||||
|
|
@ -131,6 +140,16 @@ func (h *e2bRemoteHandle) Metadata() map[string]string {
|
|||
return cloneMetadata(h.metadata)
|
||||
}
|
||||
|
||||
// TrafficAccessToken implements RemoteInboundTokenCarrier. E2B issues it only
|
||||
// in the create response; go-e2b keeps the field but never sends the header,
|
||||
// so both persisting it and attaching it are WeKnora's job.
|
||||
func (h *e2bRemoteHandle) TrafficAccessToken() string {
|
||||
if h == nil || h.sandbox == nil {
|
||||
return ""
|
||||
}
|
||||
return h.sandbox.TrafficAccessToken
|
||||
}
|
||||
|
||||
// --- RemoteSandboxClient ------------------------------------------------------
|
||||
|
||||
func (c *E2BRemoteClient) Provider() RemoteProvider { return SandboxTypeE2B }
|
||||
|
|
@ -146,7 +165,9 @@ func (c *E2BRemoteClient) Capabilities() RemoteSandboxCapabilities {
|
|||
// E2B stores snapshots as templates, so a snapshot ID can be handed
|
||||
// straight back as CreateOptions.TemplateID.
|
||||
SupportsSnapshots: true,
|
||||
SupportsVolumes: true,
|
||||
// E2B has no named-volume mount API that WeKnora can use; advertising
|
||||
// it would let a workspace configure a mount that never appears.
|
||||
SupportsVolumes: false,
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -428,19 +449,20 @@ func (c *E2BRemoteClient) Create(
|
|||
)
|
||||
}
|
||||
|
||||
// Translate the neutral RemoteNetworkPolicy to E2B's SDK types. When
|
||||
// the caller supplied no policy at all we fall back to the same
|
||||
// permissive defaults the Cube adapter uses (public egress + public
|
||||
// URL reachability) so upgrading WeKnora deployments do not silently
|
||||
// lose `curl` / `pip` access from inside the sandbox.
|
||||
policy := request.Network
|
||||
if policy.AllowInternetAccess == nil {
|
||||
defaultOn := true
|
||||
policy.AllowInternetAccess = &defaultOn
|
||||
}
|
||||
// Deliberately the opposite of E2B's own default (which is public).
|
||||
// Closing inbound requires Secure=true, pinned below, and makes the
|
||||
// create response carry a traffic access token that the lifecycle
|
||||
// persists — go-e2b stores that token but never sends it, so
|
||||
// gatewaySplitTransport is what puts it on data-plane requests.
|
||||
// Do not change this to true.
|
||||
if policy.AllowPublicTraffic == nil {
|
||||
defaultOn := true
|
||||
policy.AllowPublicTraffic = &defaultOn
|
||||
defaultClosed := false
|
||||
policy.AllowPublicTraffic = &defaultClosed
|
||||
}
|
||||
config := e2b.SandboxConfig{
|
||||
Template: template,
|
||||
|
|
@ -453,6 +475,7 @@ func (c *E2BRemoteClient) Create(
|
|||
AllowPublicTraffic: policy.AllowPublicTraffic,
|
||||
AllowOut: append([]string(nil), policy.AllowOut...),
|
||||
DenyOut: append([]string(nil), policy.DenyOut...),
|
||||
Rules: toE2BRequestRules(policy.E2BHostRules),
|
||||
},
|
||||
AutoPause: action == RemoteOnTimeoutPause,
|
||||
VolumeMounts: toE2BVolumeMounts(request.VolumeMounts),
|
||||
|
|
@ -472,6 +495,9 @@ func (c *E2BRemoteClient) Create(
|
|||
"e2b returned an empty sandbox handle", nil,
|
||||
)
|
||||
}
|
||||
// go-e2b keeps this token but never sends it, so register it for the
|
||||
// data-plane transport to attach.
|
||||
c.inboundTokens.Put(sandbox.ID, sandbox.TrafficAccessToken)
|
||||
return &e2bRemoteHandle{
|
||||
sandbox: sandbox,
|
||||
metadata: cloneMetadata(request.Metadata),
|
||||
|
|
@ -480,9 +506,10 @@ func (c *E2BRemoteClient) Create(
|
|||
|
||||
func (c *E2BRemoteClient) Connect(
|
||||
ctx context.Context,
|
||||
sandboxID string,
|
||||
request RemoteConnectRequest,
|
||||
) (RemoteSandboxHandle, error) {
|
||||
if strings.TrimSpace(sandboxID) == "" {
|
||||
sandboxID := strings.TrimSpace(request.SandboxID)
|
||||
if sandboxID == "" {
|
||||
return nil, e2bInvalidRequest("Connect", "sandbox ID is required", nil)
|
||||
}
|
||||
timeoutSeconds, err := e2bTimeoutSeconds(
|
||||
|
|
@ -503,6 +530,10 @@ func (c *E2BRemoteClient) Connect(
|
|||
"e2b returned a mismatched sandbox handle", nil,
|
||||
)
|
||||
}
|
||||
if sandbox.TrafficAccessToken == "" {
|
||||
sandbox.TrafficAccessToken = request.TrafficAccessToken
|
||||
}
|
||||
c.inboundTokens.Put(sandbox.ID, sandbox.TrafficAccessToken)
|
||||
return &e2bRemoteHandle{sandbox: sandbox}, nil
|
||||
}
|
||||
|
||||
|
|
@ -717,6 +748,7 @@ func (c *E2BRemoteClient) Delete(ctx context.Context, sandboxID string) error {
|
|||
if err := sandbox.CloseWithContext(ctx); err != nil {
|
||||
return normalizeE2BError("Delete", err)
|
||||
}
|
||||
c.inboundTokens.Delete(sandboxID)
|
||||
return nil
|
||||
}
|
||||
|
||||
|
|
@ -1122,6 +1154,30 @@ func toE2BVolumeMounts(src []RemoteVolumeMount) []e2b.VolumeMount {
|
|||
return result
|
||||
}
|
||||
|
||||
// toE2BRequestRules maps the neutral host rules onto E2B's per-host transform
|
||||
// map. E2B has no notion of a deny verdict or an audit level here — a rule is
|
||||
// only ever a header injection — which is why the neutral type carries the
|
||||
// richer Cube shape separately instead of one merged rule type.
|
||||
func toE2BRequestRules(rules []RemoteE2BHostRule) map[string][]e2b.RequestRule {
|
||||
if len(rules) == 0 {
|
||||
return nil
|
||||
}
|
||||
out := make(map[string][]e2b.RequestRule, len(rules))
|
||||
for _, rule := range rules {
|
||||
if len(rule.Headers) == 0 {
|
||||
continue
|
||||
}
|
||||
headers := make(map[string]string, len(rule.Headers))
|
||||
for name, value := range rule.Headers {
|
||||
headers[name] = value
|
||||
}
|
||||
out[rule.Host] = append(out[rule.Host], e2b.RequestRule{
|
||||
Transform: e2b.RequestTransform{Headers: headers},
|
||||
})
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// isE2BExecTimeout reports whether a failed command Run should be treated as
|
||||
// a timeout kill (Killed=true) rather than a transport error. It recognises:
|
||||
// - our own execCtx deadline (request.Timeout);
|
||||
|
|
@ -1273,8 +1329,9 @@ func e2bRemoteEntryType(fileType string) RemoteDirEntryType {
|
|||
}
|
||||
|
||||
var (
|
||||
_ RemoteSandboxClient = (*E2BRemoteClient)(nil)
|
||||
_ RemoteSnapshotManager = (*E2BRemoteClient)(nil)
|
||||
_ RemoteTemplateCatalog = (*E2BRemoteClient)(nil)
|
||||
_ RemoteSandboxHandle = (*e2bRemoteHandle)(nil)
|
||||
_ RemoteSandboxClient = (*E2BRemoteClient)(nil)
|
||||
_ RemoteSnapshotManager = (*E2BRemoteClient)(nil)
|
||||
_ RemoteTemplateCatalog = (*E2BRemoteClient)(nil)
|
||||
_ RemoteSandboxHandle = (*e2bRemoteHandle)(nil)
|
||||
_ RemoteInboundTokenCarrier = (*e2bRemoteHandle)(nil)
|
||||
)
|
||||
|
|
|
|||
|
|
@ -19,6 +19,7 @@ import (
|
|||
"time"
|
||||
|
||||
"connectrpc.com/connect"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
e2b "github.com/matiasinsaurralde/go-e2b"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
|
@ -62,6 +63,7 @@ type e2bMockServer struct {
|
|||
snapshotCreateBody map[string]any
|
||||
sandboxes map[string]map[string]any // sandboxID -> SandboxInfo JSON
|
||||
snapshots map[string]map[string]any // snapshotID -> SnapshotInfo JSON
|
||||
trafficAccessToken string
|
||||
}
|
||||
|
||||
func newE2BMockServer(t *testing.T) *e2bMockServer {
|
||||
|
|
@ -92,12 +94,19 @@ func (m *e2bMockServer) handle(w http.ResponseWriter, r *http.Request) {
|
|||
"startedAt": time.Now().UTC().Format(time.RFC3339),
|
||||
"metadata": m.createBody["metadata"],
|
||||
}
|
||||
m.mu.Lock()
|
||||
trafficAccessToken := m.trafficAccessToken
|
||||
m.mu.Unlock()
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusCreated)
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{
|
||||
response := map[string]any{
|
||||
"sandboxID": id,
|
||||
"envdAccessToken": "token-" + id,
|
||||
})
|
||||
}
|
||||
if trafficAccessToken != "" {
|
||||
response["trafficAccessToken"] = trafficAccessToken
|
||||
}
|
||||
_ = json.NewEncoder(w).Encode(response)
|
||||
|
||||
case r.URL.Path == "/sandboxes" && r.Method == http.MethodGet:
|
||||
m.listCount.Add(1)
|
||||
|
|
@ -363,7 +372,7 @@ func TestE2BRemoteClientProviderAndCapabilities(t *testing.T) {
|
|||
SupportsTimeoutRefresh: true,
|
||||
SupportsFilesystemEnumeration: true,
|
||||
SupportsSnapshots: true,
|
||||
SupportsVolumes: true,
|
||||
SupportsVolumes: false,
|
||||
}, client.Capabilities())
|
||||
}
|
||||
|
||||
|
|
@ -790,15 +799,14 @@ func TestE2BRemoteClientCreateWritesMetadataAndPauseLifecycle(t *testing.T) {
|
|||
require.Equal(t, true, mock.createBody["autoPause"])
|
||||
require.Equal(t, true, mock.createBody["autoPauseMemory"])
|
||||
require.Equal(t, map[string]any{"enabled": true}, mock.createBody["autoResume"])
|
||||
// Network defaults match the Cube adapter: public traffic on, internet
|
||||
// egress on, and Secure=true so the response carries an envd access
|
||||
// token. Regressing these keeps `pip install` broken silently, so we
|
||||
// pin the wire payload here.
|
||||
// Network defaults: egress on so `pip install` keeps working, inbound
|
||||
// CLOSED so the sandbox URL is not reachable by anyone holding the ID.
|
||||
// The inbound half is intentionally the opposite of E2B's own default.
|
||||
require.Equal(t, true, mock.createBody["secure"])
|
||||
require.Equal(t, true, mock.createBody["allow_internet_access"])
|
||||
networkPayload, ok := mock.createBody["network"].(map[string]any)
|
||||
require.True(t, ok, "network payload missing: %#v", mock.createBody["network"])
|
||||
require.Equal(t, true, networkPayload["allowPublicTraffic"])
|
||||
require.Equal(t, false, networkPayload["allowPublicTraffic"])
|
||||
|
||||
}
|
||||
|
||||
|
|
@ -850,21 +858,112 @@ func TestE2BRemoteClientCreateForwardsNetworkPolicy(t *testing.T) {
|
|||
AllowPublicTraffic: &privateSandbox,
|
||||
AllowOut: []string{"*.example.com"},
|
||||
DenyOut: []string{"0.0.0.0/0"},
|
||||
E2BHostRules: []RemoteE2BHostRule{{
|
||||
Host: "api.example.com",
|
||||
Headers: map[string]string{"X-Environment": "production"},
|
||||
}},
|
||||
},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
// Top-level allow_internet_access flips off as the caller requested,
|
||||
// AllowPublicTraffic hides the sandbox behind a traffic access token,
|
||||
// and the L3/L4 allow/deny lists both reach the server. Regressing any
|
||||
// of these silently opens (or closes) the sandbox's network policy in
|
||||
// a way callers cannot observe from unit tests, so pin the wire.
|
||||
require.Equal(t, false, mock.createBody["allow_internet_access"])
|
||||
networkPayload, ok := mock.createBody["network"].(map[string]any)
|
||||
require.True(t, ok)
|
||||
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"].(map[string]any)
|
||||
require.True(t, ok, "rules payload missing: %#v", networkPayload["rules"])
|
||||
hostRules := rules["api.example.com"].([]any)
|
||||
require.Len(t, hostRules, 1)
|
||||
transform := hostRules[0].(map[string]any)["transform"].(map[string]any)
|
||||
headers := transform["headers"].(map[string]any)
|
||||
require.Equal(t, "production", headers["X-Environment"])
|
||||
}
|
||||
|
||||
// Regression: a stored "deny by default + domain allowlist" policy used to
|
||||
// reach E2B as allow_internet_access=false with an empty denyOut, and the
|
||||
// provider answered
|
||||
//
|
||||
// 400 When specifying allowed domains in allow out, you must include
|
||||
// 'ALL_TRAFFIC' in deny out to block all other traffic.
|
||||
//
|
||||
// so every session on that config failed at create time. The existing wire
|
||||
// test could not catch it because it hand-built the resolved policy with the
|
||||
// sentinel already in place; this one starts from the stored shape and goes
|
||||
// through the real resolver.
|
||||
func TestE2BRemoteClientCreateSendsDenyAllForStoredDenyByDefault(t *testing.T) {
|
||||
tenantCfg := &types.TenantSandboxConfig{
|
||||
SandboxType: "e2b",
|
||||
E2B: &types.E2BSandboxConfig{
|
||||
APIKey: "key-test",
|
||||
TemplateID: "template-a",
|
||||
},
|
||||
Network: &types.SandboxNetworkPolicy{
|
||||
DenyEgressByDefault: true,
|
||||
AllowOut: []string{"*.example.com"},
|
||||
},
|
||||
}
|
||||
effective, err := ResolveEffectiveConfig(tenantCfg, DefaultConfig())
|
||||
require.NoError(t, err)
|
||||
|
||||
mock := newE2BMockServer(t)
|
||||
client := newTestE2BRemoteClient(t, mock)
|
||||
|
||||
_, err = client.Create(context.Background(), RemoteCreateRequest{
|
||||
TemplateID: "template-a",
|
||||
Network: effective.Network,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
require.Equal(t, false, mock.createBody["allow_internet_access"])
|
||||
networkPayload := mock.createBody["network"].(map[string]any)
|
||||
require.Equal(t, []any{"*.example.com"}, networkPayload["allowOut"])
|
||||
require.Equal(t, []any{"0.0.0.0/0"}, networkPayload["denyOut"],
|
||||
"E2B refuses a domain allowlist without an explicit deny-all")
|
||||
}
|
||||
|
||||
func TestE2BRemoteClientCreateOmitsRulesWhenNoneConfigured(t *testing.T) {
|
||||
mock := newE2BMockServer(t)
|
||||
client := newTestE2BRemoteClient(t, mock)
|
||||
|
||||
_, err := client.Create(context.Background(), RemoteCreateRequest{TemplateID: "template-a"})
|
||||
require.NoError(t, err)
|
||||
|
||||
networkPayload := mock.createBody["network"].(map[string]any)
|
||||
require.NotContains(t, networkPayload, "rules")
|
||||
}
|
||||
|
||||
// Same deliberate inversion as the Cube adapter: unspecified means inbound
|
||||
// closed. E2B additionally requires Secure=true for this, which the adapter
|
||||
// already pins.
|
||||
func TestE2BRemoteClientCreateDefaultsInboundClosed(t *testing.T) {
|
||||
mock := newE2BMockServer(t)
|
||||
client := newTestE2BRemoteClient(t, mock)
|
||||
|
||||
_, err := client.Create(context.Background(), RemoteCreateRequest{TemplateID: "template-a"})
|
||||
require.NoError(t, err)
|
||||
|
||||
require.Equal(t, true, mock.createBody["secure"])
|
||||
require.Equal(t, true, mock.createBody["allow_internet_access"])
|
||||
networkPayload := mock.createBody["network"].(map[string]any)
|
||||
require.Equal(t, false, networkPayload["allowPublicTraffic"])
|
||||
}
|
||||
|
||||
func TestE2BRemoteHandleExposesTrafficAccessToken(t *testing.T) {
|
||||
mock := newE2BMockServer(t)
|
||||
mock.mu.Lock()
|
||||
mock.trafficAccessToken = "traffic-token"
|
||||
mock.mu.Unlock()
|
||||
client := newTestE2BRemoteClient(t, mock)
|
||||
|
||||
handle, err := client.Create(context.Background(), RemoteCreateRequest{TemplateID: "template-a"})
|
||||
require.NoError(t, err)
|
||||
|
||||
carrier, ok := handle.(RemoteInboundTokenCarrier)
|
||||
require.True(t, ok, "e2b handle must expose the inbound token for the binding")
|
||||
require.Equal(t, "traffic-token", carrier.TrafficAccessToken())
|
||||
}
|
||||
|
||||
func TestE2BRemoteClientCreatePreservesTimeoutModes(t *testing.T) {
|
||||
|
|
@ -989,7 +1088,7 @@ func TestE2BRemoteClientConnectAcrossClients(t *testing.T) {
|
|||
mock.sandboxes[handle.ID()]["state"] = "paused"
|
||||
|
||||
second := newTestE2BRemoteClient(t, mock)
|
||||
reconnected, err := second.Connect(context.Background(), handle.ID())
|
||||
reconnected, err := second.Connect(context.Background(), RemoteConnectRequest{SandboxID: handle.ID()})
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, handle.ID(), reconnected.ID())
|
||||
require.Nil(t, reconnected.Metadata())
|
||||
|
|
|
|||
|
|
@ -30,6 +30,7 @@ import (
|
|||
"context"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
|
|
@ -40,8 +41,9 @@ import (
|
|||
// clients. One instance lives for the process; clients built from it come and
|
||||
// go.
|
||||
type SandboxGatewayTransportPool struct {
|
||||
control http.RoundTripper
|
||||
policy OutboundURLPolicy
|
||||
control http.RoundTripper
|
||||
policy OutboundURLPolicy
|
||||
inboundTokens *InboundTokenRegistry
|
||||
|
||||
// data maps a gateway "host:port" to the transport that dials it.
|
||||
data sync.Map
|
||||
|
|
@ -60,17 +62,28 @@ func NewSandboxGatewayTransportPoolWithPolicy(
|
|||
if control == nil {
|
||||
control = NewGuardedTransportWithPolicy(policy)
|
||||
}
|
||||
return &SandboxGatewayTransportPool{control: control, policy: 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, sandboxDomain := gatewayEndpointFor(cfg)
|
||||
gatewayURL, controlURL := gatewayEndpointFor(cfg)
|
||||
split := &gatewaySplitTransport{
|
||||
control: p.control,
|
||||
sandboxDomain: strings.ToLower(strings.TrimSpace(sandboxDomain)),
|
||||
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)))
|
||||
|
|
@ -79,21 +92,59 @@ func (p *SandboxGatewayTransportPool) RoundTripperFor(cfg *Config) http.RoundTri
|
|||
return split
|
||||
}
|
||||
|
||||
// gatewayEndpointFor reads the active provider's data-plane fields. 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, sandboxDomain string) {
|
||||
// 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.E2BSandboxDomain
|
||||
return cfg.E2BProxyURL, cfg.E2BAPIURL
|
||||
default:
|
||||
return cfg.CubeProxyURL, cfg.CubeSandboxDomain
|
||||
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 {
|
||||
|
|
@ -132,9 +183,14 @@ func newGatewayDataTransportWithPolicy(target string, policy OutboundURLPolicy)
|
|||
// 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
|
||||
sandboxDomain string
|
||||
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.
|
||||
|
|
@ -142,12 +198,38 @@ type gatewaySplitTransport struct {
|
|||
}
|
||||
|
||||
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 {
|
||||
|
|
@ -162,15 +244,26 @@ func (t *gatewaySplitTransport) applyGatewayScheme(req *http.Request) *http.Requ
|
|||
}
|
||||
|
||||
// isDataPlane reports whether host addresses a sandbox rather than the control
|
||||
// plane. Anything else - including an unset sandbox domain - stays on the
|
||||
// control transport, so a misconfiguration cannot silently redirect API calls
|
||||
// at the gateway.
|
||||
// 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 {
|
||||
if t.sandboxDomain == "" {
|
||||
host = strings.ToLower(strings.TrimSpace(host))
|
||||
if host == "" || (t.controlHost != "" && host == t.controlHost) {
|
||||
return false
|
||||
}
|
||||
host = strings.ToLower(host)
|
||||
return host == t.sandboxDomain || strings.HasSuffix(host, "."+t.sandboxDomain)
|
||||
return sandboxIDFromDataPlaneHost(host) != ""
|
||||
}
|
||||
|
||||
// CloseIdleConnections keeps the SDK's post-rollback reset meaningful. Only
|
||||
|
|
|
|||
|
|
@ -146,16 +146,93 @@ func TestSandboxGatewayTransportPoolRoutesE2BDataPlane(t *testing.T) {
|
|||
require.NotNil(t, split.data)
|
||||
require.Equal(t, "http", split.dataScheme)
|
||||
require.True(t, split.isDataPlane("49983-sbx.localhost"))
|
||||
require.False(t, split.isDataPlane("49983-sbx.cube.app"))
|
||||
|
||||
// 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,
|
||||
sandboxDomain: "localhost",
|
||||
dataScheme: "http",
|
||||
control: &recordingRoundTripper{},
|
||||
data: recorder,
|
||||
dataScheme: "http",
|
||||
}
|
||||
|
||||
request := httptest.NewRequest(http.MethodGet, "https://49983-sbx.localhost/files", nil)
|
||||
|
|
@ -170,14 +247,20 @@ func TestGatewaySplitTransportAppliesGatewayScheme(t *testing.T) {
|
|||
|
||||
func TestGatewaySplitTransportClassifiesAuthorities(t *testing.T) {
|
||||
split := &gatewaySplitTransport{
|
||||
control: NewGuardedTransport(),
|
||||
data: NewGuardedTransport(),
|
||||
sandboxDomain: "cube.app",
|
||||
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"))
|
||||
// A lookalike suffix must not be mistaken for the sandbox domain.
|
||||
// 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.
|
||||
//
|
||||
// A sandbox created with public inbound access closed only accepts requests
|
||||
// carrying its 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.
|
||||
//
|
||||
// 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 means the sandbox has
|
||||
// public inbound access, so nothing is stored.
|
||||
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 sandboxes WeKnora
|
||||
// created with inbound closed 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
|
||||
}
|
||||
|
|
@ -59,12 +59,12 @@ func (c *langfuseRemoteClient) Create(
|
|||
}
|
||||
|
||||
func (c *langfuseRemoteClient) Connect(
|
||||
ctx context.Context, sandboxID string,
|
||||
ctx context.Context, req RemoteConnectRequest,
|
||||
) (RemoteSandboxHandle, error) {
|
||||
ctx, span := startSandboxSpan(ctx, "sandbox.connect", map[string]interface{}{
|
||||
"sandbox_id": sandboxID,
|
||||
"sandbox_id": req.SandboxID,
|
||||
}, nil)
|
||||
handle, err := c.inner.Connect(ctx, sandboxID)
|
||||
handle, err := c.inner.Connect(ctx, req)
|
||||
span.Finish(sandboxHandleOut(handle), nil, err)
|
||||
return handle, err
|
||||
}
|
||||
|
|
|
|||
|
|
@ -15,6 +15,8 @@ package sandbox
|
|||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
)
|
||||
|
||||
// RemoteProvider identifies a remote sandbox backend. Values match the
|
||||
|
|
@ -38,6 +40,15 @@ type RemoteSandboxHandle interface {
|
|||
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
|
||||
}
|
||||
|
||||
// RemoteTimeoutMode describes how the remote provider should treat the
|
||||
// requested idle timeout.
|
||||
type RemoteTimeoutMode string
|
||||
|
|
@ -119,41 +130,103 @@ type RemoteCreateRequest struct {
|
|||
}
|
||||
|
||||
// RemoteNetworkPolicy is the provider-neutral outbound-network policy for a
|
||||
// new sandbox. Only the fields both Cube and E2B accept live here; provider-
|
||||
// specific extensions (E2B request rules, Cube L7 policy, egress proxies,
|
||||
// masked host names) stay inside the adapters until we have a second caller
|
||||
// that needs them expressed at this layer.
|
||||
// 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. When nil the adapter
|
||||
// leaves it unset so the provider server-side default (typically true)
|
||||
// applies. When *false the sandbox has no default egress; specific
|
||||
// hosts must appear in AllowOut.
|
||||
// - 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. nil defers to the provider default; false hides the
|
||||
// sandbox behind a per-sandbox traffic access token.
|
||||
// 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.
|
||||
// - 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 (DenyOut: ["0.0.0.0/0"]) — the adapters surface the
|
||||
// provider-native error unchanged so callers can react.
|
||||
// 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
|
||||
}
|
||||
|
||||
// IsZero reports whether the policy carries no caller-specified fields, in
|
||||
// which case adapters apply their own permissive defaults for backwards
|
||||
// compatibility with WeKnora deployments that predate provider-neutral
|
||||
// network policy.
|
||||
func (p RemoteNetworkPolicy) IsZero() bool {
|
||||
return p.AllowInternetAccess == nil &&
|
||||
p.AllowPublicTraffic == nil &&
|
||||
len(p.AllowOut) == 0 &&
|
||||
len(p.DenyOut) == 0
|
||||
// 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 sandbox was
|
||||
// created with public inbound access closed. It is an optional capability in
|
||||
// the same spirit as RemoteSnapshotManager: Docker has no such credential.
|
||||
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.
|
||||
|
|
@ -374,10 +447,10 @@ type RemoteSandboxClient interface {
|
|||
// 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 by ID. Adapters that
|
||||
// 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, sandboxID string) (RemoteSandboxHandle, error)
|
||||
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.
|
||||
|
|
|
|||
|
|
@ -29,7 +29,7 @@ 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, string) (RemoteSandboxHandle, error) {
|
||||
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) {
|
||||
|
|
|
|||
|
|
@ -4,13 +4,17 @@ import (
|
|||
"context"
|
||||
"fmt"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
type fakeRemoteHandle struct {
|
||||
id string
|
||||
provider RemoteProvider
|
||||
metadata map[string]string
|
||||
id string
|
||||
provider RemoteProvider
|
||||
metadata map[string]string
|
||||
trafficAccessToken string
|
||||
}
|
||||
|
||||
func (h *fakeRemoteHandle) ID() string { return h.id }
|
||||
|
|
@ -18,6 +22,23 @@ 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
|
||||
|
|
@ -42,10 +63,26 @@ type fakeRemoteClient struct {
|
|||
|
||||
createCount int
|
||||
connectIDs []string
|
||||
connects []RemoteConnectRequest
|
||||
getIDs []string
|
||||
deleteIDs []string
|
||||
listCount int
|
||||
|
||||
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
|
||||
|
|
@ -66,7 +103,7 @@ type fakeRemoteClient struct {
|
|||
}
|
||||
|
||||
func newFakeRemoteClient(provider RemoteProvider) *fakeRemoteClient {
|
||||
return &fakeRemoteClient{
|
||||
client := &fakeRemoteClient{
|
||||
provider: provider,
|
||||
capabilities: RemoteSandboxCapabilities{
|
||||
SupportsReconnect: true,
|
||||
|
|
@ -79,6 +116,36 @@ func newFakeRemoteClient(provider RemoteProvider) *fakeRemoteClient {
|
|||
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 }
|
||||
|
|
@ -123,7 +190,7 @@ func (c *fakeRemoteClient) Create(
|
|||
startedAt: time.Now().UTC(),
|
||||
}
|
||||
c.sandboxes[id] = record
|
||||
handle := c.handle(record)
|
||||
handle := c.handle(record, c.trafficAccessToken)
|
||||
afterCreate := c.afterCreate
|
||||
c.mu.Unlock()
|
||||
if afterCreate != nil {
|
||||
|
|
@ -134,14 +201,16 @@ func (c *fakeRemoteClient) Create(
|
|||
|
||||
func (c *fakeRemoteClient) Connect(
|
||||
ctx context.Context,
|
||||
sandboxID string,
|
||||
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
|
||||
}
|
||||
|
|
@ -155,7 +224,13 @@ func (c *fakeRemoteClient) Connect(
|
|||
nil,
|
||||
)
|
||||
}
|
||||
return c.handle(record), 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(
|
||||
|
|
@ -383,11 +458,22 @@ func (c *fakeRemoteClient) hasSandbox(id string) bool {
|
|||
return ok
|
||||
}
|
||||
|
||||
func (c *fakeRemoteClient) handle(record *fakeRemoteRecord) RemoteSandboxHandle {
|
||||
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),
|
||||
id: record.id,
|
||||
provider: c.provider,
|
||||
metadata: cloneStringMap(record.metadata),
|
||||
trafficAccessToken: trafficAccessToken,
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -283,6 +283,12 @@ type Config struct {
|
|||
// 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
|
||||
|
|
@ -358,6 +364,7 @@ func DefaultConfig() *Config {
|
|||
MaxCPU: DefaultCPULimit,
|
||||
CubeSandboxTTL: DefaultCubeSandboxTTL,
|
||||
CubeHTTPTimeout: DefaultCubeHTTPTimeout,
|
||||
Network: resolveNetworkPolicy(nil),
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -59,6 +59,21 @@ type SessionSandboxBinding struct {
|
|||
// 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 when the config closed public inbound access.
|
||||
//
|
||||
// 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 WeKnora 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 sandboxes created with public inbound allowed, and for
|
||||
// bindings written before this field existed; both are valid.
|
||||
TrafficAccessToken string `json:"traffic_access_token,omitempty"`
|
||||
}
|
||||
|
||||
// Validate checks a binding against the current schema and authoritative key.
|
||||
|
|
@ -103,6 +118,15 @@ type SessionSandboxBindingStore interface {
|
|||
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.
|
||||
|
|
@ -349,6 +373,40 @@ func (s *MemorySessionSandboxBindingStore) DeleteIfMatch(
|
|||
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()
|
||||
binding, exists := s.bindings[key]
|
||||
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[key] = binding
|
||||
return true, nil
|
||||
}
|
||||
|
||||
// InvalidateByConfig marks this process's bindings of one config stale.
|
||||
func (s *MemorySessionSandboxBindingStore) InvalidateByConfig(
|
||||
ctx context.Context,
|
||||
|
|
|
|||
|
|
@ -42,6 +42,34 @@ 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.
|
||||
|
|
@ -176,6 +204,34 @@ func (s *RedisSessionSandboxBindingStore) DeleteIfMatch(
|
|||
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 WeKnora processes sharing Redis.
|
||||
func (s *RedisSessionSandboxBindingStore) WithLifecycleLock(
|
||||
|
|
|
|||
|
|
@ -45,6 +45,11 @@ func TestRedisSessionSandboxBindingStoreContract(t *testing.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)
|
||||
|
|
|
|||
|
|
@ -2,7 +2,9 @@ package sandbox
|
|||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"strconv"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
|
@ -56,6 +58,51 @@ func testSessionSandboxBindingStore(t *testing.T, store SessionSandboxBindingSto
|
|||
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()
|
||||
|
||||
|
|
@ -320,6 +367,52 @@ func TestSessionSandboxBindingValidation(t *testing.T) {
|
|||
}
|
||||
}
|
||||
|
||||
// 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()
|
||||
|
||||
|
|
|
|||
|
|
@ -198,7 +198,7 @@ func (l *remoteSessionLifecycle) resolveLocked(
|
|||
l.consumeTurnRebuild(ctx, key)
|
||||
|
||||
if binding != nil {
|
||||
handle, replace, err := l.connectBinding(ctx, *binding)
|
||||
handle, replace, err := l.connectBinding(ctx, key, *binding)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
|
@ -231,6 +231,7 @@ func (l *remoteSessionLifecycle) resolveLocked(
|
|||
|
||||
func (l *remoteSessionLifecycle) connectBinding(
|
||||
ctx context.Context,
|
||||
key SessionSandboxKey,
|
||||
binding SessionSandboxBinding,
|
||||
) (RemoteSandboxHandle, bool, error) {
|
||||
summary, err := l.client.Get(ctx, binding.SandboxID)
|
||||
|
|
@ -254,7 +255,10 @@ func (l *remoteSessionLifecycle) connectBinding(
|
|||
return nil, true, nil
|
||||
}
|
||||
|
||||
handle, err := l.client.Connect(ctx, binding.SandboxID)
|
||||
handle, err := l.client.Connect(ctx, RemoteConnectRequest{
|
||||
SandboxID: binding.SandboxID,
|
||||
TrafficAccessToken: binding.TrafficAccessToken,
|
||||
})
|
||||
if err != nil {
|
||||
if CanReplaceRemoteBinding(err) {
|
||||
return nil, true, nil
|
||||
|
|
@ -264,9 +268,54 @@ func (l *remoteSessionLifecycle) connectBinding(
|
|||
if err := l.validateHandle(handle, binding.SandboxID); err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
persistInboundToken(ctx, l.bindings, key, binding, handle)
|
||||
return handle, false, nil
|
||||
}
|
||||
|
||||
// persistInboundToken writes a provider-reissued traffic token back onto the
|
||||
// binding. Connect may return a fresher credential than Redis has (pause then
|
||||
// resume); without this a later restart restores the stale copy, data-plane
|
||||
// calls 403, and CanReplaceRemoteBinding will not swap the binding.
|
||||
func persistInboundToken(
|
||||
ctx context.Context,
|
||||
store SessionSandboxBindingStore,
|
||||
key SessionSandboxKey,
|
||||
binding SessionSandboxBinding,
|
||||
handle RemoteSandboxHandle,
|
||||
) {
|
||||
if store == nil {
|
||||
return
|
||||
}
|
||||
token := InboundTokenOf(handle)
|
||||
if token == "" || token == binding.TrafficAccessToken {
|
||||
return
|
||||
}
|
||||
if _, err := store.ReplaceTrafficTokenIfMatch(ctx, key, binding, token); err != nil {
|
||||
log.Printf(
|
||||
"[sandbox] persist inbound token of session %s failed: %v",
|
||||
key.SessionID, err,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// 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.
|
||||
func (l *remoteSessionLifecycle) inboundTokenRequired() bool {
|
||||
allowPublic := l.createRequest.Network.AllowPublicTraffic
|
||||
return allowPublic != nil && !*allowPublic
|
||||
}
|
||||
|
||||
// missingRequiredInboundToken reports a handle that would 403 on every
|
||||
// data-plane call: the provider issues a traffic token, this config requires
|
||||
// it, and the handle does not have one. Docker is excluded because its handle
|
||||
// does not implement RemoteInboundTokenCarrier.
|
||||
func (l *remoteSessionLifecycle) missingRequiredInboundToken(handle RemoteSandboxHandle) bool {
|
||||
_, carriesInboundToken := handle.(RemoteInboundTokenCarrier)
|
||||
return carriesInboundToken && l.inboundTokenRequired() && InboundTokenOf(handle) == ""
|
||||
}
|
||||
|
||||
func (l *remoteSessionLifecycle) recoverOwnedSandbox(
|
||||
ctx context.Context,
|
||||
key SessionSandboxKey,
|
||||
|
|
@ -305,7 +354,7 @@ func (l *remoteSessionLifecycle) recoverOwnedSandbox(
|
|||
summary.ID,
|
||||
)
|
||||
}
|
||||
handle, err := l.client.Connect(ctx, summary.ID)
|
||||
handle, err := l.client.Connect(ctx, RemoteConnectRequest{SandboxID: summary.ID})
|
||||
if err != nil {
|
||||
if CanReplaceRemoteBinding(err) {
|
||||
continue
|
||||
|
|
@ -315,6 +364,42 @@ func (l *remoteSessionLifecycle) recoverOwnedSandbox(
|
|||
if err := l.validateHandle(handle, summary.ID); err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
// A sandbox recovered by metadata has no binding to supply its inbound
|
||||
// token, and both token-carrying providers issue that token only at
|
||||
// create time. Adopting one under a closed-inbound policy would wedge
|
||||
// the session: every data-plane call answers 403, which httpErrorKind
|
||||
// classifies as authentication rather than NotFound, so
|
||||
// CanReplaceRemoteBinding never lets the binding be replaced.
|
||||
//
|
||||
// The test is whether the provider HAS the concept, not whether the
|
||||
// token is empty. Docker's handle omits RemoteInboundTokenCarrier
|
||||
// because it has no inbound credential and no provider gateway, so an
|
||||
// empty token there means "not applicable" rather than "lost" — and
|
||||
// destroying a healthy container over it would cost /workspace on
|
||||
// every binding loss.
|
||||
if l.missingRequiredInboundToken(handle) {
|
||||
// Deleting rather than walking away is safe for the same reason
|
||||
// cleanupOwnedDuplicates below is: this loop holds the lifecycle
|
||||
// lock for key, and l.metadata(key) scopes every candidate to this
|
||||
// session. It is also necessary, because nothing in-tree reclaims
|
||||
// orphans (ReapOrphanSandboxes has no production caller) and
|
||||
// Connect above has already resumed this sandbox and refreshed its
|
||||
// TTL, so leaving it would strand a billable sandbox per restart.
|
||||
log.Printf(
|
||||
"[sandbox] deleting remote sandbox %s of session %s: "+
|
||||
"adopted by metadata without the inbound traffic token "+
|
||||
"this config's network policy requires",
|
||||
summary.ID, key.SessionID,
|
||||
)
|
||||
if err := l.cleanupSandboxID(ctx, summary.ID); err != nil {
|
||||
return nil, false, fmt.Errorf(
|
||||
"delete unusable owned remote sandbox %q: %w",
|
||||
summary.ID,
|
||||
err,
|
||||
)
|
||||
}
|
||||
continue
|
||||
}
|
||||
if err := l.cleanupOwnedDuplicates(ctx, summaries, summary.ID, metadata); err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
|
|
@ -322,7 +407,16 @@ func (l *remoteSessionLifecycle) recoverOwnedSandbox(
|
|||
if templateID == "" {
|
||||
templateID = l.createRequest.TemplateID
|
||||
}
|
||||
binding := l.newBinding(key, summary.ID, templateID, summary.StartedAt)
|
||||
// Reached only when inbound is public or the provider re-issued the
|
||||
// token above, so an empty token here is a policy that does not need
|
||||
// one rather than a credential we lost.
|
||||
binding := l.newBinding(
|
||||
key,
|
||||
summary.ID,
|
||||
templateID,
|
||||
InboundTokenOf(handle),
|
||||
summary.StartedAt,
|
||||
)
|
||||
created, err := l.bindings.Create(ctx, key, binding)
|
||||
if err != nil {
|
||||
return nil, false, fmt.Errorf("bind owned remote sandbox: %w", err)
|
||||
|
|
@ -363,6 +457,19 @@ func (l *remoteSessionLifecycle) createAndBind(
|
|||
if err := l.validateHandle(handle, ""); err != nil {
|
||||
return nil, errors.Join(err, l.cleanupCreated(ctx, handle))
|
||||
}
|
||||
// Same 403 wedge as metadata adoption: the provider issues this token
|
||||
// only at create time, and authentication errors are not replaceable.
|
||||
// Binding an empty token would leave the session permanently stuck, so
|
||||
// fail the create and destroy the unusable sandbox instead.
|
||||
if l.missingRequiredInboundToken(handle) {
|
||||
return nil, errors.Join(
|
||||
fmt.Errorf(
|
||||
"create remote sandbox %q: inbound traffic token missing under a closed-inbound policy",
|
||||
handle.ID(),
|
||||
),
|
||||
l.cleanupCreated(ctx, handle),
|
||||
)
|
||||
}
|
||||
|
||||
exists, checkErr := l.sessionChecker.SessionExists(ctx, key)
|
||||
if checkErr != nil {
|
||||
|
|
@ -379,6 +486,7 @@ func (l *remoteSessionLifecycle) createAndBind(
|
|||
key,
|
||||
handle.ID(),
|
||||
request.TemplateID,
|
||||
InboundTokenOf(handle),
|
||||
l.now().UTC(),
|
||||
)
|
||||
created, bindErr := l.bindings.Create(ctx, key, binding)
|
||||
|
|
@ -437,7 +545,10 @@ func (l *remoteSessionLifecycle) connectKnownWinner(
|
|||
l.client.Provider(),
|
||||
)
|
||||
}
|
||||
handle, replace, err := l.connectBinding(ctx, winner)
|
||||
handle, replace, err := l.connectBinding(ctx, SessionSandboxKey{
|
||||
TenantID: winner.TenantID,
|
||||
SessionID: winner.SessionID,
|
||||
}, winner)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
|
@ -584,20 +695,22 @@ func (l *remoteSessionLifecycle) newBinding(
|
|||
key SessionSandboxKey,
|
||||
sandboxID string,
|
||||
templateID string,
|
||||
trafficAccessToken string,
|
||||
createdAt time.Time,
|
||||
) SessionSandboxBinding {
|
||||
if createdAt.IsZero() {
|
||||
createdAt = l.now().UTC()
|
||||
}
|
||||
return SessionSandboxBinding{
|
||||
Version: SessionSandboxBindingVersion,
|
||||
Provider: l.client.Provider(),
|
||||
TenantID: key.TenantID,
|
||||
SessionID: key.SessionID,
|
||||
SandboxID: sandboxID,
|
||||
TemplateID: templateID,
|
||||
CreatedAt: createdAt.UTC(),
|
||||
ConfigID: l.sandboxConfigID,
|
||||
Version: SessionSandboxBindingVersion,
|
||||
Provider: l.client.Provider(),
|
||||
TenantID: key.TenantID,
|
||||
SessionID: key.SessionID,
|
||||
SandboxID: sandboxID,
|
||||
TemplateID: templateID,
|
||||
CreatedAt: createdAt.UTC(),
|
||||
ConfigID: l.sandboxConfigID,
|
||||
TrafficAccessToken: trafficAccessToken,
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -128,6 +128,15 @@ func (s *bindingStoreFaults) DeleteIfMatch(
|
|||
return s.base.DeleteIfMatch(ctx, key, provider, sandboxID)
|
||||
}
|
||||
|
||||
func (s *bindingStoreFaults) ReplaceTrafficTokenIfMatch(
|
||||
ctx context.Context,
|
||||
key SessionSandboxKey,
|
||||
expected SessionSandboxBinding,
|
||||
token string,
|
||||
) (bool, error) {
|
||||
return s.base.ReplaceTrafficTokenIfMatch(ctx, key, expected, token)
|
||||
}
|
||||
|
||||
func (s *bindingStoreFaults) InvalidateByConfig(
|
||||
ctx context.Context,
|
||||
tenantID uint64,
|
||||
|
|
@ -173,6 +182,132 @@ func newTestRemoteSessionLifecycle(
|
|||
return lifecycle
|
||||
}
|
||||
|
||||
func TestCreateAndBindPersistsInboundToken(t *testing.T) {
|
||||
client := newFakeRemoteClient(SandboxTypeCube)
|
||||
client.trafficAccessToken = "traffic-token"
|
||||
store := NewMemorySessionSandboxBindingStore()
|
||||
lifecycle := newTestRemoteSessionLifecycle(
|
||||
t, client, store, &fakeSessionExistenceChecker{exists: true},
|
||||
)
|
||||
key := SessionSandboxKey{TenantID: 1, SessionID: "session-1"}
|
||||
|
||||
_, err := lifecycle.Resolve(context.Background(), key)
|
||||
require.NoError(t, err)
|
||||
|
||||
binding, err := store.Get(context.Background(), key)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "traffic-token", binding.TrafficAccessToken,
|
||||
"the token is issued once, so the binding is the only place it survives a pause")
|
||||
}
|
||||
|
||||
func TestCreateAndBindRejectsTokenlessSandboxWhenInboundClosed(t *testing.T) {
|
||||
closed := false
|
||||
client := newFakeRemoteClient(SandboxTypeE2B)
|
||||
client.trafficAccessToken = ""
|
||||
store := NewMemorySessionSandboxBindingStore()
|
||||
lifecycle := newTestRemoteSessionLifecycleWithPolicy(
|
||||
t, client, store, &fakeSessionExistenceChecker{exists: true},
|
||||
RemoteNetworkPolicy{AllowPublicTraffic: &closed},
|
||||
)
|
||||
key := SessionSandboxKey{TenantID: 1, SessionID: "session-1"}
|
||||
|
||||
_, err := lifecycle.Resolve(context.Background(), key)
|
||||
|
||||
require.Error(t, err)
|
||||
require.Contains(t, err.Error(), "inbound traffic token missing")
|
||||
creates, _, _, _, deletes := client.counts()
|
||||
require.Equal(t, 1, creates)
|
||||
require.Equal(t, 1, deletes, "the unusable sandbox must be destroyed, not bound")
|
||||
binding, err := store.Get(context.Background(), key)
|
||||
require.NoError(t, err)
|
||||
require.Nil(t, binding, "an empty token must not be persisted")
|
||||
}
|
||||
|
||||
func TestCreateAndBindAllowsTokenlessSandboxWhenProviderHasNoInboundCredential(t *testing.T) {
|
||||
closed := false
|
||||
client := newFakeRemoteClient(SandboxTypeDocker)
|
||||
client.omitsInboundTokenCarrier = true
|
||||
store := NewMemorySessionSandboxBindingStore()
|
||||
lifecycle := newTestRemoteSessionLifecycleWithPolicy(
|
||||
t, client, store, &fakeSessionExistenceChecker{exists: true},
|
||||
RemoteNetworkPolicy{AllowPublicTraffic: &closed},
|
||||
)
|
||||
key := SessionSandboxKey{TenantID: 1, SessionID: "session-1"}
|
||||
|
||||
handle, err := lifecycle.Resolve(context.Background(), key)
|
||||
|
||||
require.NoError(t, err)
|
||||
require.NotEmpty(t, handle.ID())
|
||||
creates, _, _, _, deletes := client.counts()
|
||||
require.Equal(t, 1, creates)
|
||||
require.Zero(t, deletes)
|
||||
}
|
||||
|
||||
func TestCreateAndBindPersistsTokenWhenInboundClosed(t *testing.T) {
|
||||
closed := false
|
||||
client := newFakeRemoteClient(SandboxTypeCube)
|
||||
client.trafficAccessToken = "traffic-token"
|
||||
store := NewMemorySessionSandboxBindingStore()
|
||||
lifecycle := newTestRemoteSessionLifecycleWithPolicy(
|
||||
t, client, store, &fakeSessionExistenceChecker{exists: true},
|
||||
RemoteNetworkPolicy{AllowPublicTraffic: &closed},
|
||||
)
|
||||
key := SessionSandboxKey{TenantID: 1, SessionID: "session-1"}
|
||||
|
||||
_, err := lifecycle.Resolve(context.Background(), key)
|
||||
require.NoError(t, err)
|
||||
|
||||
binding, err := store.Get(context.Background(), key)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "traffic-token", binding.TrafficAccessToken)
|
||||
}
|
||||
|
||||
func TestResolveReconnectPassesStoredInboundToken(t *testing.T) {
|
||||
client := newFakeRemoteClient(SandboxTypeCube)
|
||||
client.trafficAccessToken = "traffic-token"
|
||||
store := NewMemorySessionSandboxBindingStore()
|
||||
lifecycle := newTestRemoteSessionLifecycle(
|
||||
t, client, store, &fakeSessionExistenceChecker{exists: true},
|
||||
)
|
||||
key := SessionSandboxKey{TenantID: 1, SessionID: "session-1"}
|
||||
|
||||
_, err := lifecycle.Resolve(context.Background(), key)
|
||||
require.NoError(t, err)
|
||||
_, err = lifecycle.Resolve(context.Background(), key)
|
||||
require.NoError(t, err)
|
||||
|
||||
client.mu.Lock()
|
||||
connects := append([]RemoteConnectRequest(nil), client.connects...)
|
||||
client.mu.Unlock()
|
||||
require.Len(t, connects, 1)
|
||||
require.Equal(t, "traffic-token", connects[0].TrafficAccessToken)
|
||||
}
|
||||
|
||||
func TestResolveReconnectPersistsProviderReissuedInboundToken(t *testing.T) {
|
||||
client := newFakeRemoteClient(SandboxTypeCube)
|
||||
client.trafficAccessToken = "create-token"
|
||||
store := NewMemorySessionSandboxBindingStore()
|
||||
lifecycle := newTestRemoteSessionLifecycle(
|
||||
t, client, store, &fakeSessionExistenceChecker{exists: true},
|
||||
)
|
||||
key := SessionSandboxKey{TenantID: 1, SessionID: "session-1"}
|
||||
|
||||
_, err := lifecycle.Resolve(context.Background(), key)
|
||||
require.NoError(t, err)
|
||||
|
||||
client.mu.Lock()
|
||||
client.connectTrafficToken = "rotated-token"
|
||||
client.mu.Unlock()
|
||||
|
||||
_, err = lifecycle.Resolve(context.Background(), key)
|
||||
require.NoError(t, err)
|
||||
|
||||
binding, err := store.Get(context.Background(), key)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "rotated-token", binding.TrafficAccessToken,
|
||||
"a token the provider reissued on connect must replace the stored copy")
|
||||
}
|
||||
|
||||
func TestRemoteSessionLifecycleCreatesOnceAcrossCoordinators(t *testing.T) {
|
||||
store := NewMemorySessionSandboxBindingStore()
|
||||
client := newFakeRemoteClient(SandboxTypeCube)
|
||||
|
|
@ -384,6 +519,138 @@ func TestRemoteSessionLifecycleDeletesDuplicateMetadataCandidates(t *testing.T)
|
|||
}
|
||||
}
|
||||
|
||||
func newTestRemoteSessionLifecycleWithPolicy(
|
||||
t *testing.T,
|
||||
client RemoteSandboxClient,
|
||||
store SessionSandboxBindingStore,
|
||||
checker SessionExistenceChecker,
|
||||
policy RemoteNetworkPolicy,
|
||||
) *remoteSessionLifecycle {
|
||||
t.Helper()
|
||||
lifecycle, err := newRemoteSessionLifecycle(
|
||||
client,
|
||||
store,
|
||||
checker,
|
||||
RemoteCreateRequest{
|
||||
TemplateID: "template-a",
|
||||
Network: policy,
|
||||
Timeout: RemoteTimeoutPolicy{
|
||||
Mode: RemoteTimeoutExplicit,
|
||||
Value: time.Hour,
|
||||
Action: RemoteOnTimeoutPause,
|
||||
},
|
||||
},
|
||||
time.Second,
|
||||
"",
|
||||
)
|
||||
require.NoError(t, err)
|
||||
return lifecycle
|
||||
}
|
||||
|
||||
// A metadata-adopted sandbox has no binding to supply its inbound token. When
|
||||
// the policy closed inbound, adopting it would bind a sandbox whose every
|
||||
// data-plane call answers 403 — and 403 is RemoteErrorKindAuthentication, which
|
||||
// CanReplaceRemoteBinding refuses to replace, so the session would stay wedged
|
||||
// until an operator intervened. Creating a fresh sandbox is the only recovery.
|
||||
func TestRemoteSessionLifecycleSkipsTokenlessAdoptionWhenInboundClosed(t *testing.T) {
|
||||
closed := false
|
||||
client := newFakeRemoteClient(SandboxTypeE2B)
|
||||
client.trafficAccessToken = "fresh-token"
|
||||
store := NewMemorySessionSandboxBindingStore()
|
||||
lifecycle := newTestRemoteSessionLifecycleWithPolicy(
|
||||
t, client, store, &fakeSessionExistenceChecker{exists: true},
|
||||
RemoteNetworkPolicy{AllowPublicTraffic: &closed},
|
||||
)
|
||||
key := SessionSandboxKey{TenantID: 42, SessionID: "session-a"}
|
||||
client.addSandbox("orphan", "template-a", RemoteStateRunning, lifecycle.metadata(key), time.Unix(100, 0))
|
||||
|
||||
handle, err := lifecycle.Resolve(context.Background(), key)
|
||||
|
||||
require.NoError(t, err)
|
||||
require.NotEqual(t, "orphan", handle.ID())
|
||||
creates, _, _, _, _ := client.counts()
|
||||
require.Equal(t, 1, creates)
|
||||
binding, err := store.Get(context.Background(), key)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, handle.ID(), binding.SandboxID)
|
||||
require.Equal(t, "fresh-token", binding.TrafficAccessToken)
|
||||
// The abandoned sandbox is deleted, not left behind. Nothing in-tree
|
||||
// reclaims orphans (ReapOrphanSandboxes has no production caller), and
|
||||
// without this every binding loss would strand one more paused sandbox.
|
||||
require.False(t, client.hasSandbox("orphan"))
|
||||
_, _, _, _, deletes := client.counts()
|
||||
require.Equal(t, 1, deletes)
|
||||
}
|
||||
|
||||
// Docker has no inbound credential at all, so its handle does not implement
|
||||
// RemoteInboundTokenCarrier and InboundTokenOf always returns "". The guard
|
||||
// must not read that as a lost credential: Docker never had the 403 wedge, and
|
||||
// firing here would destroy a healthy container and its /workspace on every
|
||||
// binding loss — on precisely the single-node deployment the guard was for.
|
||||
func TestRemoteSessionLifecycleAdoptsWhenProviderHasNoInboundCredential(t *testing.T) {
|
||||
closed := false
|
||||
client := newFakeRemoteClient(SandboxTypeDocker)
|
||||
client.omitsInboundTokenCarrier = true
|
||||
store := NewMemorySessionSandboxBindingStore()
|
||||
lifecycle := newTestRemoteSessionLifecycleWithPolicy(
|
||||
t, client, store, &fakeSessionExistenceChecker{exists: true},
|
||||
RemoteNetworkPolicy{AllowPublicTraffic: &closed},
|
||||
)
|
||||
key := SessionSandboxKey{TenantID: 42, SessionID: "session-a"}
|
||||
client.addSandbox("existing", "template-a", RemoteStateRunning, lifecycle.metadata(key), time.Unix(100, 0))
|
||||
|
||||
handle, err := lifecycle.Resolve(context.Background(), key)
|
||||
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "existing", handle.ID())
|
||||
creates, _, _, _, deletes := client.counts()
|
||||
require.Zero(t, creates)
|
||||
require.Zero(t, deletes)
|
||||
}
|
||||
|
||||
func TestRemoteSessionLifecycleAdoptsWhenProviderReissuesInboundToken(t *testing.T) {
|
||||
closed := false
|
||||
client := newFakeRemoteClient(SandboxTypeE2B)
|
||||
client.trafficAccessToken = "reissued-token"
|
||||
client.reissuesTokenOnConnect = true
|
||||
store := NewMemorySessionSandboxBindingStore()
|
||||
lifecycle := newTestRemoteSessionLifecycleWithPolicy(
|
||||
t, client, store, &fakeSessionExistenceChecker{exists: true},
|
||||
RemoteNetworkPolicy{AllowPublicTraffic: &closed},
|
||||
)
|
||||
key := SessionSandboxKey{TenantID: 42, SessionID: "session-a"}
|
||||
client.addSandbox("orphan", "template-a", RemoteStateRunning, lifecycle.metadata(key), time.Unix(100, 0))
|
||||
|
||||
handle, err := lifecycle.Resolve(context.Background(), key)
|
||||
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "orphan", handle.ID())
|
||||
creates, _, _, _, _ := client.counts()
|
||||
require.Zero(t, creates)
|
||||
binding, err := store.Get(context.Background(), key)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "reissued-token", binding.TrafficAccessToken)
|
||||
}
|
||||
|
||||
func TestRemoteSessionLifecycleAdoptsTokenlessSandboxWhenInboundPublic(t *testing.T) {
|
||||
open := true
|
||||
client := newFakeRemoteClient(SandboxTypeE2B)
|
||||
store := NewMemorySessionSandboxBindingStore()
|
||||
lifecycle := newTestRemoteSessionLifecycleWithPolicy(
|
||||
t, client, store, &fakeSessionExistenceChecker{exists: true},
|
||||
RemoteNetworkPolicy{AllowPublicTraffic: &open},
|
||||
)
|
||||
key := SessionSandboxKey{TenantID: 42, SessionID: "session-a"}
|
||||
client.addSandbox("orphan", "template-a", RemoteStateRunning, lifecycle.metadata(key), time.Unix(100, 0))
|
||||
|
||||
handle, err := lifecycle.Resolve(context.Background(), key)
|
||||
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "orphan", handle.ID())
|
||||
creates, _, _, _, _ := client.counts()
|
||||
require.Zero(t, creates)
|
||||
}
|
||||
|
||||
func TestRemoteSessionLifecycleStopsDuplicateCleanupAfterLockLoss(t *testing.T) {
|
||||
for _, provider := range []RemoteProvider{SandboxTypeCube, SandboxTypeE2B} {
|
||||
t.Run(string(provider), func(t *testing.T) {
|
||||
|
|
|
|||
|
|
@ -899,7 +899,10 @@ func (m *SessionBoundManager) lookupSessionHandle(
|
|||
if binding == nil || binding.Provider != m.client.Provider() {
|
||||
return nil, false, nil
|
||||
}
|
||||
handle, err := m.client.Connect(ctx, binding.SandboxID)
|
||||
handle, err := m.client.Connect(ctx, RemoteConnectRequest{
|
||||
SandboxID: binding.SandboxID,
|
||||
TrafficAccessToken: binding.TrafficAccessToken,
|
||||
})
|
||||
if err != nil {
|
||||
if CanReplaceRemoteBinding(err) {
|
||||
return nil, false, nil
|
||||
|
|
@ -910,6 +913,7 @@ func (m *SessionBoundManager) lookupSessionHandle(
|
|||
handle.Provider() != m.client.Provider() {
|
||||
return nil, false, errors.New("sandbox: remote handle does not match binding")
|
||||
}
|
||||
persistInboundToken(ctx, m.bindings, key, *binding, handle)
|
||||
return handle, true, nil
|
||||
}
|
||||
|
||||
|
|
@ -1088,6 +1092,7 @@ func buildSessionCreateRequest(provider RemoteProvider, cfg *Config) (RemoteCrea
|
|||
return RemoteCreateRequest{
|
||||
TemplateID: cfg.CubeTemplate,
|
||||
EnvVars: envVars,
|
||||
Network: cfg.Network,
|
||||
Timeout: RemoteTimeoutPolicy{
|
||||
Mode: RemoteTimeoutExplicit,
|
||||
Value: ttl,
|
||||
|
|
@ -1104,6 +1109,7 @@ func buildSessionCreateRequest(provider RemoteProvider, cfg *Config) (RemoteCrea
|
|||
return RemoteCreateRequest{
|
||||
TemplateID: cfg.E2BTemplate,
|
||||
EnvVars: envVars,
|
||||
Network: cfg.Network,
|
||||
Timeout: RemoteTimeoutPolicy{
|
||||
Mode: RemoteTimeoutExplicit,
|
||||
Value: ttl,
|
||||
|
|
@ -1117,9 +1123,13 @@ func buildSessionCreateRequest(provider RemoteProvider, cfg *Config) (RemoteCrea
|
|||
if ttl <= 0 {
|
||||
ttl = DefaultDockerIdleTTL
|
||||
}
|
||||
// Docker can only honour the overall egress switch (see
|
||||
// DockerRemoteClient.networkMode); the allow / deny lists are
|
||||
// rejected at save time so they cannot arrive here.
|
||||
return RemoteCreateRequest{
|
||||
TemplateID: cfg.DockerImage,
|
||||
EnvVars: envVars,
|
||||
Network: cfg.Network,
|
||||
Timeout: RemoteTimeoutPolicy{
|
||||
Mode: RemoteTimeoutExplicit,
|
||||
Value: ttl,
|
||||
|
|
|
|||
|
|
@ -400,6 +400,34 @@ func TestWriteSessionFileSucceedsWhenInstallDirectoryAlreadyExists(t *testing.T)
|
|||
require.Equal(t, skillDir+"/SKILL.md", writes[0].path)
|
||||
}
|
||||
|
||||
// The whole feature is inert without this: RemoteNetworkPolicy already existed
|
||||
// and both adapters already forwarded it, but nothing ever filled it in.
|
||||
func TestBuildSessionCreateRequestCarriesNetworkPolicy(t *testing.T) {
|
||||
denied := false
|
||||
cfg := DefaultConfig()
|
||||
cfg.CubeTemplate = "tpl-1"
|
||||
cfg.E2BTemplate = "tpl-1"
|
||||
cfg.DockerImage = "img-1"
|
||||
cfg.Network = RemoteNetworkPolicy{
|
||||
AllowInternetAccess: &denied,
|
||||
AllowOut: []string{"api.example.com"},
|
||||
DenyOut: []string{"0.0.0.0/0"},
|
||||
}
|
||||
|
||||
for _, provider := range []RemoteProvider{
|
||||
SandboxTypeCube, SandboxTypeE2B, SandboxTypeDocker,
|
||||
} {
|
||||
request, err := buildSessionCreateRequest(provider, cfg)
|
||||
require.NoError(t, err, "provider %s", provider)
|
||||
require.NotNil(t, request.Network.AllowInternetAccess, "provider %s", provider)
|
||||
require.False(t, *request.Network.AllowInternetAccess, "provider %s", provider)
|
||||
require.Equal(t, []string{"api.example.com"}, request.Network.AllowOut,
|
||||
"provider %s", provider)
|
||||
require.Equal(t, []string{"0.0.0.0/0"}, request.Network.DenyOut,
|
||||
"provider %s", provider)
|
||||
}
|
||||
}
|
||||
|
||||
func newSessionManagerExecTestHarness(t *testing.T) (*SessionBoundManager, *fakeRemoteClient) {
|
||||
t.Helper()
|
||||
|
||||
|
|
|
|||
|
|
@ -22,6 +22,7 @@ package sandbox
|
|||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
|
|
@ -43,6 +44,7 @@ func ResolveEffectiveConfig(
|
|||
}
|
||||
effective := *global
|
||||
if tenantCfg == nil {
|
||||
effective.Network = resolveNetworkPolicy(nil)
|
||||
return &effective, nil
|
||||
}
|
||||
// Keep the baseline's cross-cutting settings, drop everything provider
|
||||
|
|
@ -59,6 +61,7 @@ func ResolveEffectiveConfig(
|
|||
}
|
||||
overrideSeconds(&effective.DefaultTimeout, tenantCfg.DefaultTimeoutSec)
|
||||
effective.AllowPrivateEndpoints = tenantCfg.AllowPrivateEndpoints
|
||||
effective.Network = resolveNetworkPolicy(tenantCfg.Network)
|
||||
if tenantCfg.EnvVars != nil {
|
||||
effective.EnvVars = cloneMetadata(tenantCfg.EnvVars)
|
||||
}
|
||||
|
|
@ -176,6 +179,7 @@ func ResolveEffectiveConfig(
|
|||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
applyDockerNetworkPolicy(&effective)
|
||||
}
|
||||
return &effective, nil
|
||||
}
|
||||
|
|
@ -212,6 +216,7 @@ func clearProviderFields(cfg *Config) {
|
|||
cfg.E2BTemplate = ""
|
||||
cfg.E2BSandboxTTL = 0
|
||||
cfg.E2BHTTPTimeout = 0
|
||||
cfg.Network = RemoteNetworkPolicy{}
|
||||
}
|
||||
|
||||
// ErrUnsupportedSandboxType marks a sandbox type string we cannot honour. It is
|
||||
|
|
@ -280,3 +285,101 @@ func overrideSeconds(dst *time.Duration, seconds int) {
|
|||
*dst = time.Duration(seconds) * time.Second
|
||||
}
|
||||
}
|
||||
|
||||
// resolveNetworkPolicy turns the stored, admin-facing policy into the
|
||||
// provider-facing one. This is the single place the three inversions happen:
|
||||
//
|
||||
// - DenyEgressByDefault -> AllowInternetAccess=false
|
||||
// - AllowPublicInbound -> AllowPublicTraffic
|
||||
// - CubeEgressRule.Deny -> RemoteCubeEgressRule.Allow
|
||||
//
|
||||
// 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.
|
||||
func resolveNetworkPolicy(stored *types.SandboxNetworkPolicy) RemoteNetworkPolicy {
|
||||
allowEgress := true
|
||||
inboundPublic := false
|
||||
if stored != nil {
|
||||
allowEgress = !stored.DenyEgressByDefault
|
||||
inboundPublic = stored.AllowPublicInbound
|
||||
}
|
||||
policy := RemoteNetworkPolicy{
|
||||
AllowInternetAccess: &allowEgress,
|
||||
AllowPublicTraffic: &inboundPublic,
|
||||
}
|
||||
if stored == nil {
|
||||
return policy
|
||||
}
|
||||
policy.AllowOut = append([]string(nil), stored.AllowOut...)
|
||||
// Canonicalise first: any IPv4 /0 (including 1.2.3.4/0) collapses onto
|
||||
// 0.0.0.0/0, which is the spelling E2B string-matches as ALL_TRAFFIC.
|
||||
// Leaving a non-canonical /0 on the wire would pass validation and then
|
||||
// fail create, or accept a domain allow-list without actually denying the
|
||||
// rest of the internet.
|
||||
policy.DenyOut = types.CanonicalizeDenyOut(stored.DenyOut)
|
||||
// DenyEgressByDefault means "install a 0.0.0.0/0 deny-all" — that is the
|
||||
// stored field's documented definition — so materialise it as a real deny
|
||||
// entry instead of leaving it implied by the top-level switch. E2B
|
||||
// validates the two independently and rejects a create whose allowOut
|
||||
// names a domain unless denyOut carries the entry:
|
||||
//
|
||||
// 400 When specifying allowed domains in allow out, you must include
|
||||
// 'ALL_TRAFFIC' in deny out to block all other traffic.
|
||||
//
|
||||
// allow_internet_access=false does not satisfy it. Doing this here rather
|
||||
// than in the E2B adapter keeps the neutral policy self-consistent, so
|
||||
// every adapter and every reader of DenyOut sees the same deny-all the
|
||||
// admin asked for.
|
||||
if stored.DenyEgressByDefault && !types.DenyOutCoversAllIPv4(policy.DenyOut) {
|
||||
policy.DenyOut = append(policy.DenyOut, types.DenyAllIPv4)
|
||||
}
|
||||
|
||||
for _, rule := range stored.CubeRules {
|
||||
converted := RemoteCubeEgressRule{
|
||||
Name: rule.Name,
|
||||
Scheme: rule.Scheme,
|
||||
SNI: rule.SNI,
|
||||
Host: rule.Host,
|
||||
Methods: append([]string(nil), rule.Methods...),
|
||||
Path: rule.Path,
|
||||
Allow: !rule.Deny,
|
||||
Audit: rule.Audit,
|
||||
}
|
||||
for _, inject := range rule.Inject {
|
||||
converted.Inject = append(converted.Inject, RemoteHeaderInject{
|
||||
Header: inject.Header,
|
||||
Secret: inject.Secret,
|
||||
Format: inject.Format,
|
||||
})
|
||||
}
|
||||
policy.CubeRules = append(policy.CubeRules, converted)
|
||||
}
|
||||
for _, rule := range stored.E2BHostRules {
|
||||
converted := RemoteE2BHostRule{Host: rule.Host}
|
||||
if len(rule.Headers) > 0 {
|
||||
converted.Headers = make(map[string]string, len(rule.Headers))
|
||||
for name, value := range rule.Headers {
|
||||
converted.Headers[name] = value
|
||||
}
|
||||
}
|
||||
policy.E2BHostRules = append(policy.E2BHostRules, converted)
|
||||
}
|
||||
return policy
|
||||
}
|
||||
|
||||
// applyDockerNetworkPolicy maps docker.network_mode=none onto the resolved
|
||||
// egress switch so DeniesEgressByDefault (and the deep connectivity check)
|
||||
// agree with the network the adapter will actually create. The stored
|
||||
// SandboxNetworkPolicy stays empty on Docker configs; this is the Docker
|
||||
// form's overall switch expressed in the same field the rest of the stack
|
||||
// already consults.
|
||||
func applyDockerNetworkPolicy(cfg *Config) {
|
||||
if cfg == nil {
|
||||
return
|
||||
}
|
||||
if !strings.EqualFold(strings.TrimSpace(cfg.DockerNetworkMode), "none") {
|
||||
return
|
||||
}
|
||||
allow := false
|
||||
cfg.Network.AllowInternetAccess = &allow
|
||||
}
|
||||
|
|
|
|||
|
|
@ -9,7 +9,7 @@ import (
|
|||
)
|
||||
|
||||
func globalTestConfig() *Config {
|
||||
return &Config{
|
||||
cfg := &Config{
|
||||
Type: SandboxTypeE2B,
|
||||
DefaultTimeout: 60 * time.Second,
|
||||
E2BAPIKey: "global-key",
|
||||
|
|
@ -19,6 +19,8 @@ func globalTestConfig() *Config {
|
|||
E2BSandboxTTL: 10 * time.Minute,
|
||||
E2BHTTPTimeout: 30 * time.Second,
|
||||
}
|
||||
cfg.Network = resolveNetworkPolicy(nil)
|
||||
return cfg
|
||||
}
|
||||
|
||||
// completeE2BTenantConfig is the minimum a named E2B config must carry now that
|
||||
|
|
@ -33,6 +35,19 @@ func completeE2BTenantConfig() *types.TenantSandboxConfig {
|
|||
}
|
||||
}
|
||||
|
||||
// completeCubeTenantConfig is the minimum a named Cube config must carry now that nothing is inherited.
|
||||
func completeCubeTenantConfig() *types.TenantSandboxConfig {
|
||||
return &types.TenantSandboxConfig{
|
||||
SandboxType: "cube",
|
||||
Cube: &types.CubeSandboxConfig{
|
||||
APIURL: "https://203.0.113.20",
|
||||
ProxyURL: "https://203.0.113.21",
|
||||
SandboxDomain: "cube.app",
|
||||
TemplateID: "tpl-1",
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// A nil tenant config means "the deployment default backend", which is the one
|
||||
// path where the baseline is used as-is.
|
||||
func TestResolveEffectiveConfigNilTenantKeepsGlobal(t *testing.T) {
|
||||
|
|
@ -44,6 +59,27 @@ func TestResolveEffectiveConfigNilTenantKeepsGlobal(t *testing.T) {
|
|||
require.Equal(t, *global, *got)
|
||||
}
|
||||
|
||||
func TestResolveEffectiveConfigNilTenantMaterializesNetworkDefaults(t *testing.T) {
|
||||
global := &Config{Type: SandboxTypeDisabled, DefaultTimeout: time.Second}
|
||||
|
||||
got, err := ResolveEffectiveConfig(nil, global)
|
||||
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, got.Network.AllowInternetAccess)
|
||||
require.True(t, *got.Network.AllowInternetAccess)
|
||||
require.NotNil(t, got.Network.AllowPublicTraffic)
|
||||
require.False(t, *got.Network.AllowPublicTraffic)
|
||||
}
|
||||
|
||||
func TestDefaultConfigMaterializesNetworkDefaults(t *testing.T) {
|
||||
got := DefaultConfig()
|
||||
|
||||
require.NotNil(t, got.Network.AllowInternetAccess)
|
||||
require.True(t, *got.Network.AllowInternetAccess)
|
||||
require.NotNil(t, got.Network.AllowPublicTraffic)
|
||||
require.False(t, *got.Network.AllowPublicTraffic)
|
||||
}
|
||||
|
||||
func TestResolveEffectiveConfigDoesNotMutateGlobal(t *testing.T) {
|
||||
global := globalTestConfig()
|
||||
|
||||
|
|
@ -68,6 +104,210 @@ func TestResolveEffectiveConfigDoesNotInheritProviderFields(t *testing.T) {
|
|||
require.Empty(t, got.E2BSandboxDomain)
|
||||
}
|
||||
|
||||
func TestResolveEffectiveConfigTranslatesNetworkPolicy(t *testing.T) {
|
||||
tenantCfg := completeE2BTenantConfig()
|
||||
tenantCfg.Network = &types.SandboxNetworkPolicy{
|
||||
DenyEgressByDefault: true,
|
||||
AllowPublicInbound: false,
|
||||
AllowOut: []string{"*.example.com"},
|
||||
DenyOut: []string{"0.0.0.0/0"},
|
||||
E2BHostRules: []types.E2BHostRule{{
|
||||
Host: "api.example.com",
|
||||
Headers: map[string]string{"X-Key": "secret"},
|
||||
}},
|
||||
}
|
||||
|
||||
got, err := ResolveEffectiveConfig(tenantCfg, globalTestConfig())
|
||||
require.NoError(t, err)
|
||||
|
||||
require.NotNil(t, got.Network.AllowInternetAccess)
|
||||
require.False(t, *got.Network.AllowInternetAccess,
|
||||
"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")
|
||||
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)
|
||||
require.Equal(t, "secret", got.Network.E2BHostRules[0].Headers["X-Key"])
|
||||
}
|
||||
|
||||
// E2B rejects a create whose allowOut names a domain unless denyOut carries an
|
||||
// explicit deny-all; it does not accept allow_internet_access=false as a
|
||||
// substitute. Since DenyEgressByDefault means exactly "install a 0.0.0.0/0
|
||||
// deny-all", the resolver has to materialise that entry, or ticking the box the
|
||||
// validator recommends produces a payload the provider refuses.
|
||||
func TestResolveEffectiveConfigMaterialisesDenyAllEntry(t *testing.T) {
|
||||
tenantCfg := completeE2BTenantConfig()
|
||||
tenantCfg.Network = &types.SandboxNetworkPolicy{
|
||||
DenyEgressByDefault: true,
|
||||
AllowOut: []string{"*.example.com"},
|
||||
}
|
||||
|
||||
got, err := ResolveEffectiveConfig(tenantCfg, globalTestConfig())
|
||||
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, []string{"0.0.0.0/0"}, got.Network.DenyOut)
|
||||
require.True(t, got.Network.DeniesEgressByDefault())
|
||||
}
|
||||
|
||||
func TestResolveEffectiveConfigDoesNotDuplicateDenyAllEntry(t *testing.T) {
|
||||
for _, existing := range []string{"0.0.0.0/0", " 0.0.0.0/0 ", "1.2.3.4/0"} {
|
||||
t.Run(existing, func(t *testing.T) {
|
||||
tenantCfg := completeE2BTenantConfig()
|
||||
tenantCfg.Network = &types.SandboxNetworkPolicy{
|
||||
DenyEgressByDefault: true,
|
||||
AllowOut: []string{"*.example.com"},
|
||||
DenyOut: []string{existing},
|
||||
}
|
||||
|
||||
got, err := ResolveEffectiveConfig(tenantCfg, globalTestConfig())
|
||||
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, []string{types.DenyAllIPv4}, got.Network.DenyOut,
|
||||
"any IPv4 /0 must be rewritten to the canonical deny-all, not duplicated")
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolveEffectiveConfigCanonicalizesNonCanonicalDenyAll(t *testing.T) {
|
||||
tenantCfg := completeE2BTenantConfig()
|
||||
tenantCfg.Network = &types.SandboxNetworkPolicy{
|
||||
AllowOut: []string{"api.example.com"},
|
||||
DenyOut: []string{"10.0.0.0/8", "1.2.3.4/0"},
|
||||
}
|
||||
|
||||
got, err := ResolveEffectiveConfig(tenantCfg, globalTestConfig())
|
||||
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, []string{"10.0.0.0/8", types.DenyAllIPv4}, got.Network.DenyOut)
|
||||
require.True(t, got.Network.DeniesEgressByDefault())
|
||||
}
|
||||
|
||||
// The entry is the resolved form of DenyEgressByDefault, so an egress-open
|
||||
// policy must not acquire it.
|
||||
func TestResolveEffectiveConfigLeavesDenyOutAloneWhenEgressOpen(t *testing.T) {
|
||||
tenantCfg := completeE2BTenantConfig()
|
||||
tenantCfg.Network = &types.SandboxNetworkPolicy{
|
||||
DenyOut: []string{"169.254.169.254/32"},
|
||||
}
|
||||
|
||||
got, err := ResolveEffectiveConfig(tenantCfg, globalTestConfig())
|
||||
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, []string{"169.254.169.254/32"}, got.Network.DenyOut)
|
||||
require.False(t, got.Network.DeniesEgressByDefault())
|
||||
}
|
||||
|
||||
func TestResolveEffectiveConfigAllowsPublicInboundWhenConfigured(t *testing.T) {
|
||||
tenantCfg := completeE2BTenantConfig()
|
||||
tenantCfg.Network = &types.SandboxNetworkPolicy{AllowPublicInbound: true}
|
||||
|
||||
got, err := ResolveEffectiveConfig(tenantCfg, globalTestConfig())
|
||||
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, got.Network.AllowPublicTraffic)
|
||||
require.True(t, *got.Network.AllowPublicTraffic)
|
||||
}
|
||||
|
||||
func TestResolveEffectiveConfigDefaultsNetworkToEgressOpenInboundClosed(t *testing.T) {
|
||||
// No stored policy at all: the shipped default must still be explicit, so
|
||||
// the adapters do not have to re-derive it.
|
||||
got, err := ResolveEffectiveConfig(completeE2BTenantConfig(), globalTestConfig())
|
||||
require.NoError(t, err)
|
||||
|
||||
require.NotNil(t, got.Network.AllowInternetAccess)
|
||||
require.True(t, *got.Network.AllowInternetAccess)
|
||||
require.NotNil(t, got.Network.AllowPublicTraffic)
|
||||
require.False(t, *got.Network.AllowPublicTraffic)
|
||||
}
|
||||
|
||||
func TestResolveEffectiveConfigInvertsCubeRuleDeny(t *testing.T) {
|
||||
tenantCfg := completeCubeTenantConfig()
|
||||
tenantCfg.Network = &types.SandboxNetworkPolicy{
|
||||
CubeRules: []types.CubeEgressRule{
|
||||
{
|
||||
Name: "allow-api",
|
||||
Scheme: "https",
|
||||
SNI: "api.example.com",
|
||||
Host: "api.example.com",
|
||||
Methods: []string{"GET", "POST"},
|
||||
Path: "/v1/*",
|
||||
Audit: "full",
|
||||
Inject: []types.CubeHeaderInject{{
|
||||
Header: "Authorization",
|
||||
Secret: "token",
|
||||
Format: "Bearer %s",
|
||||
}},
|
||||
},
|
||||
{Name: "deny-uploads", SNI: "uploads.example.com", Deny: true},
|
||||
},
|
||||
}
|
||||
|
||||
got, err := ResolveEffectiveConfig(tenantCfg, globalTestConfig())
|
||||
require.NoError(t, err)
|
||||
|
||||
require.Len(t, got.Network.CubeRules, 2)
|
||||
require.True(t, got.Network.CubeRules[0].Allow,
|
||||
"a stored rule without Deny is an allow rule")
|
||||
require.Equal(t, "allow-api", got.Network.CubeRules[0].Name)
|
||||
require.Equal(t, "https", got.Network.CubeRules[0].Scheme)
|
||||
require.Equal(t, "api.example.com", got.Network.CubeRules[0].SNI)
|
||||
require.Equal(t, "api.example.com", got.Network.CubeRules[0].Host)
|
||||
require.Equal(t, []string{"GET", "POST"}, got.Network.CubeRules[0].Methods)
|
||||
require.Equal(t, "/v1/*", got.Network.CubeRules[0].Path)
|
||||
require.Equal(t, "full", got.Network.CubeRules[0].Audit)
|
||||
require.Equal(t, []RemoteHeaderInject{{
|
||||
Header: "Authorization",
|
||||
Secret: "token",
|
||||
Format: "Bearer %s",
|
||||
}}, got.Network.CubeRules[0].Inject)
|
||||
require.False(t, got.Network.CubeRules[1].Allow)
|
||||
}
|
||||
|
||||
func TestResolveEffectiveConfigCopiesNetworkPolicyCollections(t *testing.T) {
|
||||
stored := &types.SandboxNetworkPolicy{
|
||||
AllowOut: []string{"api.example.com"},
|
||||
CubeRules: []types.CubeEgressRule{{
|
||||
Name: "api",
|
||||
Host: "api.example.com",
|
||||
Methods: []string{"GET"},
|
||||
}},
|
||||
E2BHostRules: []types.E2BHostRule{{
|
||||
Host: "api.example.com",
|
||||
Headers: map[string]string{"Authorization": "stored-token"},
|
||||
}},
|
||||
}
|
||||
tenantCfg := completeE2BTenantConfig()
|
||||
tenantCfg.Network = stored
|
||||
|
||||
got, err := ResolveEffectiveConfig(tenantCfg, globalTestConfig())
|
||||
require.NoError(t, err)
|
||||
|
||||
got.Network.AllowOut[0] = "mutated.example.com"
|
||||
got.Network.CubeRules[0].Methods[0] = "POST"
|
||||
got.Network.E2BHostRules[0].Headers["Authorization"] = "mutated-token"
|
||||
|
||||
require.Equal(t, "api.example.com", stored.AllowOut[0])
|
||||
require.Equal(t, "GET", stored.CubeRules[0].Methods[0])
|
||||
require.Equal(t, "stored-token", stored.E2BHostRules[0].Headers["Authorization"])
|
||||
}
|
||||
|
||||
func TestResolveEffectiveConfigDoesNotInheritNetworkFromBaseline(t *testing.T) {
|
||||
// This assertion pins the resolved end state, not clearProviderFields as
|
||||
// the mechanism that produces it.
|
||||
baseline := globalTestConfig()
|
||||
inherited := true
|
||||
baseline.Network = RemoteNetworkPolicy{AllowPublicTraffic: &inherited}
|
||||
|
||||
got, err := ResolveEffectiveConfig(completeE2BTenantConfig(), baseline)
|
||||
require.NoError(t, err)
|
||||
|
||||
require.NotNil(t, got.Network.AllowPublicTraffic)
|
||||
require.False(t, *got.Network.AllowPublicTraffic,
|
||||
"policy belongs to the named config; the .env baseline must not leak in")
|
||||
}
|
||||
|
||||
// A leftover sub-struct from the deployment's other provider must not survive
|
||||
// either, or a cube config would silently answer with e2b coordinates.
|
||||
func TestResolveEffectiveConfigClearsInactiveProviderBaseline(t *testing.T) {
|
||||
|
|
@ -243,6 +483,32 @@ func TestResolveEffectiveConfigDetectsLocalDockerHostWhenBlank(t *testing.T) {
|
|||
require.Equal(t, "unix:///tmp/from-env.sock", effective.DockerHost)
|
||||
}
|
||||
|
||||
func TestResolveEffectiveConfigMapsDockerNoneToDeniedEgress(t *testing.T) {
|
||||
effective, err := ResolveEffectiveConfig(&types.TenantSandboxConfig{
|
||||
SandboxType: "docker",
|
||||
Docker: &types.DockerSandboxConfig{
|
||||
Image: "weknora:test",
|
||||
NetworkMode: "none",
|
||||
},
|
||||
}, DefaultConfig())
|
||||
require.NoError(t, err)
|
||||
require.True(t, effective.Network.DeniesEgressByDefault(),
|
||||
"docker network_mode=none is this backend's deny-all switch")
|
||||
}
|
||||
|
||||
func TestResolveEffectiveConfigKeepsDockerBridgeEgressOpen(t *testing.T) {
|
||||
t.Setenv("DOCKER_HOST", "unix:///tmp/from-env.sock")
|
||||
effective, err := ResolveEffectiveConfig(&types.TenantSandboxConfig{
|
||||
SandboxType: "docker",
|
||||
Docker: &types.DockerSandboxConfig{
|
||||
Image: "weknora:test",
|
||||
NetworkMode: "bridge",
|
||||
},
|
||||
}, DefaultConfig())
|
||||
require.NoError(t, err)
|
||||
require.False(t, effective.Network.DeniesEgressByDefault())
|
||||
}
|
||||
|
||||
func TestResolveEffectiveConfigRejectsPlaintextDockerTCP(t *testing.T) {
|
||||
_, err := ResolveEffectiveConfig(&types.TenantSandboxConfig{
|
||||
SandboxType: "docker",
|
||||
|
|
|
|||
|
|
@ -302,6 +302,16 @@ func SandboxConfigForResponse(cfg *TenantSandboxConfig, maskSecrets bool) *Tenan
|
|||
}
|
||||
out.EnvVars = envVars
|
||||
}
|
||||
// Injected headers carry credentials, so they are masked as a class the
|
||||
// same way EnvVars values are.
|
||||
if out.Network != nil {
|
||||
out.Network = out.Network.CloneWithSecrets(func(value string) string {
|
||||
if value == "" {
|
||||
return ""
|
||||
}
|
||||
return RedactedSecretPlaceholder
|
||||
})
|
||||
}
|
||||
return &out
|
||||
}
|
||||
|
||||
|
|
@ -347,6 +357,17 @@ func MergeSandboxConfigForUpdate(incoming, existing *TenantSandboxConfig) *Tenan
|
|||
out.EnvVars = envVars
|
||||
}
|
||||
|
||||
// Network is an editor-owned field, so incoming decides its shape; only
|
||||
// the credential values fall back to what is stored. Unlike SkillImage,
|
||||
// omitting it clears it — the admin deleting every rule must stick.
|
||||
if out.Network != nil {
|
||||
var prev *SandboxNetworkPolicy
|
||||
if existing != nil {
|
||||
prev = existing.Network
|
||||
}
|
||||
out.Network = mergeNetworkPolicyForUpdate(out.Network, prev)
|
||||
}
|
||||
|
||||
// SkillImage and VolumeMount are owned by the install / volume paths, not
|
||||
// by the sandbox settings form. The editor rebuilds the payload without
|
||||
// either field, so copying incoming as-is would wipe a live snapshot on
|
||||
|
|
@ -375,3 +396,55 @@ func MergeSandboxConfigForUpdate(incoming, existing *TenantSandboxConfig) *Tenan
|
|||
|
||||
return &out
|
||||
}
|
||||
|
||||
// mergeNetworkPolicyForUpdate resolves redacted injected-header secrets in
|
||||
// incoming against existing. Rules are matched by the identity the admin sees:
|
||||
// a Cube inject by (rule name, header name), an E2B header by (host, header
|
||||
// name). A renamed rule therefore loses its stored secret, which is correct —
|
||||
// there is no way to tell a rename from a replacement.
|
||||
func mergeNetworkPolicyForUpdate(
|
||||
incoming, existing *SandboxNetworkPolicy,
|
||||
) *SandboxNetworkPolicy {
|
||||
if incoming == nil {
|
||||
return nil
|
||||
}
|
||||
out := incoming.CloneWithSecrets(func(value string) string { return value })
|
||||
if existing == nil {
|
||||
return out
|
||||
}
|
||||
|
||||
storedCube := make(map[string]string)
|
||||
for _, rule := range existing.CubeRules {
|
||||
for _, inject := range rule.Inject {
|
||||
storedCube[networkSecretKey(rule.Name, inject.Header)] = inject.Secret
|
||||
}
|
||||
}
|
||||
for i, rule := range out.CubeRules {
|
||||
for j, inject := range rule.Inject {
|
||||
prev := storedCube[networkSecretKey(rule.Name, inject.Header)]
|
||||
out.CubeRules[i].Inject[j].Secret = PreserveIfRedacted(inject.Secret, prev)
|
||||
}
|
||||
}
|
||||
|
||||
storedE2B := make(map[string]string)
|
||||
for _, rule := range existing.E2BHostRules {
|
||||
for name, value := range rule.Headers {
|
||||
storedE2B[networkSecretKey(rule.Host, name)] = value
|
||||
}
|
||||
}
|
||||
for i, rule := range out.E2BHostRules {
|
||||
for name, value := range rule.Headers {
|
||||
prev := storedE2B[networkSecretKey(rule.Host, name)]
|
||||
out.E2BHostRules[i].Headers[name] = PreserveIfRedacted(value, prev)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// networkSecretKey is the identity the merge uses for one injected header.
|
||||
// Parent (rule name / host) and child (header name) are trimmed and folded so
|
||||
// a whitespace or HTTP-header case change is not treated as a rename that
|
||||
// drops the stored secret.
|
||||
func networkSecretKey(parent, child string) string {
|
||||
return strings.ToLower(strings.TrimSpace(parent)) + "\x00" + strings.ToLower(strings.TrimSpace(child))
|
||||
}
|
||||
|
|
|
|||
|
|
@ -6,6 +6,39 @@ import (
|
|||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestSandboxConfigValueEncryptsInjectedHeaderSecrets(t *testing.T) {
|
||||
t.Setenv("SYSTEM_AES_KEY", "0123456789abcdef0123456789abcdef")
|
||||
|
||||
cfg := &TenantSandboxConfig{
|
||||
SandboxType: "cube",
|
||||
Network: &SandboxNetworkPolicy{
|
||||
CubeRules: []CubeEgressRule{{
|
||||
Name: "allow-api",
|
||||
Host: "api.example.com",
|
||||
Inject: []CubeHeaderInject{{Header: "Authorization", Secret: "cube-secret"}},
|
||||
}},
|
||||
E2BHostRules: []E2BHostRule{{
|
||||
Host: "api.example.com",
|
||||
Headers: map[string]string{"X-Key": "e2b-secret"},
|
||||
}},
|
||||
},
|
||||
}
|
||||
|
||||
raw, err := cfg.Value()
|
||||
require.NoError(t, err)
|
||||
encoded := string(raw.([]byte))
|
||||
require.NotContains(t, encoded, "cube-secret")
|
||||
require.NotContains(t, encoded, "e2b-secret")
|
||||
// Header names stay readable, same rationale as EnvVars keys.
|
||||
require.Contains(t, encoded, "Authorization")
|
||||
require.Contains(t, encoded, "X-Key")
|
||||
|
||||
var loaded TenantSandboxConfig
|
||||
require.NoError(t, loaded.Scan(raw.([]byte)))
|
||||
require.Equal(t, "cube-secret", loaded.Network.CubeRules[0].Inject[0].Secret)
|
||||
require.Equal(t, "e2b-secret", loaded.Network.E2BHostRules[0].Headers["X-Key"])
|
||||
}
|
||||
|
||||
func TestSandboxConfigForResponseMasksSecrets(t *testing.T) {
|
||||
cfg := &TenantSandboxConfig{
|
||||
SandboxType: "e2b",
|
||||
|
|
@ -27,6 +60,31 @@ func TestSandboxConfigForResponseMasksSecrets(t *testing.T) {
|
|||
require.Equal(t, "hf-secret", cfg.EnvVars["HF_TOKEN"])
|
||||
}
|
||||
|
||||
func TestSandboxConfigForResponseMasksInjectedHeaderSecrets(t *testing.T) {
|
||||
cfg := &TenantSandboxConfig{
|
||||
Network: &SandboxNetworkPolicy{
|
||||
CubeRules: []CubeEgressRule{{
|
||||
Name: "allow-api",
|
||||
Host: "api.example.com",
|
||||
Inject: []CubeHeaderInject{{Header: "Authorization", Secret: "cube-secret"}},
|
||||
}},
|
||||
E2BHostRules: []E2BHostRule{{
|
||||
Host: "api.example.com",
|
||||
Headers: map[string]string{"X-Key": "e2b-secret", "X-Empty": ""},
|
||||
}},
|
||||
},
|
||||
}
|
||||
|
||||
out := SandboxConfigForResponse(cfg, true)
|
||||
|
||||
require.Equal(t, RedactedSecretPlaceholder, out.Network.CubeRules[0].Inject[0].Secret)
|
||||
require.Equal(t, RedactedSecretPlaceholder, out.Network.E2BHostRules[0].Headers["X-Key"])
|
||||
require.Empty(t, out.Network.E2BHostRules[0].Headers["X-Empty"],
|
||||
"an unset header value must not become a placeholder")
|
||||
require.Equal(t, "cube-secret", cfg.Network.CubeRules[0].Inject[0].Secret,
|
||||
"masking must not mutate the stored config")
|
||||
}
|
||||
|
||||
func TestSandboxConfigForResponseSkipsMaskingWhenDisabled(t *testing.T) {
|
||||
cfg := &TenantSandboxConfig{E2B: &E2BSandboxConfig{APIKey: "e2b-secret"}}
|
||||
|
||||
|
|
@ -67,6 +125,92 @@ func TestMergeSandboxConfigForUpdatePreservesRedactedSecrets(t *testing.T) {
|
|||
require.NotContains(t, out.EnvVars, "GONE", "env vars removed by the user must not resurrect")
|
||||
}
|
||||
|
||||
func TestMergeSandboxConfigForUpdatePreservesInjectedHeaderSecrets(t *testing.T) {
|
||||
existing := &TenantSandboxConfig{
|
||||
Network: &SandboxNetworkPolicy{
|
||||
CubeRules: []CubeEgressRule{{
|
||||
Name: "allow-api",
|
||||
Inject: []CubeHeaderInject{
|
||||
{Header: "Authorization", Secret: "old-auth"},
|
||||
{Header: "X-Trace", Secret: "old-trace"},
|
||||
},
|
||||
}},
|
||||
E2BHostRules: []E2BHostRule{{
|
||||
Host: "api.example.com",
|
||||
Headers: map[string]string{"X-Key": "old-key", "X-Other": "old-other"},
|
||||
}},
|
||||
},
|
||||
}
|
||||
incoming := &TenantSandboxConfig{
|
||||
Network: &SandboxNetworkPolicy{
|
||||
CubeRules: []CubeEgressRule{{
|
||||
Name: "allow-api",
|
||||
Inject: []CubeHeaderInject{
|
||||
{Header: "Authorization", Secret: RedactedSecretPlaceholder}, // untouched
|
||||
{Header: "X-Trace", Secret: "new-trace"}, // retyped
|
||||
},
|
||||
}},
|
||||
E2BHostRules: []E2BHostRule{{
|
||||
Host: "api.example.com",
|
||||
Headers: map[string]string{"X-Key": RedactedSecretPlaceholder},
|
||||
}},
|
||||
},
|
||||
}
|
||||
|
||||
out := MergeSandboxConfigForUpdate(incoming, existing)
|
||||
|
||||
require.Equal(t, "old-auth", out.Network.CubeRules[0].Inject[0].Secret)
|
||||
require.Equal(t, "new-trace", out.Network.CubeRules[0].Inject[1].Secret)
|
||||
require.Equal(t, "old-key", out.Network.E2BHostRules[0].Headers["X-Key"])
|
||||
// A header the admin deleted must actually go, not be restored.
|
||||
require.NotContains(t, out.Network.E2BHostRules[0].Headers, "X-Other")
|
||||
}
|
||||
|
||||
func TestMergeSandboxConfigForUpdateMatchesInjectedHeadersCaseInsensitively(t *testing.T) {
|
||||
existing := &TenantSandboxConfig{
|
||||
Network: &SandboxNetworkPolicy{
|
||||
CubeRules: []CubeEgressRule{{
|
||||
Name: "Allow-API",
|
||||
Inject: []CubeHeaderInject{{Header: "Authorization", Secret: "old-auth"}},
|
||||
}},
|
||||
E2BHostRules: []E2BHostRule{{
|
||||
Host: "API.example.com",
|
||||
Headers: map[string]string{"X-Key": "old-key"},
|
||||
}},
|
||||
},
|
||||
}
|
||||
incoming := &TenantSandboxConfig{
|
||||
Network: &SandboxNetworkPolicy{
|
||||
CubeRules: []CubeEgressRule{{
|
||||
Name: "allow-api",
|
||||
Inject: []CubeHeaderInject{{Header: "authorization", Secret: RedactedSecretPlaceholder}},
|
||||
}},
|
||||
E2BHostRules: []E2BHostRule{{
|
||||
Host: " api.example.com ",
|
||||
Headers: map[string]string{"x-key": RedactedSecretPlaceholder},
|
||||
}},
|
||||
},
|
||||
}
|
||||
|
||||
out := MergeSandboxConfigForUpdate(incoming, existing)
|
||||
|
||||
require.Equal(t, "old-auth", out.Network.CubeRules[0].Inject[0].Secret,
|
||||
"HTTP header case and rule-name case must not drop the stored secret")
|
||||
require.Equal(t, "old-key", out.Network.E2BHostRules[0].Headers["x-key"],
|
||||
"host whitespace and header case must not drop the stored secret")
|
||||
}
|
||||
|
||||
func TestMergeSandboxConfigForUpdateDropsNetworkWhenIncomingOmitsIt(t *testing.T) {
|
||||
existing := &TenantSandboxConfig{
|
||||
Network: &SandboxNetworkPolicy{DenyEgressByDefault: true},
|
||||
}
|
||||
|
||||
out := MergeSandboxConfigForUpdate(&TenantSandboxConfig{}, existing)
|
||||
|
||||
require.Nil(t, out.Network,
|
||||
"network is an editor-owned field: omitting it must clear it, unlike SkillImage")
|
||||
}
|
||||
|
||||
func TestMergeSandboxConfigForUpdateHandlesNilExisting(t *testing.T) {
|
||||
incoming := &TenantSandboxConfig{E2B: &E2BSandboxConfig{APIKey: RedactedSecretPlaceholder}}
|
||||
|
||||
|
|
|
|||
|
|
@ -0,0 +1,551 @@
|
|||
// Sandbox network policy stored on a tenant sandbox config.
|
||||
//
|
||||
// One sandbox config carries one network policy, applied to every sandbox
|
||||
// created from it — chat sessions, skill installs and connectivity probes
|
||||
// alike. The provider-facing translation lives in internal/sandbox; this file
|
||||
// is only the stored shape, its secret handling, and its validation.
|
||||
|
||||
package types
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"net"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// 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.
|
||||
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 bool `json:"allow_public_inbound,omitempty"`
|
||||
|
||||
// AllowOut accepts IPv4, IPv4 CIDR, a DNS name, or a single-label
|
||||
// wildcard such as "*.example.com". Domain entries are only meaningful
|
||||
// together with a deny-all; see ValidateSandboxNetworkPolicy.
|
||||
AllowOut []string `json:"allow_out,omitempty"`
|
||||
|
||||
// DenyOut accepts IPv4 and IPv4 CIDR only. Neither provider can deny a
|
||||
// domain: denial is a pure longest-prefix match on the destination IP.
|
||||
DenyOut []string `json:"deny_out,omitempty"`
|
||||
|
||||
// CubeRules are validated whenever present and consumed only by the Cube
|
||||
// provider adapter.
|
||||
CubeRules []CubeEgressRule `json:"cube_rules,omitempty"`
|
||||
|
||||
// E2BHostRules are validated whenever present and consumed only by the E2B
|
||||
// provider adapter.
|
||||
E2BHostRules []E2BHostRule `json:"e2b_host_rules,omitempty"`
|
||||
}
|
||||
|
||||
// CubeEgressRule mirrors cubesandbox.Rule. Match fields are AND-ed; Methods is
|
||||
// OR-ed internally.
|
||||
type CubeEgressRule struct {
|
||||
Name string `json:"name"`
|
||||
Scheme string `json:"scheme,omitempty"`
|
||||
SNI string `json:"sni,omitempty"`
|
||||
Host string `json:"host,omitempty"`
|
||||
Methods []string `json:"methods,omitempty"`
|
||||
Path string `json:"path,omitempty"`
|
||||
|
||||
// Deny inverts the action, which defaults to allow. A deny rule still
|
||||
// needs Host or SNI: the target has to reach CubeEgress for it to answer
|
||||
// with a request-level 403 instead of the network layer dropping it.
|
||||
Deny bool `json:"deny,omitempty"`
|
||||
|
||||
// Audit is none | metadata | full. Empty uses the server default.
|
||||
Audit string `json:"audit,omitempty"`
|
||||
|
||||
// Inject adds credential headers on allowed HTTPS requests.
|
||||
Inject []CubeHeaderInject `json:"inject,omitempty"`
|
||||
}
|
||||
|
||||
// CubeHeaderInject mirrors cubesandbox.Inject. Secret is a credential and is
|
||||
// encrypted at rest; Header and Format are not.
|
||||
type CubeHeaderInject struct {
|
||||
Header string `json:"header"`
|
||||
Secret string `json:"secret"`
|
||||
Format string `json:"format,omitempty"`
|
||||
}
|
||||
|
||||
// E2BHostRule mirrors one entry of e2b.NetworkConfig.Rules. Host must also
|
||||
// appear in AllowOut: a rule grants no egress on its own.
|
||||
type E2BHostRule struct {
|
||||
Host string `json:"host"`
|
||||
// Headers values are credentials and are encrypted at rest; names stay
|
||||
// readable so operators can see which headers are injected.
|
||||
Headers map[string]string `json:"headers,omitempty"`
|
||||
}
|
||||
|
||||
// CloneWithSecrets deep-copies p, passing every credential-bearing field
|
||||
// through transform. Both the encrypt (Value), decrypt (Scan) and mask
|
||||
// (SandboxConfigForResponse) directions share it so they cannot drift about
|
||||
// which fields count as secrets. The receiver is never mutated.
|
||||
func (p *SandboxNetworkPolicy) CloneWithSecrets(
|
||||
transform func(string) string,
|
||||
) *SandboxNetworkPolicy {
|
||||
if p == nil {
|
||||
return nil
|
||||
}
|
||||
out := *p
|
||||
out.AllowOut = append([]string(nil), p.AllowOut...)
|
||||
out.DenyOut = append([]string(nil), p.DenyOut...)
|
||||
|
||||
if p.CubeRules != nil {
|
||||
rules := make([]CubeEgressRule, len(p.CubeRules))
|
||||
for i, rule := range p.CubeRules {
|
||||
copied := rule
|
||||
copied.Methods = append([]string(nil), rule.Methods...)
|
||||
if rule.Inject != nil {
|
||||
injects := make([]CubeHeaderInject, len(rule.Inject))
|
||||
for j, inject := range rule.Inject {
|
||||
injects[j] = inject
|
||||
injects[j].Secret = transform(inject.Secret)
|
||||
}
|
||||
copied.Inject = injects
|
||||
}
|
||||
rules[i] = copied
|
||||
}
|
||||
out.CubeRules = rules
|
||||
}
|
||||
|
||||
if p.E2BHostRules != nil {
|
||||
hostRules := make([]E2BHostRule, len(p.E2BHostRules))
|
||||
for i, rule := range p.E2BHostRules {
|
||||
copied := rule
|
||||
if rule.Headers != nil {
|
||||
headers := make(map[string]string, len(rule.Headers))
|
||||
for name, value := range rule.Headers {
|
||||
headers[name] = transform(value)
|
||||
}
|
||||
copied.Headers = headers
|
||||
}
|
||||
hostRules[i] = copied
|
||||
}
|
||||
out.E2BHostRules = hostRules
|
||||
}
|
||||
return &out
|
||||
}
|
||||
|
||||
// e2bNetworkLimits mirror the hard limits E2B enforces server-side. Checking
|
||||
// them here turns a 400 at sandbox-create time into a message on the form the
|
||||
// admin is looking at.
|
||||
const (
|
||||
e2bMaxRuleDomains = 10
|
||||
e2bMaxHeadersPerRule = 20
|
||||
e2bMaxRuleDomainLength = 128
|
||||
e2bMaxHeaderNameLength = 64
|
||||
e2bMaxHeaderValueLen = 2048
|
||||
)
|
||||
|
||||
// DenyAllIPv4 is the deny-all entry both providers expect in a deny list. E2B
|
||||
// calls it ALL_TRAFFIC in its error messages but accepts this CIDR (its own
|
||||
// SDK exports it as e2b.AllTraffic with this value).
|
||||
const DenyAllIPv4 = "0.0.0.0/0"
|
||||
|
||||
var (
|
||||
cubeAuditLevels = map[string]bool{"": true, "none": true, "metadata": true, "full": true}
|
||||
httpMethods = map[string]bool{
|
||||
"GET": true, "HEAD": true, "POST": true, "PUT": true, "PATCH": true,
|
||||
"DELETE": true, "CONNECT": true, "OPTIONS": true, "TRACE": true,
|
||||
}
|
||||
)
|
||||
|
||||
// ValidateSandboxNetworkPolicy rejects a policy the provider would refuse, or
|
||||
// would silently accept without doing what the admin meant. Errors are plain
|
||||
// values; the service layer wraps them as bad-request responses.
|
||||
func ValidateSandboxNetworkPolicy(cfg *TenantSandboxConfig) error {
|
||||
if cfg == nil || cfg.Network == nil {
|
||||
return nil
|
||||
}
|
||||
p := cfg.Network
|
||||
backend := strings.TrimSpace(strings.ToLower(cfg.SandboxType))
|
||||
|
||||
if backend == "docker" &&
|
||||
(len(p.AllowOut) > 0 || len(p.DenyOut) > 0 ||
|
||||
len(p.CubeRules) > 0 || len(p.E2BHostRules) > 0) {
|
||||
return errors.New(
|
||||
"docker 后端只能整体开关出网,无法按 IP、域名或 HTTP 规则放行;" +
|
||||
"请清空放行/拒绝列表,或改用 cube / e2b 后端")
|
||||
}
|
||||
|
||||
allowKeys := make(map[string]string, len(p.AllowOut))
|
||||
hasDomainAllow := false
|
||||
for _, target := range p.AllowOut {
|
||||
kind, key, err := classifyNetworkTarget(target, true)
|
||||
if err != nil {
|
||||
return fmt.Errorf("allow_out %q: %w", target, err)
|
||||
}
|
||||
if prior, seen := allowKeys[key]; seen {
|
||||
return fmt.Errorf("allow_out 中 %q 与 %q 是同一个目标,请只保留一条", prior, target)
|
||||
}
|
||||
allowKeys[key] = target
|
||||
if kind == targetDomain {
|
||||
hasDomainAllow = true
|
||||
}
|
||||
}
|
||||
|
||||
denyKeys := make(map[string]string, len(p.DenyOut))
|
||||
deniesEverything := p.DenyEgressByDefault
|
||||
for _, target := range p.DenyOut {
|
||||
kind, key, err := classifyNetworkTarget(target, false)
|
||||
if err != nil {
|
||||
return fmt.Errorf("deny_out %q: %w", target, err)
|
||||
}
|
||||
if kind == targetDomain {
|
||||
return fmt.Errorf(
|
||||
"deny_out 不支持域名(%q):拒绝判定只按目的 IP 匹配。"+
|
||||
"如需只放行少数域名,请启用「默认拒绝」并把它们写进 allow_out", target)
|
||||
}
|
||||
if prior, seen := denyKeys[key]; seen {
|
||||
return fmt.Errorf("deny_out 中 %q 与 %q 是同一个目标,请只保留一条", prior, target)
|
||||
}
|
||||
denyKeys[key] = target
|
||||
if key == DenyAllIPv4 {
|
||||
deniesEverything = true
|
||||
}
|
||||
}
|
||||
|
||||
if hasDomainAllow && !deniesEverything {
|
||||
return errors.New(
|
||||
"allow_out 里有域名时必须同时兜底拒绝其余流量:" +
|
||||
"启用「默认拒绝」,或在 deny_out 中加入 0.0.0.0/0。" +
|
||||
"否则未经 DNS 学习的目的 IP 仍会默认放行,白名单形同虚设")
|
||||
}
|
||||
|
||||
if err := validateCubeEgressRules(p.CubeRules); err != nil {
|
||||
return err
|
||||
}
|
||||
return validateE2BHostRules(p.E2BHostRules, allowKeys)
|
||||
}
|
||||
|
||||
// DenyOutCoversAllIPv4 reports whether a deny list blocks every IPv4
|
||||
// destination. That is the second of the two ways an admin can express the
|
||||
// deny-all fallback — the first being DenyEgressByDefault — and
|
||||
// ValidateSandboxNetworkPolicy treats them as equivalent, so every consumer
|
||||
// that asks "does this policy deny by default?" has to accept both or it will
|
||||
// misjudge a config the admin was allowed to save.
|
||||
//
|
||||
// It normalises through classifyNetworkTarget rather than comparing strings so
|
||||
// it cannot disagree with the validator about which entries count: any /0
|
||||
// collapses onto 0.0.0.0/0, and surrounding whitespace is ignored. Entries the
|
||||
// validator would reject are skipped here; rejecting them is its job.
|
||||
func DenyOutCoversAllIPv4(denyOut []string) bool {
|
||||
for _, target := range denyOut {
|
||||
kind, key, err := classifyNetworkTarget(target, false)
|
||||
if err != nil || kind != targetIP {
|
||||
continue
|
||||
}
|
||||
if key == DenyAllIPv4 {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// CanonicalizeDenyOut rewrites any IPv4 /0 onto DenyAllIPv4 so providers that
|
||||
// string-match 0.0.0.0/0 (E2B's ALL_TRAFFIC) see the same deny-all the
|
||||
// validator accepted. Other entries are copied as typed. Nil input stays nil.
|
||||
func CanonicalizeDenyOut(denyOut []string) []string {
|
||||
if denyOut == nil {
|
||||
return nil
|
||||
}
|
||||
out := make([]string, 0, len(denyOut))
|
||||
for _, target := range denyOut {
|
||||
kind, key, err := classifyNetworkTarget(target, false)
|
||||
if err == nil && kind == targetIP && key == DenyAllIPv4 {
|
||||
out = append(out, DenyAllIPv4)
|
||||
continue
|
||||
}
|
||||
out = append(out, target)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
type networkTargetKind int
|
||||
|
||||
const (
|
||||
targetIP networkTargetKind = iota
|
||||
targetDomain
|
||||
)
|
||||
|
||||
// classifyNetworkTarget normalises one allow/deny entry and reports whether it
|
||||
// is an address or a domain. key is the normalised form both providers dedupe
|
||||
// on: a bare IPv4 collapses onto its /32, a domain is lowercased with the
|
||||
// trailing dot removed.
|
||||
func classifyNetworkTarget(
|
||||
target string,
|
||||
allowWildcard bool,
|
||||
) (kind networkTargetKind, key string, err error) {
|
||||
trimmed := strings.TrimSpace(target)
|
||||
if trimmed == "" {
|
||||
return 0, "", errors.New("不能为空")
|
||||
}
|
||||
if strings.ContainsAny(trimmed, " \t") {
|
||||
return 0, "", errors.New("不能包含空格")
|
||||
}
|
||||
if ip := net.ParseIP(trimmed); ip != nil {
|
||||
if ip.To4() == nil {
|
||||
return 0, "", errors.New("暂不支持 IPv6")
|
||||
}
|
||||
return targetIP, ip.String() + "/32", nil
|
||||
}
|
||||
if _, network, cidrErr := net.ParseCIDR(trimmed); cidrErr == nil {
|
||||
if network.IP.To4() == nil {
|
||||
return 0, "", errors.New("暂不支持 IPv6 CIDR")
|
||||
}
|
||||
return targetIP, network.String(), nil
|
||||
}
|
||||
return classifyDomainTarget(trimmed, allowWildcard)
|
||||
}
|
||||
|
||||
func classifyDomainTarget(
|
||||
trimmed string,
|
||||
allowWildcard bool,
|
||||
) (networkTargetKind, string, error) {
|
||||
domain := strings.ToLower(strings.TrimSuffix(trimmed, "."))
|
||||
if strings.Contains(domain, ":") {
|
||||
return 0, "", errors.New("不能带端口")
|
||||
}
|
||||
wildcard := false
|
||||
if strings.HasPrefix(domain, "*.") {
|
||||
if !allowWildcard {
|
||||
return 0, "", errors.New("此处不支持通配域名")
|
||||
}
|
||||
wildcard = true
|
||||
domain = strings.TrimPrefix(domain, "*.")
|
||||
}
|
||||
if strings.Trim(domain, "0123456789.") == "" {
|
||||
return 0, "", errors.New("不是合法 IPv4 地址")
|
||||
}
|
||||
if domain == "" || strings.Contains(domain, "*") {
|
||||
return 0, "", errors.New("通配符只能是单层前缀,例如 *.example.com")
|
||||
}
|
||||
if strings.HasPrefix(domain, ".") || strings.HasSuffix(domain, ".") ||
|
||||
strings.Contains(domain, "..") {
|
||||
return 0, "", errors.New("不是合法域名")
|
||||
}
|
||||
labels := strings.Split(domain, ".")
|
||||
if len(labels) < 2 {
|
||||
return 0, "", errors.New("不是合法域名")
|
||||
}
|
||||
for _, label := range labels {
|
||||
if label == "" || len(label) > 63 {
|
||||
return 0, "", errors.New("不是合法域名")
|
||||
}
|
||||
for _, r := range label {
|
||||
isAlnum := (r >= 'a' && r <= 'z') || (r >= '0' && r <= '9')
|
||||
if !isAlnum && r != '-' {
|
||||
return 0, "", errors.New("不是合法域名")
|
||||
}
|
||||
}
|
||||
if strings.HasPrefix(label, "-") || strings.HasSuffix(label, "-") {
|
||||
return 0, "", errors.New("不是合法域名")
|
||||
}
|
||||
}
|
||||
key := domain
|
||||
if wildcard {
|
||||
key = "*." + domain
|
||||
}
|
||||
return targetDomain, key, nil
|
||||
}
|
||||
|
||||
func validateCubeEgressRules(rules []CubeEgressRule) error {
|
||||
names := make(map[string]bool, len(rules))
|
||||
for _, rule := range rules {
|
||||
name := strings.TrimSpace(rule.Name)
|
||||
if name == "" {
|
||||
return errors.New("每条 Cube HTTP 规则都需要 name,用于审计与模板合并")
|
||||
}
|
||||
if names[name] {
|
||||
return fmt.Errorf("cube HTTP 规则 name %q 重复", name)
|
||||
}
|
||||
names[name] = true
|
||||
|
||||
if strings.TrimSpace(rule.Host) == "" && strings.TrimSpace(rule.SNI) == "" {
|
||||
return fmt.Errorf(
|
||||
"cube HTTP 规则 %q 必须填 host 或 sni:网络层只从这两个字段提取放行目标,"+
|
||||
"只写 method / path 的规则永远到不了 CubeEgress", name)
|
||||
}
|
||||
if host := strings.TrimSpace(rule.Host); host != "" {
|
||||
if _, _, err := classifyNetworkTarget(hostWithoutPort(host), true); err != nil {
|
||||
return fmt.Errorf("cube HTTP 规则 %q 的 host %q: %w", name, rule.Host, err)
|
||||
}
|
||||
}
|
||||
if sni := strings.TrimSpace(rule.SNI); sni != "" {
|
||||
kind, _, err := classifyNetworkTarget(sni, true)
|
||||
if err != nil {
|
||||
return fmt.Errorf("cube HTTP 规则 %q 的 sni %q: %w", name, rule.SNI, err)
|
||||
}
|
||||
if kind != targetDomain {
|
||||
return fmt.Errorf("cube HTTP 规则 %q 的 sni 只能是域名,不能是 IP", name)
|
||||
}
|
||||
}
|
||||
switch strings.ToLower(strings.TrimSpace(rule.Scheme)) {
|
||||
case "", "http", "https":
|
||||
default:
|
||||
return fmt.Errorf("cube HTTP 规则 %q 的 scheme 只能是 http 或 https", name)
|
||||
}
|
||||
if !cubeAuditLevels[strings.ToLower(strings.TrimSpace(rule.Audit))] {
|
||||
return fmt.Errorf("cube HTTP 规则 %q 的 audit 只能是 none、metadata 或 full", name)
|
||||
}
|
||||
for _, method := range rule.Methods {
|
||||
if !httpMethods[strings.ToUpper(strings.TrimSpace(method))] {
|
||||
return fmt.Errorf("cube HTTP 规则 %q 的 method %q 不是标准 HTTP 方法", name, method)
|
||||
}
|
||||
}
|
||||
injectHeaders := make(map[string]bool, len(rule.Inject))
|
||||
for _, inject := range rule.Inject {
|
||||
header := strings.TrimSpace(inject.Header)
|
||||
if header == "" {
|
||||
return fmt.Errorf("cube HTTP 规则 %q 的注入 header 名不能为空", name)
|
||||
}
|
||||
if err := validateHTTPHeaderName(header); err != nil {
|
||||
return fmt.Errorf("规则 %q 的注入 header 名 %q: %w", name, header, err)
|
||||
}
|
||||
if injectHeaders[header] {
|
||||
return fmt.Errorf("cube HTTP 规则 %q 的注入 header 名 %q 重复", name, header)
|
||||
}
|
||||
injectHeaders[header] = true
|
||||
if err := validateHTTPHeaderValue(inject.Secret); err != nil {
|
||||
return fmt.Errorf("规则 %q 的注入 header %q 的值: %w", name, header, err)
|
||||
}
|
||||
if err := validateHTTPHeaderValue(inject.Format); err != nil {
|
||||
return fmt.Errorf("规则 %q 的注入 header %q 的 format: %w", name, header, err)
|
||||
}
|
||||
if rule.Deny && inject.Secret != "" {
|
||||
return fmt.Errorf("cube HTTP 规则 %q 是拒绝规则,注入 header 不会生效", name)
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func hostWithoutPort(host string) string {
|
||||
if h, _, err := net.SplitHostPort(host); err == nil {
|
||||
return h
|
||||
}
|
||||
return host
|
||||
}
|
||||
|
||||
func validateE2BHostRules(rules []E2BHostRule, allowKeys map[string]string) error {
|
||||
if len(rules) > e2bMaxRuleDomains {
|
||||
return fmt.Errorf("e2b 每个沙箱最多 %d 个 host 规则域名", e2bMaxRuleDomains)
|
||||
}
|
||||
seen := make(map[string]bool, len(rules))
|
||||
for _, rule := range rules {
|
||||
host := strings.TrimSpace(rule.Host)
|
||||
if host == "" {
|
||||
return errors.New("e2b host 规则的 host 不能为空")
|
||||
}
|
||||
if len(host) > e2bMaxRuleDomainLength {
|
||||
return fmt.Errorf("e2b host 规则的 host %q 超过 %d 字符", host, e2bMaxRuleDomainLength)
|
||||
}
|
||||
kind, key, err := classifyNetworkTarget(host, true)
|
||||
if err != nil {
|
||||
return fmt.Errorf("e2b host 规则的 host %q: %w", host, err)
|
||||
}
|
||||
if kind != targetDomain {
|
||||
return fmt.Errorf("e2b host 规则的 host %q 只能是域名", host)
|
||||
}
|
||||
if seen[key] {
|
||||
return fmt.Errorf("e2b host 规则 %q 重复:每个域名只能有一条规则", host)
|
||||
}
|
||||
seen[key] = true
|
||||
|
||||
if !allowListCovers(allowKeys, key) {
|
||||
return fmt.Errorf(
|
||||
"e2b host 规则的 host %q 必须同时出现在 allow_out 中:"+
|
||||
"规则本身只做 header 注入,不授权出网", host)
|
||||
}
|
||||
if len(rule.Headers) > e2bMaxHeadersPerRule {
|
||||
return fmt.Errorf("e2b host 规则 %q 最多 %d 个 header", host, e2bMaxHeadersPerRule)
|
||||
}
|
||||
for name, value := range rule.Headers {
|
||||
if strings.TrimSpace(name) == "" {
|
||||
return fmt.Errorf("e2b host 规则 %q 的 header 名不能为空", host)
|
||||
}
|
||||
if err := validateHTTPHeaderName(name); err != nil {
|
||||
return fmt.Errorf("host 规则 %q 的 header 名 %q: %w", host, name, err)
|
||||
}
|
||||
if len(name) > e2bMaxHeaderNameLength {
|
||||
return fmt.Errorf("e2b host 规则 %q 的 header 名超过 %d 字符",
|
||||
host, e2bMaxHeaderNameLength)
|
||||
}
|
||||
if err := validateHTTPHeaderValue(value); err != nil {
|
||||
return fmt.Errorf("host 规则 %q 的 header %q 的值: %w", host, name, err)
|
||||
}
|
||||
if len(value) > e2bMaxHeaderValueLen {
|
||||
return fmt.Errorf("e2b host 规则 %q 的 header 值超过 %d 字符",
|
||||
host, e2bMaxHeaderValueLen)
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// validateHTTPHeaderName rejects names that cannot be a single HTTP field
|
||||
// name. CR/LF would let an injected header smuggle a second field through
|
||||
// CubeEgress / E2B request transforms.
|
||||
func validateHTTPHeaderName(name string) error {
|
||||
if name == "" {
|
||||
return errors.New("不能为空")
|
||||
}
|
||||
for _, r := range name {
|
||||
if !isHTTPTokenChar(r) {
|
||||
return errors.New("不是合法 HTTP header 名")
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// validateHTTPHeaderValue rejects CR, LF and NUL, which would terminate the
|
||||
// field and let the rest of the string become a smuggled header or request.
|
||||
// Empty is allowed (unset / placeholder).
|
||||
func validateHTTPHeaderValue(value string) error {
|
||||
if strings.ContainsAny(value, "\r\n\x00") {
|
||||
return errors.New("不能包含换行或 NUL")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func isHTTPTokenChar(r rune) bool {
|
||||
if r <= 32 || r >= 127 {
|
||||
return false
|
||||
}
|
||||
switch r {
|
||||
case '(', ')', '<', '>', '@', ',', ';', ':', '\\', '"', '/', '[', ']', '?', '=', '{', '}':
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// allowListCovers reports whether an allow entry authorises host: either the
|
||||
// exact name, or a wildcard whose suffix matches. Mirrors both providers'
|
||||
// rule that "*.example.com" covers subdomains but not the apex.
|
||||
func allowListCovers(allowKeys map[string]string, host string) bool {
|
||||
if _, ok := allowKeys[host]; ok {
|
||||
return true
|
||||
}
|
||||
for key := range allowKeys {
|
||||
suffix, ok := strings.CutPrefix(key, "*.")
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
if strings.HasSuffix(host, "."+suffix) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
|
@ -0,0 +1,486 @@
|
|||
package types
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// The zero value must mean "egress open, inbound closed", which is what lets a
|
||||
// config with no network block behave identically to one saved with defaults.
|
||||
func TestSandboxNetworkPolicyZeroValueIsTheDefault(t *testing.T) {
|
||||
var p SandboxNetworkPolicy
|
||||
|
||||
require.False(t, p.DenyEgressByDefault, "egress must default to allowed")
|
||||
require.False(t, p.AllowPublicInbound, "inbound must default to closed")
|
||||
|
||||
encoded, err := json.Marshal(&p)
|
||||
require.NoError(t, err)
|
||||
require.JSONEq(t, `{}`, string(encoded),
|
||||
"a default policy must serialize empty so it is indistinguishable from nil")
|
||||
}
|
||||
|
||||
func TestSandboxNetworkPolicyCloneWithSecretsTransformsOnlyCredentials(t *testing.T) {
|
||||
policy := &SandboxNetworkPolicy{
|
||||
DenyEgressByDefault: true,
|
||||
AllowOut: []string{"api.example.com"},
|
||||
DenyOut: []string{"0.0.0.0/0"},
|
||||
CubeRules: []CubeEgressRule{{
|
||||
Name: "allow-api",
|
||||
Scheme: "https",
|
||||
SNI: "api.example.com",
|
||||
Host: "api.example.com",
|
||||
Inject: []CubeHeaderInject{{
|
||||
Header: "Authorization",
|
||||
Secret: "real-token",
|
||||
Format: "Bearer ${SECRET}",
|
||||
}},
|
||||
}},
|
||||
E2BHostRules: []E2BHostRule{{
|
||||
Host: "api.example.com",
|
||||
Headers: map[string]string{"X-Key": "real-key"},
|
||||
}},
|
||||
}
|
||||
|
||||
out := policy.CloneWithSecrets(func(string) string { return "TRANSFORMED" })
|
||||
|
||||
require.Equal(t, "TRANSFORMED", out.CubeRules[0].Inject[0].Secret)
|
||||
require.Equal(t, "TRANSFORMED", out.E2BHostRules[0].Headers["X-Key"])
|
||||
// Everything an operator needs to read stays legible.
|
||||
require.Equal(t, "Authorization", out.CubeRules[0].Inject[0].Header)
|
||||
require.Equal(t, "Bearer ${SECRET}", out.CubeRules[0].Inject[0].Format)
|
||||
require.Equal(t, "X-Key", firstKey(out.E2BHostRules[0].Headers))
|
||||
require.Equal(t, []string{"api.example.com"}, out.AllowOut)
|
||||
require.True(t, out.DenyEgressByDefault)
|
||||
|
||||
// The receiver must not be mutated: Value() is called on a live row.
|
||||
require.Equal(t, "real-token", policy.CubeRules[0].Inject[0].Secret)
|
||||
require.Equal(t, "real-key", policy.E2BHostRules[0].Headers["X-Key"])
|
||||
|
||||
// And the copy must be deep, or a later mutation would reach back.
|
||||
out.AllowOut[0] = "mutated"
|
||||
require.Equal(t, "api.example.com", policy.AllowOut[0])
|
||||
}
|
||||
|
||||
func TestSandboxNetworkPolicyCloneWithSecretsNil(t *testing.T) {
|
||||
var p *SandboxNetworkPolicy
|
||||
require.Nil(t, p.CloneWithSecrets(func(s string) string { return s }))
|
||||
}
|
||||
|
||||
func TestSandboxNetworkPolicyCloneWithSecretsDeepCopiesEmptyCollections(t *testing.T) {
|
||||
policy := &SandboxNetworkPolicy{
|
||||
CubeRules: []CubeEgressRule{{
|
||||
Inject: make([]CubeHeaderInject, 0, 1),
|
||||
}},
|
||||
E2BHostRules: []E2BHostRule{{
|
||||
Headers: map[string]string{},
|
||||
}},
|
||||
}
|
||||
|
||||
out := policy.CloneWithSecrets(func(s string) string { return s })
|
||||
out.CubeRules[0].Inject = append(out.CubeRules[0].Inject, CubeHeaderInject{Header: "X-Clone"})
|
||||
out.E2BHostRules[0].Headers["X-Clone"] = "value"
|
||||
|
||||
policy.CubeRules[0].Inject = append(policy.CubeRules[0].Inject, CubeHeaderInject{Header: "X-Original"})
|
||||
require.Equal(t, "X-Clone", out.CubeRules[0].Inject[0].Header)
|
||||
require.Empty(t, policy.E2BHostRules[0].Headers)
|
||||
|
||||
policy = &SandboxNetworkPolicy{
|
||||
CubeRules: make([]CubeEgressRule, 0, 1),
|
||||
E2BHostRules: make([]E2BHostRule, 0, 1),
|
||||
}
|
||||
out = policy.CloneWithSecrets(func(s string) string { return s })
|
||||
out.CubeRules = append(out.CubeRules, CubeEgressRule{Name: "clone"})
|
||||
out.E2BHostRules = append(out.E2BHostRules, E2BHostRule{Host: "clone.example.com"})
|
||||
policy.CubeRules = append(policy.CubeRules, CubeEgressRule{Name: "original"})
|
||||
policy.E2BHostRules = append(policy.E2BHostRules, E2BHostRule{Host: "original.example.com"})
|
||||
require.Equal(t, "clone", out.CubeRules[0].Name)
|
||||
require.Equal(t, "clone.example.com", out.E2BHostRules[0].Host)
|
||||
}
|
||||
|
||||
func firstKey(m map[string]string) string {
|
||||
for k := range m {
|
||||
return k
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func TestValidateSandboxNetworkPolicyAcceptsDefaults(t *testing.T) {
|
||||
require.NoError(t, ValidateSandboxNetworkPolicy(nil))
|
||||
require.NoError(t, ValidateSandboxNetworkPolicy(&TenantSandboxConfig{SandboxType: "cube"}))
|
||||
require.NoError(t, ValidateSandboxNetworkPolicy(&TenantSandboxConfig{
|
||||
SandboxType: "cube",
|
||||
Network: &SandboxNetworkPolicy{},
|
||||
}))
|
||||
}
|
||||
|
||||
func TestValidateSandboxNetworkPolicyDomainAllowNeedsDenyAll(t *testing.T) {
|
||||
// A domain allow-list without a deny-all is misleading rather than strict:
|
||||
// destinations the sandbox never resolved through DNS stay reachable.
|
||||
err := ValidateSandboxNetworkPolicy(&TenantSandboxConfig{
|
||||
SandboxType: "cube",
|
||||
Network: &SandboxNetworkPolicy{AllowOut: []string{"api.example.com"}},
|
||||
})
|
||||
require.Error(t, err)
|
||||
require.Contains(t, err.Error(), "0.0.0.0/0")
|
||||
|
||||
// Either of the two ways to express deny-all is enough.
|
||||
require.NoError(t, ValidateSandboxNetworkPolicy(&TenantSandboxConfig{
|
||||
SandboxType: "cube",
|
||||
Network: &SandboxNetworkPolicy{
|
||||
DenyEgressByDefault: true,
|
||||
AllowOut: []string{"api.example.com"},
|
||||
},
|
||||
}))
|
||||
require.NoError(t, ValidateSandboxNetworkPolicy(&TenantSandboxConfig{
|
||||
SandboxType: "cube",
|
||||
Network: &SandboxNetworkPolicy{
|
||||
AllowOut: []string{"api.example.com"},
|
||||
DenyOut: []string{"0.0.0.0/0"},
|
||||
},
|
||||
}))
|
||||
// IP-only allow lists never need the fallback.
|
||||
require.NoError(t, ValidateSandboxNetworkPolicy(&TenantSandboxConfig{
|
||||
SandboxType: "cube",
|
||||
Network: &SandboxNetworkPolicy{AllowOut: []string{"1.1.1.1", "203.0.113.0/24"}},
|
||||
}))
|
||||
}
|
||||
|
||||
// DenyOutCoversAllIPv4 exists so every consumer of the policy agrees with the
|
||||
// validator about what "deny all" looks like. It must therefore use the same
|
||||
// normalisation the validator does, not a string compare: net.ParseCIDR
|
||||
// collapses any /0 onto 0.0.0.0/0, and the validator trims whitespace.
|
||||
func TestDenyOutCoversAllIPv4MatchesValidatorNormalisation(t *testing.T) {
|
||||
require.True(t, DenyOutCoversAllIPv4([]string{"0.0.0.0/0"}))
|
||||
require.True(t, DenyOutCoversAllIPv4([]string{" 0.0.0.0/0 "}))
|
||||
require.True(t, DenyOutCoversAllIPv4([]string{"1.2.3.4/0"}))
|
||||
require.True(t, DenyOutCoversAllIPv4([]string{"10.0.0.0/8", "0.0.0.0/0"}))
|
||||
|
||||
require.False(t, DenyOutCoversAllIPv4(nil))
|
||||
require.False(t, DenyOutCoversAllIPv4([]string{}))
|
||||
require.False(t, DenyOutCoversAllIPv4([]string{"10.0.0.0/8"}))
|
||||
require.False(t, DenyOutCoversAllIPv4([]string{"0.0.0.0/32"}))
|
||||
require.False(t, DenyOutCoversAllIPv4([]string{"0.0.0.0"}))
|
||||
// Unparseable entries are the validator's problem, not this predicate's.
|
||||
require.False(t, DenyOutCoversAllIPv4([]string{"not a cidr"}))
|
||||
|
||||
require.Equal(t, []string{DenyAllIPv4}, CanonicalizeDenyOut([]string{"1.2.3.4/0"}))
|
||||
require.Equal(t, []string{DenyAllIPv4}, CanonicalizeDenyOut([]string{" 0.0.0.0/0 "}))
|
||||
require.Equal(t, []string{"10.0.0.0/8", DenyAllIPv4}, CanonicalizeDenyOut([]string{"10.0.0.0/8", "1.2.3.4/0"}))
|
||||
require.Nil(t, CanonicalizeDenyOut(nil))
|
||||
|
||||
// The two spellings the validator accepts must agree with the predicate.
|
||||
for _, policy := range []*SandboxNetworkPolicy{
|
||||
{AllowOut: []string{"api.example.com"}, DenyOut: []string{"0.0.0.0/0"}},
|
||||
{AllowOut: []string{"api.example.com"}, DenyOut: []string{"1.2.3.4/0"}},
|
||||
} {
|
||||
require.NoError(t, ValidateSandboxNetworkPolicy(&TenantSandboxConfig{
|
||||
SandboxType: "cube",
|
||||
Network: policy,
|
||||
}))
|
||||
require.True(t, DenyOutCoversAllIPv4(policy.DenyOut))
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateSandboxNetworkPolicyRejectsDomainInDenyOut(t *testing.T) {
|
||||
err := ValidateSandboxNetworkPolicy(&TenantSandboxConfig{
|
||||
SandboxType: "cube",
|
||||
Network: &SandboxNetworkPolicy{DenyOut: []string{"api.example.com"}},
|
||||
})
|
||||
require.Error(t, err)
|
||||
require.Contains(t, err.Error(), "deny_out")
|
||||
}
|
||||
|
||||
func TestValidateSandboxNetworkPolicyRejectsBadTargets(t *testing.T) {
|
||||
for _, target := range []string{
|
||||
"*", ".example.com", "*.*.example.com",
|
||||
"api.*.example.com", "example.com:443", "999.999.999.999", "*.999.999", "",
|
||||
} {
|
||||
err := ValidateSandboxNetworkPolicy(&TenantSandboxConfig{
|
||||
SandboxType: "cube",
|
||||
Network: &SandboxNetworkPolicy{
|
||||
DenyEgressByDefault: true,
|
||||
AllowOut: []string{target},
|
||||
},
|
||||
})
|
||||
require.Error(t, err, "target %q must be rejected", target)
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateSandboxNetworkPolicyCubeRules(t *testing.T) {
|
||||
valid := CubeEgressRule{Name: "allow-api", Scheme: "https", SNI: "api.example.com"}
|
||||
require.NoError(t, ValidateSandboxNetworkPolicy(&TenantSandboxConfig{
|
||||
SandboxType: "cube",
|
||||
Network: &SandboxNetworkPolicy{CubeRules: []CubeEgressRule{valid}},
|
||||
}))
|
||||
|
||||
noName := valid
|
||||
noName.Name = ""
|
||||
requireRuleRejected(t, noName, "name")
|
||||
|
||||
// CubeVS extracts network targets only from match.sni / match.host, so a
|
||||
// rule with neither never reaches CubeEgress at all.
|
||||
noTarget := valid
|
||||
noTarget.SNI = ""
|
||||
noTarget.Path = "/v1/*"
|
||||
requireRuleRejected(t, noTarget, "host")
|
||||
|
||||
badScheme := valid
|
||||
badScheme.Scheme = "ftp"
|
||||
requireRuleRejected(t, badScheme, "scheme")
|
||||
|
||||
badAudit := valid
|
||||
badAudit.Audit = "verbose"
|
||||
requireRuleRejected(t, badAudit, "audit")
|
||||
|
||||
badMethod := valid
|
||||
badMethod.Methods = []string{"FETCH"}
|
||||
requireRuleRejected(t, badMethod, "method")
|
||||
|
||||
longHeader := valid
|
||||
longHeader.Inject = []CubeHeaderInject{{
|
||||
Header: strings.Repeat("h", e2bMaxHeaderNameLength+1),
|
||||
Secret: "secret",
|
||||
}}
|
||||
require.NoError(t, ValidateSandboxNetworkPolicy(&TenantSandboxConfig{
|
||||
SandboxType: "cube",
|
||||
Network: &SandboxNetworkPolicy{CubeRules: []CubeEgressRule{longHeader}},
|
||||
}))
|
||||
}
|
||||
|
||||
func requireRuleRejected(t *testing.T, rule CubeEgressRule, wantSubstring string) {
|
||||
t.Helper()
|
||||
err := ValidateSandboxNetworkPolicy(&TenantSandboxConfig{
|
||||
SandboxType: "cube",
|
||||
Network: &SandboxNetworkPolicy{CubeRules: []CubeEgressRule{rule}},
|
||||
})
|
||||
require.Error(t, err)
|
||||
require.Contains(t, err.Error(), wantSubstring)
|
||||
}
|
||||
|
||||
func TestValidateSandboxNetworkPolicyRejectsDuplicateInjectHeaders(t *testing.T) {
|
||||
err := ValidateSandboxNetworkPolicy(&TenantSandboxConfig{
|
||||
SandboxType: "cube",
|
||||
Network: &SandboxNetworkPolicy{CubeRules: []CubeEgressRule{{
|
||||
Name: "allow-api",
|
||||
SNI: "api.example.com",
|
||||
Inject: []CubeHeaderInject{
|
||||
{Header: "Authorization", Secret: "first"},
|
||||
{Header: "Authorization", Secret: "second"},
|
||||
},
|
||||
}}},
|
||||
})
|
||||
require.Error(t, err)
|
||||
require.Contains(t, err.Error(), "Authorization")
|
||||
require.Contains(t, err.Error(), "重复")
|
||||
}
|
||||
|
||||
func TestValidateSandboxNetworkPolicyRejectsInjectedHeaderCRLF(t *testing.T) {
|
||||
valid := CubeEgressRule{Name: "allow-api", SNI: "api.example.com"}
|
||||
|
||||
crlfName := valid
|
||||
crlfName.Inject = []CubeHeaderInject{{Header: "X-Key\r\nX-Smuggled", Secret: "v"}}
|
||||
requireRuleRejected(t, crlfName, "header 名")
|
||||
|
||||
spaceName := valid
|
||||
spaceName.Inject = []CubeHeaderInject{{Header: "X Key", Secret: "v"}}
|
||||
requireRuleRejected(t, spaceName, "header 名")
|
||||
|
||||
crlfValue := valid
|
||||
crlfValue.Inject = []CubeHeaderInject{{Header: "Authorization", Secret: "tok\r\nX-Smuggled: 1"}}
|
||||
requireRuleRejected(t, crlfValue, "不能包含换行")
|
||||
|
||||
crlfFormat := valid
|
||||
crlfFormat.Inject = []CubeHeaderInject{{
|
||||
Header: "Authorization", Secret: "tok", Format: "Bearer ${SECRET}\r\nX-Smuggled: 1",
|
||||
}}
|
||||
requireRuleRejected(t, crlfFormat, "format")
|
||||
|
||||
err := ValidateSandboxNetworkPolicy(&TenantSandboxConfig{
|
||||
SandboxType: "e2b",
|
||||
Network: &SandboxNetworkPolicy{
|
||||
DenyEgressByDefault: true,
|
||||
AllowOut: []string{"api.example.com"},
|
||||
E2BHostRules: []E2BHostRule{{
|
||||
Host: "api.example.com",
|
||||
Headers: map[string]string{"X-Key\nEvil": "v"},
|
||||
}},
|
||||
},
|
||||
})
|
||||
require.Error(t, err)
|
||||
require.Contains(t, err.Error(), "header 名")
|
||||
}
|
||||
|
||||
func TestValidateSandboxNetworkPolicyE2BHostRuleNeedsAllowOut(t *testing.T) {
|
||||
// A transform rule grants no egress on its own.
|
||||
err := ValidateSandboxNetworkPolicy(&TenantSandboxConfig{
|
||||
SandboxType: "e2b",
|
||||
Network: &SandboxNetworkPolicy{
|
||||
DenyEgressByDefault: true,
|
||||
E2BHostRules: []E2BHostRule{{
|
||||
Host: "api.example.com",
|
||||
Headers: map[string]string{"X-Key": "v"},
|
||||
}},
|
||||
},
|
||||
})
|
||||
require.Error(t, err)
|
||||
require.Contains(t, err.Error(), "allow_out")
|
||||
|
||||
// A wildcard allow covers its subdomains.
|
||||
require.NoError(t, ValidateSandboxNetworkPolicy(&TenantSandboxConfig{
|
||||
SandboxType: "e2b",
|
||||
Network: &SandboxNetworkPolicy{
|
||||
DenyEgressByDefault: true,
|
||||
AllowOut: []string{"*.example.com"},
|
||||
E2BHostRules: []E2BHostRule{{
|
||||
Host: "api.example.com",
|
||||
Headers: map[string]string{"X-Key": "v"},
|
||||
}},
|
||||
},
|
||||
}))
|
||||
|
||||
for _, host := range []string{"example.com", "evilexample.com"} {
|
||||
err = ValidateSandboxNetworkPolicy(&TenantSandboxConfig{
|
||||
SandboxType: "e2b",
|
||||
Network: &SandboxNetworkPolicy{
|
||||
DenyEgressByDefault: true,
|
||||
AllowOut: []string{"*.example.com"},
|
||||
E2BHostRules: []E2BHostRule{{Host: host}},
|
||||
},
|
||||
})
|
||||
require.Error(t, err)
|
||||
require.Contains(t, err.Error(), "allow_out")
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateSandboxNetworkPolicyE2BLimits(t *testing.T) {
|
||||
headers := make(map[string]string, 21)
|
||||
for i := 0; i < 21; i++ {
|
||||
headers["X-Header-"+string(rune('a'+i))] = "v"
|
||||
}
|
||||
err := ValidateSandboxNetworkPolicy(&TenantSandboxConfig{
|
||||
SandboxType: "e2b",
|
||||
Network: &SandboxNetworkPolicy{
|
||||
DenyEgressByDefault: true,
|
||||
AllowOut: []string{"api.example.com"},
|
||||
E2BHostRules: []E2BHostRule{{Host: "api.example.com", Headers: headers}},
|
||||
},
|
||||
})
|
||||
require.Error(t, err)
|
||||
require.Contains(t, err.Error(), "最多 20 个 header")
|
||||
|
||||
domains := make([]string, e2bMaxRuleDomains+1)
|
||||
rules := make([]E2BHostRule, e2bMaxRuleDomains+1)
|
||||
for i := range domains {
|
||||
domains[i] = string(rune('a'+i)) + ".example.com"
|
||||
rules[i] = E2BHostRule{Host: domains[i]}
|
||||
}
|
||||
err = ValidateSandboxNetworkPolicy(&TenantSandboxConfig{
|
||||
SandboxType: "e2b",
|
||||
Network: &SandboxNetworkPolicy{
|
||||
DenyEgressByDefault: true,
|
||||
AllowOut: domains,
|
||||
E2BHostRules: rules,
|
||||
},
|
||||
})
|
||||
require.Error(t, err)
|
||||
require.Contains(t, err.Error(), "最多 10 个 host 规则域名")
|
||||
|
||||
longHost := strings.Repeat("a", 63) + "." + strings.Repeat("b", 63) + ".com"
|
||||
err = ValidateSandboxNetworkPolicy(&TenantSandboxConfig{
|
||||
SandboxType: "e2b",
|
||||
Network: &SandboxNetworkPolicy{
|
||||
DenyEgressByDefault: true,
|
||||
E2BHostRules: []E2BHostRule{{Host: longHost}},
|
||||
},
|
||||
})
|
||||
require.Error(t, err)
|
||||
require.Contains(t, err.Error(), "超过 128 字符")
|
||||
|
||||
for _, tc := range []struct {
|
||||
name, value, want string
|
||||
}{
|
||||
{strings.Repeat("h", e2bMaxHeaderNameLength+1), "v", "header 名超过 64 字符"},
|
||||
{"X-Key", strings.Repeat("v", e2bMaxHeaderValueLen+1), "header 值超过 2048 字符"},
|
||||
} {
|
||||
err = ValidateSandboxNetworkPolicy(&TenantSandboxConfig{
|
||||
SandboxType: "e2b",
|
||||
Network: &SandboxNetworkPolicy{
|
||||
DenyEgressByDefault: true,
|
||||
AllowOut: []string{"api.example.com"},
|
||||
E2BHostRules: []E2BHostRule{{
|
||||
Host: "api.example.com",
|
||||
Headers: map[string]string{tc.name: tc.value},
|
||||
}},
|
||||
},
|
||||
})
|
||||
require.Error(t, err)
|
||||
require.Contains(t, err.Error(), tc.want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateSandboxNetworkPolicyRejectsDuplicateRules(t *testing.T) {
|
||||
err := ValidateSandboxNetworkPolicy(&TenantSandboxConfig{
|
||||
SandboxType: "e2b",
|
||||
Network: &SandboxNetworkPolicy{
|
||||
DenyEgressByDefault: true,
|
||||
AllowOut: []string{"api.example.com"},
|
||||
E2BHostRules: []E2BHostRule{
|
||||
{Host: "api.example.com"},
|
||||
{Host: "api.example.com"},
|
||||
},
|
||||
},
|
||||
})
|
||||
require.Error(t, err)
|
||||
require.Contains(t, err.Error(), "e2b host 规则")
|
||||
require.Contains(t, err.Error(), "重复")
|
||||
|
||||
err = ValidateSandboxNetworkPolicy(&TenantSandboxConfig{
|
||||
SandboxType: "cube",
|
||||
Network: &SandboxNetworkPolicy{CubeRules: []CubeEgressRule{
|
||||
{Name: "allow-api", SNI: "api.example.com"},
|
||||
{Name: "allow-api", SNI: "other.example.com"},
|
||||
}},
|
||||
})
|
||||
require.Error(t, err)
|
||||
require.Contains(t, err.Error(), `cube HTTP 规则 name "allow-api" 重复`)
|
||||
}
|
||||
|
||||
func TestValidateSandboxNetworkPolicyDockerRejectsFineGrained(t *testing.T) {
|
||||
err := ValidateSandboxNetworkPolicy(&TenantSandboxConfig{
|
||||
SandboxType: "docker",
|
||||
Network: &SandboxNetworkPolicy{AllowOut: []string{"1.1.1.1"}},
|
||||
})
|
||||
require.Error(t, err)
|
||||
require.Contains(t, err.Error(), "docker")
|
||||
|
||||
// The overall switches remain meaningful for Docker.
|
||||
require.NoError(t, ValidateSandboxNetworkPolicy(&TenantSandboxConfig{
|
||||
SandboxType: "docker",
|
||||
Network: &SandboxNetworkPolicy{DenyEgressByDefault: true},
|
||||
}))
|
||||
}
|
||||
|
||||
func TestValidateSandboxNetworkPolicyRejectsDuplicateTargets(t *testing.T) {
|
||||
// Cube normalises map keys, so these two are one entry; accepting both
|
||||
// would let an admin believe they configured two.
|
||||
err := ValidateSandboxNetworkPolicy(&TenantSandboxConfig{
|
||||
SandboxType: "cube",
|
||||
Network: &SandboxNetworkPolicy{
|
||||
AllowOut: []string{"198.51.100.1", "198.51.100.1/32"},
|
||||
},
|
||||
})
|
||||
require.Error(t, err)
|
||||
require.Contains(t, err.Error(), "198.51.100.1")
|
||||
|
||||
err = ValidateSandboxNetworkPolicy(&TenantSandboxConfig{
|
||||
SandboxType: "cube",
|
||||
Network: &SandboxNetworkPolicy{
|
||||
DenyEgressByDefault: true,
|
||||
AllowOut: []string{"API.Example.com.", "api.example.com"},
|
||||
},
|
||||
})
|
||||
require.Error(t, err)
|
||||
}
|
||||
|
|
@ -664,6 +664,12 @@ type TenantSandboxConfig struct {
|
|||
// afterwards boot the new snapshot.
|
||||
SkillRollout string `json:"skill_rollout,omitempty"`
|
||||
|
||||
// Network is the outbound/inbound network policy applied to every sandbox
|
||||
// created from this config — chat sessions, skill installs and deep
|
||||
// connectivity probes alike. nil and the zero value mean the same thing:
|
||||
// outbound egress allowed, inbound public access closed.
|
||||
Network *SandboxNetworkPolicy `json:"network,omitempty"`
|
||||
|
||||
// ── 后端专属配置(同一时刻只有一个生效,由 SandboxType 决定)───
|
||||
|
||||
Cube *CubeSandboxConfig `json:"cube,omitempty"`
|
||||
|
|
@ -842,10 +848,11 @@ type SkillImageConfig struct {
|
|||
}
|
||||
|
||||
// Value implements the driver.Valuer interface. Every secret-bearing field
|
||||
// (Cube.APIKey, E2B.APIKey and all EnvVars values) is encrypted before
|
||||
// persisting. EnvVars are included because environment variables routinely
|
||||
// carry credentials, and their values are handed to tenant scripts verbatim.
|
||||
// The receiver is never mutated: nested structs and the map are copied first.
|
||||
// (Cube.APIKey, E2B.APIKey, all EnvVars values, and injected header values) is
|
||||
// encrypted before persisting. EnvVars are included because environment
|
||||
// variables routinely carry credentials, and their values are handed to tenant
|
||||
// scripts verbatim. The receiver is never mutated: nested structs and the map
|
||||
// are copied first.
|
||||
func (c *TenantSandboxConfig) Value() (driver.Value, error) {
|
||||
if c == nil {
|
||||
return nil, nil
|
||||
|
|
@ -882,6 +889,11 @@ func (c *TenantSandboxConfig) Value() (driver.Value, error) {
|
|||
}
|
||||
cp.EnvVars = envVars
|
||||
}
|
||||
// Injected headers are the sandbox-side way to call an API without the
|
||||
// credential ever entering the sandbox, so their values are secrets.
|
||||
if c.Network != nil {
|
||||
cp.Network = c.Network.CloneWithSecrets(encrypt)
|
||||
}
|
||||
|
||||
return json.Marshal(&cp)
|
||||
}
|
||||
|
|
@ -923,6 +935,13 @@ func (c *TenantSandboxConfig) Scan(value interface{}) error {
|
|||
for name, stored := range c.EnvVars {
|
||||
c.EnvVars[name] = decrypt(stored, "env_vars."+name)
|
||||
}
|
||||
if c.Network != nil {
|
||||
// CloneWithSecrets has no rule/header context, so rotated-key failures
|
||||
// share one label rather than identifying the individual credential.
|
||||
c.Network = c.Network.CloneWithSecrets(func(stored string) string {
|
||||
return decrypt(stored, "network.injected_header")
|
||||
})
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in New Issue