WeKnora/internal/handler/sandbox_check_test.go

138 lines
5.0 KiB
Go
Raw Normal View History

feat(sandbox): 沙箱后端改为按空间配置,并补齐 E2B 模板与检测诊断 沙箱的后端类型、凭据、模板、超时和私网访问策略此前分散在部署级 WEKNORA_SANDBOX_* 环境变量里,一个实例只能有一套,租户之间无法各用 自己的 E2B 账号或自建 Cube 集群。现在这些配置全部落到空间维度的具名 沙箱配置上:部署环境不再提供覆盖项,未选择配置的智能体直接不启用脚本 执行,而不是静默回落到某个部署默认值——后者会让「这个智能体到底跑在 哪」无从判断。 同时把连接检测从「能不能连上控制面」扩展成可解释的诊断: - E2B 标准模板显式带上 default 标签构建。创建沙箱时裸模板名/ID 只解析 default 标签,构建带了别的标签就永远拿不到,表现为一个与「模板不存在」 无法区分的 404。 - 模板状态不再从历史构建或 spawn 次数反推就绪,只认当前构建;构建完成 却没有 default 标签的模板单独报成 untagged,因为它在列表里和「仍在构建」 长得一样,但等待永远不会有结果。 - 创建失败带上 HTTP 状态,404 走模板解释路径,给出具体到「重建模板」还是 「Key 属于其他团队」的结论。 - 探针脚本改在进程工作目录下暂存。系统临时目录在 macOS 上位于 /var/folders,Docker 虚拟机并不共享,挂载进容器后是空目录,真实技能执行 (脚本在 skills/ 下)却不会踩到,检测因此报假失败。 - 检测失败不再只说「命令输出与预期不符」,带上退出码与 stderr 首行。 前端把沙箱设置页与配置抽屉重做:凭据按「是否已配置」展示而非回显掩码, 删除与停用改为就地确认,占用情况走右侧抽屉,列表卡片展示模板状态、凭据、 超时等可判断健康度的事实。
2026-08-11 07:31:58 +00:00
package handler
import (
"testing"
"github.com/stretchr/testify/require"
"github.com/Tencent/WeKnora/internal/sandbox"
"github.com/Tencent/WeKnora/internal/types"
)
func TestSandboxConnectionCheckConfigAllowsTemplateDiscoveryAfterConnection(t *testing.T) {
incoming := &types.TenantSandboxConfig{
SandboxType: "e2b",
E2B: &types.E2BSandboxConfig{APIKey: "key"},
}
got := sandboxConnectionCheckConfig(incoming)
require.Equal(t, "__connection_check__", got.E2B.TemplateID)
require.Empty(t, incoming.E2B.TemplateID, "the submitted form must not be mutated")
}
func TestSandboxCheckReasonDockerUnavailableIncludesHost(t *testing.T) {
msg := sandboxCheckReason(&sandbox.RemoteError{
Kind: sandbox.RemoteErrorKindUnavailable,
Provider: sandbox.SandboxTypeDocker,
Message: "Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?",
})
require.Contains(t, msg, "unix:///var/run/docker.sock")
require.Contains(t, msg, "docker context")
}
func TestRunStatelessSandboxCheckRemovedWithLocalBackend(t *testing.T) {
incoming := &types.TenantSandboxConfig{SandboxType: "local"}
_, err := sandbox.ResolveEffectiveConfig(incoming, sandbox.DefaultConfig())
require.ErrorIs(t, err, sandbox.ErrUnsupportedSandboxType)
feat(sandbox): 沙箱后端改为按空间配置,并补齐 E2B 模板与检测诊断 沙箱的后端类型、凭据、模板、超时和私网访问策略此前分散在部署级 WEKNORA_SANDBOX_* 环境变量里,一个实例只能有一套,租户之间无法各用 自己的 E2B 账号或自建 Cube 集群。现在这些配置全部落到空间维度的具名 沙箱配置上:部署环境不再提供覆盖项,未选择配置的智能体直接不启用脚本 执行,而不是静默回落到某个部署默认值——后者会让「这个智能体到底跑在 哪」无从判断。 同时把连接检测从「能不能连上控制面」扩展成可解释的诊断: - E2B 标准模板显式带上 default 标签构建。创建沙箱时裸模板名/ID 只解析 default 标签,构建带了别的标签就永远拿不到,表现为一个与「模板不存在」 无法区分的 404。 - 模板状态不再从历史构建或 spawn 次数反推就绪,只认当前构建;构建完成 却没有 default 标签的模板单独报成 untagged,因为它在列表里和「仍在构建」 长得一样,但等待永远不会有结果。 - 创建失败带上 HTTP 状态,404 走模板解释路径,给出具体到「重建模板」还是 「Key 属于其他团队」的结论。 - 探针脚本改在进程工作目录下暂存。系统临时目录在 macOS 上位于 /var/folders,Docker 虚拟机并不共享,挂载进容器后是空目录,真实技能执行 (脚本在 skills/ 下)却不会踩到,检测因此报假失败。 - 检测失败不再只说「命令输出与预期不符」,带上退出码与 stderr 首行。 前端把沙箱设置页与配置抽屉重做:凭据按「是否已配置」展示而非回显掩码, 删除与停用改为就地确认,占用情况走右侧抽屉,列表卡片展示模板状态、凭据、 超时等可判断健康度的事实。
2026-08-11 07:31:58 +00:00
}
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>
2026-09-03 02:49:46 +00:00
// 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)
}