Open-source LLM knowledge platform: turn raw documents into a queryable RAG, an autonomous reasoning agent, and a self-maintaining Wiki.
Go agentagenticaichatbotdsh-pluginembeddingsevaluationgenerative-aigolangknowledge-basellmmulti-tenantollamaopenaiquestion-answeringragrerankingsemantic-searchvector-searchwiki
feat: require opt-in for the Docker sandbox backend (#2936)
lyingbug02269bd8f10d
diff --git a/.env.example b/.env.exampleindex 75842ffe2..408d897a6 100644--- a/.env.example+++ b/.env.example@@ -582,7 +582,10 @@ SYSTEM_AES_KEY=weknora-system-aes-key-32bytes!!# ========== G1. Agent Skills Sandbox ==========# Sandbox 后端、凭据、模板、超时和私网访问策略全部在「设置 → 沙箱后端」-# 按空间维护;部署环境不再提供 WEKNORA_SANDBOX_* 覆盖项。+# 按空间维护。唯一的部署级开关是 Docker 后端:默认关闭,因为本机+# docker.sock 等同宿主机 root;私有化单机需要时改为 true,或由系统管理员在+# 「设置 → 系统设置 → 网络安全」打开(立即生效,无需重启)。+WEKNORA_SANDBOX_DOCKER_ENABLED=false# 多实例仍应配置通用 REDIS_ADDR,以共享 session→sandbox binding。# 自定义 Skills 目录(挂载后指定,免重建镜像)。diff --git a/docker-compose.yml b/docker-compose.ymlindex 4e8d1bfb5..fe52937b5 100644--- a/docker-compose.yml+++ b/docker-compose.yml@@ -42,6 +42,9 @@ services:- ./config/config.yaml:/app/config/config.yaml# Optional: mount custom skills directory (allows adding skills without rebuilding image)- ./skills/preloaded:/app/skills/preloaded+ # Docker 沙箱默认关闭(见 WEKNORA_SANDBOX_DOCKER_ENABLED)。需要本机 daemon 时+ # 同时设 true 并挂载实际 socket——这等同宿主机 root,仅私有化单机。+ # - /var/run/docker.sock:/var/run/docker.sock# Optional: declarative built-in models. Copy config/builtin_models.yaml.example# to config/builtin_models.yaml, edit it for your deployment, then# uncomment the line below. See docs/BUILTIN_MODELS.md.@@ -83,6 +86,9 @@ services:# 文档处理语言(问题/摘要生成)。优先级:此环境变量(部署级覆盖,非空即生效)# > Accept-Language 请求头 > 内置默认值 (zh-CN)。留空则跟随请求方 Accept-Language。- WEKNORA_LANGUAGE=${WEKNORA_LANGUAGE:-}+ # Docker 沙箱默认关闭:本机 docker.sock 等同宿主机 root。+ # 系统管理员也可在「设置 → 系统设置」打开(立即生效)。未落库时读本变量。+ - WEKNORA_SANDBOX_DOCKER_ENABLED=${WEKNORA_SANDBOX_DOCKER_ENABLED:-false}# gin 信任的代理 CIDR(逗号分隔);显式设为空字符串则禁用代理信任。# 默认信任 loopback + 私网段(容器网络内 nginx 已覆盖)# - WEKNORA_TRUSTED_PROXIES=${WEKNORA_TRUSTED_PROXIES:-}@@ -368,7 +374,8 @@ services:extra_hosts:- "host.docker.internal:host-gateway"- # Sandbox 镜像:仅用于 build/pull,非常驻服务;app 执行 Skills 时按需 docker run 该镜像,用毕即释+ # Sandbox 镜像:仅用于 build/pull,非常驻。Docker 沙箱默认关闭,需+ # WEKNORA_SANDBOX_DOCKER_ENABLED=true 并挂载 docker.sock 后,app 才会按会话创建容器。sandbox:image: wechatopenai/weknora-sandbox:${WEKNORA_VERSION:-latest}container_name: WeKnora-sandboxdiff --git a/docs/agent-skills.md b/docs/agent-skills.mdindex 841b6f87f..3daa4dd3b 100644--- a/docs/agent-skills.md+++ b/docs/agent-skills.md@@ -124,7 +124,7 @@ type AgentConfig struct {### Sandbox 配置入口-Sandbox 不再读取 `WEKNORA_SANDBOX_*` 环境变量。后端、凭据、模板、执行超时、TTL 和私网访问策略均在「设置 → 沙箱后端」按空间保存;智能体没有选择空间配置时,脚本执行保持禁用。+Sandbox 不再把凭据和模板放进 `WEKNORA_SANDBOX_*`。后端、凭据、模板、执行超时、TTL 和私网访问策略均在「设置 → 沙箱后端」按空间保存;智能体没有选择空间配置时,脚本执行保持禁用。Docker 后端默认关闭,由系统管理员在「设置 → 系统设置」打开,或设置 `WEKNORA_SANDBOX_DOCKER_ENABLED=true`。### Sandbox 模式diff --git a/docs/sandbox-docker-backend.md b/docs/sandbox-docker-backend.mdindex 5a03b2ef5..bb3055629 100644--- a/docs/sandbox-docker-backend.md+++ b/docs/sandbox-docker-backend.md@@ -13,6 +13,7 @@ CubeSandbox / E2B 的集群与模板见 [沙箱集群与标准模板](./sandbox-这正是当初把 provider 抽象成 `RemoteSandboxClient` 的收益。- 它适合单机 / 私有化部署。跨主机调度、内核级隔离、内存态快照仍然要用 E2B 协议后端,原因见「边界」一节。+- **默认关闭。** 本机 `docker.sock` 等同宿主机 root。系统管理员可在「设置 → 系统设置 → 网络安全」打开,立即生效;也可用环境变量 `WEKNORA_SANDBOX_DOCKER_ENABLED=true` 作为未落库时的回退。设置页始终保留 Docker 标签:未打开时没有「添加」入口,只说明如何启用。已有配置仍可查看/删除,但不会再创建容器。- Docker 官方的 Docker Sandboxes(`sbx`)不能当后端:那是开发者本机 CLI,要 Docker 账号登录、工作区是宿主机目录直挂、没有多租户服务端 API。@@ -115,6 +116,8 @@ archive 接口里只剩 `HEAD` 还在用,且仅用于读固定路径的活跃在「设置 → 沙箱后端」中新建配置并选择 Docker:+系统管理员可在「设置 → 系统设置 → 网络安全」打开 Docker 沙箱(立即生效)。未落库时回退到 `WEKNORA_SANDBOX_DOCKER_ENABLED`。默认关闭,因为能保存 Docker 配置的空间管理员可以在本进程够得到的 Engine API 上创建容器,而本机 `docker.sock` 等同宿主机 root。设置页始终有 Docker 标签;未打开时没有添加按钮,只提示如何启用。+| 字段 | 说明 || --- | --- || 镜像 | 必填。会话容器都从它创建,等价于其它后端的 template ID |diff --git a/frontend/src/components/SandboxConfigEditorDrawer.vue b/frontend/src/components/SandboxConfigEditorDrawer.vueindex 464c01213..86ff1f4ae 100644--- a/frontend/src/components/SandboxConfigEditorDrawer.vue+++ b/frontend/src/components/SandboxConfigEditorDrawer.vue@@ -104,6 +104,12 @@{{ $t(`settings.sandbox.backendDescriptions.${backend}`) }}</p></t-form-item>+ <t-alert v-if="backend === 'docker' && !dockerBackendEnabled" theme="warning" class="compact-alert"+ :message="$t('settings.sandbox.dockerDisabledAlert')">+ <template #description>+ <p>{{ $t('settings.sandbox.dockerDisabledHint') }}</p>+ </template>+ </t-alert><t-form-item :label="$t('settings.sandbox.configName')" :status="nameError ? 'error' : undefined":tips="nameError || undefined"><t-input v-model="name" :placeholder="$t('settings.sandbox.configNamePlaceholder')" />@@ -237,6 +243,18 @@<t-input v-model="docker.tls_cert_path" placeholder="/etc/weknora/docker-certs":disabled="retargetFrozen" @input="onFieldInput('tls_cert_path')" /></t-form-item>+ <t-alert theme="warning" class="compact-alert" :message="$t('settings.sandbox.dockerHostRisk')" />+ <div class="private-endpoint-row">+ <div>+ <p class="private-endpoint-row__title">{{ $t('settings.sandbox.allowPrivateEndpoints') }}</p>+ <p class="section-help">{{ $t('settings.sandbox.allowPrivateEndpointsHint') }}</p>+ </div>+ <t-switch+ v-model="allowPrivateEndpoints"+ :disabled="retargetFrozen"+ @change="invalidateConnection"+ />+ </div></section><section v-if="currentStepKey === 'template'" class="setting-drawer__section">@@ -478,6 +496,7 @@ import { MessagePlugin } from 'tdesign-vue-next'import { useI18n } from 'vue-i18n'import SettingDrawer from '@/components/settings/SettingDrawer.vue'import SandboxBackendBadge from '@/components/settings/SandboxBackendBadge.vue'+import { useDeploymentCapabilitiesStore } from '@/stores/deploymentCapabilities'import {checkSandboxConfig,createSandboxConfig,@@ -512,6 +531,10 @@ const emit = defineEmits<{}>()const { t } = useI18n()+const deploymentCapabilities = useDeploymentCapabilitiesStore()+const dockerBackendEnabled = computed(() =>+ deploymentCapabilities.isSupported('settings.sandbox.docker'),+)// The backend echoes stored secrets as this placeholder. It never leaves the// form as visible text: inputs stay empty and say "configured", and the@@ -527,7 +550,11 @@ const defaultDockerImage = 'wechatopenai/weknora-sandbox:main'const clusterGuideUrl = 'https://github.com/Tencent/WeKnora/blob/main/docs/sandbox-cluster.md'const e2bApiKeysUrl = 'https://e2b.dev/dashboard?tab=keys'-const backendOptions = [...NAMED_SANDBOX_BACKEND_TYPES]+const backendOptions = computed(() => {+ const types = [...NAMED_SANDBOX_BACKEND_TYPES]+ if (dockerBackendEnabled.value || backend.value === 'docker') return types+ return types.filter((type) => type !== 'docker')+})const saving = ref(false)const checking = ref(false)@@ -595,13 +622,17 @@ const primaryText = computed(() => {// the image on the connection step; Cube/E2B still have an empty template_id// there, so the action waits until the template step.const canDeepCheck = computed(() => {+ if (backend.value === 'docker' && !dockerBackendEnabled.value) return falseif (currentStepKey.value === 'template') return truereturn currentStepKey.value === 'connection' && !isRemoteBackend.value})const showCheckResult = computed(() => canDeepCheck.value)const primaryDisabled = computed(() => (- currentStepKey.value === 'template'- && (!selectedTemplate.value || !isTemplateSelectable(selectedTemplate.value))+ (backend.value === 'docker' && !dockerBackendEnabled.value)+ || (+ currentStepKey.value === 'template'+ && (!selectedTemplate.value || !isTemplateSelectable(selectedTemplate.value))+ )))// savedRecord is the config this drawer is editing, including one it just@@ -796,6 +827,7 @@ async function refreshInFlightSkill() {watch(() => props.visible, (open) => {if (open) {+ void deploymentCapabilities.ensureLoaded()reset()void refreshInFlightSkill()} else {@@ -1064,6 +1096,7 @@ function validateName(): boolean {}async function handlePrimaryAction() {+ if (backend.value === 'docker' && !dockerBackendEnabled.value) returnif (currentStepKey.value === 'connection') {if (!validateName() || !validateRequiredFields(false)) returnif (!(await runCheck(false))) returndiff --git a/frontend/src/config/deploymentCapabilities.test.ts b/frontend/src/config/deploymentCapabilities.test.tsindex 09bf8f8f5..417482bec 100644--- a/frontend/src/config/deploymentCapabilities.test.ts+++ b/frontend/src/config/deploymentCapabilities.test.ts@@ -52,3 +52,21 @@ test('the skill catalog follows the sandbox capability', () => {assert.equal(SETTINGS_SECTION_CAPABILITY.skills, 'settings.sandbox')assert.equal(SETTINGS_SECTION_CAPABILITY.skills, SETTINGS_SECTION_CAPABILITY.sandbox)})++test('docker sandbox stays hidden unless the deployment explicitly enables it', () => {+ assert.equal(isDeploymentCapabilitySupported({}, 'settings.sandbox.docker'), false)+ assert.equal(+ isDeploymentCapabilitySupported(+ { 'settings.sandbox.docker': { supported: false, reason: 'docker_backend_disabled' } },+ 'settings.sandbox.docker',+ ),+ false,+ )+ assert.equal(+ isDeploymentCapabilitySupported(+ { 'settings.sandbox.docker': { supported: true } },+ 'settings.sandbox.docker',+ ),+ true,+ )+})diff --git a/frontend/src/config/deploymentCapabilities.ts b/frontend/src/config/deploymentCapabilities.tsindex e6219eb13..e0b6f7bc7 100644--- a/frontend/src/config/deploymentCapabilities.ts+++ b/frontend/src/config/deploymentCapabilities.ts@@ -9,6 +9,7 @@ export const DEPLOYMENT_CAPABILITY_KEYS = ['settings.vectorstore','settings.storage','settings.sandbox',+ 'settings.sandbox.docker',] as constexport type DeploymentCapabilityKey = typeof DEPLOYMENT_CAPABILITY_KEYS[number]@@ -36,6 +37,11 @@ export function isDeploymentCapabilitySupported(options?.edition?.trim().toLowerCase() === 'lite'if (isLite) return false}+ // Docker talks to a local Engine API (often docker.sock = host root), so+ // missing or failed capability probes must not leave the picker visible.+ if (key === 'settings.sandbox.docker') {+ return capabilities[key]?.supported === true+ }return capabilities[key]?.supported !== false}diff --git a/frontend/src/i18n/locales/en-US.ts b/frontend/src/i18n/locales/en-US.tsindex 63fb71235..0b73c1959 100755--- a/frontend/src/i18n/locales/en-US.ts+++ b/frontend/src/i18n/locales/en-US.ts@@ -1104,6 +1104,10 @@ export default {e2b: 'Managed MicroVM service or an E2B-compatible deployment',docker: 'Keep a long-lived container per session on this WeKnora host; scripts and files stay in that container',},+ dockerDisabledAlert: 'Docker sandbox is not enabled on this deployment',+ dockerDisabledHint: 'A local docker.sock is equivalent to root on the host. For a single-machine private install, a system admin can enable it under Settings → System settings → Network security.',+ dockerDisabledCard: 'Docker sandbox is disabled on this deployment; this config will not create containers',+ dockerHostRisk: 'Empty or unix:// uses the Docker daemon on the WeKnora host, which is equivalent to root on that machine. Use this only for a private single-node install. Prefer Cube or E2B when multiple workspaces share a host. Remote tcp:// endpoints require a TLS certificate directory.',addConfig: 'Add sandbox',viewClusterGuide: 'Cluster setup guide',configName: 'Config name',@@ -3633,7 +3637,7 @@ export default {security: {tab: 'Network security {count}',title: 'Network security',- description: 'Manage trusted hosts, IPs, and networks that may bypass SSRF protection.'+ description: 'Manage the SSRF allowlist and whether the Docker sandbox is allowed (a local docker.sock is equivalent to root on the host).'},other: {tab: 'Other {count}',@@ -3861,11 +3865,15 @@ export default {ssrf: {whitelist: 'SSRF protection allowlist'},+ sandbox: {+ docker_enabled: 'Enable Docker sandbox'+ },tenant: {max_owned_per_user: 'Max workspaces owned per user',self_service_creation_enabled: 'Allow self-service workspace creation',default_storage_quota_gb: 'Default storage quota for new workspaces (GB)',- auto_create_api_key: 'Automatically create an API key for new workspaces'+ auto_create_api_key: 'Automatically create an API key for new workspaces',+ auto_accept_invitation: 'Auto-join invited registered users'},asynq: {core_concurrency: 'Guaranteed core parse concurrency',@@ -3888,11 +3896,15 @@ export default {ssrf: {whitelist: 'SSRF protection allowlist. Accepts entries such as example.com / *.foo.com / 10.0.0.0/8 / 2001:db8::1. Takes effect immediately after saving. The SSRF_WHITELIST_EXTRA environment variable is still maintained by the deployer and is not overridden here.'},+ sandbox: {+ docker_enabled: 'Allow the Docker sandbox backend. A local docker.sock is equivalent to root on the host, so this stays off by default. Only a system admin can turn it on; the change takes effect immediately. Enable it only on a private single-node install that mounts the daemon socket or uses a TLS-protected remote tcp:// endpoint.'+ },tenant: {max_owned_per_user: 'Maximum number of workspaces a non-superuser may own via self-service creation. Read on every workspace creation and takes effect immediately after saving. 0 uses the built-in default of 10; a negative value disables the cap entirely (not recommended on public deployments).',self_service_creation_enabled: 'Whether non-superusers may create workspaces themselves. When disabled, regular users can only join existing workspaces by invitation; cross-workspace superusers remain exempt. Takes effect immediately.',default_storage_quota_gb: 'Default storage quota (GB) assigned when a new workspace is created, covering vectors, originals, text, indexes, and related data. Read only at creation time — changes apply to newly created workspaces only and do not retroactively update existing workspaces. 0 or a negative value uses the built-in default of 10 GB.',- auto_create_api_key: 'Automatically creates a full_access API key for a new workspace and returns its plaintext token in the create response. Use only for integrations that depend on the legacy behavior; it is disabled by default and explicit API-key creation is recommended.'+ auto_create_api_key: 'Automatically creates a full_access API key for a new workspace and returns its plaintext token in the create response. Use only for integrations that depend on the legacy behavior; it is disabled by default and explicit API-key creation is recommended.',+ auto_accept_invitation: 'When enabled, inviting a registered user by email adds them as a member immediately instead of waiting for inbox confirmation. When off, the invitee must accept from their inbox. Takes effect immediately.'},asynq: {core_concurrency: 'Guaranteed per-process concurrency for document and manual parsing. Core may also borrow the shared elastic pool. Minimum 1; requires a service restart.',@@ -3922,7 +3934,8 @@ export default {confirmBtn: 'Confirm save',cancelBtn: 'Cancel',emptyValue: '(empty)',- bodyAuthRegistrationMode: 'About to change "{label}" to: {value}\n\nIf switched to self_serve, anyone on the public internet can register an account — please confirm this is intended.'+ bodyAuthRegistrationMode: 'About to change "{label}" to: {value}\n\nIf switched to self_serve, anyone on the public internet can register an account — please confirm this is intended.',+ bodySandboxDockerEnabled: 'Once on, workspace admins can point a sandbox at the local Docker daemon. A local docker.sock is equivalent to root on the host. Use this only on a private single-node install that mounts the daemon or uses a TLS-protected remote tcp:// endpoint.'},listConfirm: {ssrf: {diff --git a/frontend/src/i18n/locales/ko-KR.ts b/frontend/src/i18n/locales/ko-KR.tsindex 8deaf14a5..b91bca9ad 100755--- a/frontend/src/i18n/locales/ko-KR.ts+++ b/frontend/src/i18n/locales/ko-KR.ts@@ -2786,7 +2786,8 @@ export default {confirmBtn: '저장 확인',cancelBtn: '취소',emptyValue: '(비어 있음)',- bodyAuthRegistrationMode: '「{label}」을(를) {value}(으)로 변경하려고 합니다.\n\nself_serve로 전환하면 인터넷의 누구나 계정을 만들 수 있습니다. 의도된 동작인지 확인해 주세요.'+ bodyAuthRegistrationMode: '「{label}」을(를) {value}(으)로 변경하려고 합니다.\n\nself_serve로 전환하면 인터넷의 누구나 계정을 만들 수 있습니다. 의도된 동작인지 확인해 주세요.',+ bodySandboxDockerEnabled: '켜면 워크스페이스 관리자가 로컬 Docker 데몬을 샌드박스로 지정할 수 있습니다. 로컬 docker.sock은 호스트 root와 같습니다. 데몬을 마운트했거나 TLS가 있는 원격 tcp:// 를 쓰는 프라이빗 단일 노드에서만 사용하세요.'},enumLabels: {auth: {@@ -2816,11 +2817,15 @@ export default {max_owned_per_user: '슈퍼유저가 아닌 사용자가 셀프 서비스로 소유할 수 있는 최대 워크스페이스 수입니다. 워크스페이스 생성 시마다 읽으며 저장 즉시 적용됩니다. 0은 내장 기본값 10을 사용하고, 음수는 제한을 완전히 해제합니다(공개 배포에는 권장하지 않음).',self_service_creation_enabled: '비슈퍼유저가 공간을 직접 만들 수 있는지 설정합니다. 비활성화하면 일반 사용자는 초대로만 기존 공간에 참여할 수 있으며, 크로스 워크스페이스 슈퍼유저는 계속 만들 수 있습니다.',default_storage_quota_gb: '신규 워크스페이스 생성 시 기본으로 할당되는 저장 용량(GB)으로, 벡터·원본·텍스트·인덱스 등을 포함합니다. 생성 시에만 읽으며, 변경은 이후 생성되는 워크스페이스에만 적용되고 기존 워크스페이스에는 소급되지 않습니다. 0 또는 음수는 내장 기본값 10GB를 사용합니다.',- auto_create_api_key: '신규 워크스페이스에 full_access API Key를 자동 생성하고 생성 응답에 평문 token을 반환합니다. 기존 동작에 의존하는 연동에만 사용하세요. 기본값은 비활성화입니다.'+ auto_create_api_key: '신규 워크스페이스에 full_access API Key를 자동 생성하고 생성 응답에 평문 token을 반환합니다. 기존 동작에 의존하는 연동에만 사용하세요. 기본값은 비활성화입니다.',+ auto_accept_invitation: '켜면 워크스페이스 관리자가 이메일로 가입된 사용자를 초대할 때 상대가 바로 멤버가 되며, 받은편지함에서 수락할 필요가 없습니다. 끄면 「초대 발송 → 상대가 수락」 흐름을 유지합니다. 저장 즉시 적용됩니다.'},ssrf: {whitelist: 'SSRF 보호 허용 목록입니다. example.com / *.foo.com / 10.0.0.0/8 / 2001:db8::1 형식을 입력할 수 있습니다. 저장 즉시 적용됩니다. SSRF_WHITELIST_EXTRA 환경 변수는 배포자가 관리하며 여기서 덮어쓰지 않습니다.'},+ sandbox: {+ docker_enabled: 'Docker 샌드박스 백엔드를 허용할지 설정합니다. 로컬 docker.sock은 호스트 root와 같으므로 기본값은 꺼짐입니다. 시스템 관리자만 켤 수 있으며 저장 즉시 적용됩니다. 데몬 소켓을 마운트했거나 TLS가 있는 원격 tcp:// 를 쓰는 프라이빗 단일 노드에서만 켜세요.'+ },auth: {registration_mode: '셀프 가입 모드입니다. self_serve = 누구나 계정을 만들 수 있음; invite_only = 공개 가입을 끄고 Owner/Admin만 초대 가능. 저장 즉시 적용되며, self_serve는 스팸 가입이 들어올 수 있으니 신중히 사용하세요.',default_tenant_mode: '공개 가입 후 공간 초기화 정책입니다. create_personal은 개인 공간을 만들고 Owner를 부여하며, tenantless는 초대 수락 또는 직접 공간 생성 전까지 계정만 만듭니다.',@@ -2843,11 +2848,15 @@ export default {max_owned_per_user: '사용자당 최대 워크스페이스 수',self_service_creation_enabled: '사용자 공간 직접 생성 허용',default_storage_quota_gb: '신규 워크스페이스 기본 저장 용량 (GB)',- auto_create_api_key: '신규 워크스페이스 API Key 자동 생성'+ auto_create_api_key: '신규 워크스페이스 API Key 자동 생성',+ auto_accept_invitation: '등록된 사용자 초대 시 자동 가입'},ssrf: {whitelist: 'SSRF 보호 허용 목록'},+ sandbox: {+ docker_enabled: 'Docker 샌드박스 사용'+ },auth: {registration_mode: '셀프 가입 모드',default_tenant_mode: '기본 공간 프로비저닝',@@ -3074,7 +3083,7 @@ export default {security: {tab: '네트워크 보안 {count}',title: '네트워크 보안',- description: 'SSRF 보호를 우회할 수 있는 신뢰 호스트, IP, 네트워크를 관리합니다.'+ description: 'SSRF 허용 목록과 Docker 샌드박스 허용 여부(로컬 docker.sock은 호스트 root와 같음)를 관리합니다.'},runtime: {tab: '런타임 및 동시성 {count}',@@ -5015,6 +5024,10 @@ export default {e2b: 'Managed MicroVM service or an E2B-compatible deployment',docker: '이 WeKnora 호스트의 Docker에서 세션마다 장수명 컨테이너를 유지합니다. 스크립트와 파일이 같은 컨테이너에 남습니다',},+ dockerDisabledAlert: '이 배포에서는 Docker 샌드박스가 켜져 있지 않습니다',+ dockerDisabledHint: '로컬 docker.sock은 호스트 root와 같습니다. 단일 머신 프라이빗 설치에서는 시스템 관리자가 설정 → 시스템 설정 → 네트워크 보안에서 켤 수 있습니다.',+ dockerDisabledCard: '이 배포에서 Docker 샌드박스가 꺼져 있어 이 구성은 컨테이너를 만들지 않습니다',+ dockerHostRisk: '비우거나 unix:// 를 쓰면 WeKnora가 있는 머신의 Docker 데몬을 사용하며, 그 권한은 해당 머신의 root와 같습니다. 프라이빗 단일 노드에만 쓰세요. 여러 워크스페이스가 같은 호스트를 쓰는 경우에는 Cube 또는 E2B를 쓰세요. 원격 tcp:// 는 TLS 인증서 디렉터리가 필요합니다.',addConfig: '샌드박스 추가',viewClusterGuide: 'Cluster setup guide',configName: 'Config name',diff --git a/frontend/src/i18n/locales/ru-RU.ts b/frontend/src/i18n/locales/ru-RU.tsindex c972d3dc3..74624fdbd 100755--- a/frontend/src/i18n/locales/ru-RU.ts+++ b/frontend/src/i18n/locales/ru-RU.ts@@ -2786,7 +2786,8 @@ export default {confirmBtn: 'Подтвердить сохранение',cancelBtn: 'Отмена',emptyValue: '(пусто)',- bodyAuthRegistrationMode: 'Вы собираетесь изменить «{label}» на: {value}\n\nЕсли переключить на self_serve, любой пользователь публичного интернета сможет создать аккаунт — убедитесь, что это ожидаемое поведение.'+ bodyAuthRegistrationMode: 'Вы собираетесь изменить «{label}» на: {value}\n\nЕсли переключить на self_serve, любой пользователь публичного интернета сможет создать аккаунт — убедитесь, что это ожидаемое поведение.',+ bodySandboxDockerEnabled: 'После включения администраторы пространства смогут направить песочницу на локальный демон Docker. Локальный docker.sock равносилен root на хосте. Только для частной одноузловой установки с примонтированным демоном или удалённым tcp:// с TLS.'},enumLabels: {auth: {@@ -2816,11 +2817,15 @@ export default {max_owned_per_user: 'Максимальное число пространств, которыми может владеть обычный (не супер) пользователь через самостоятельное создание. Читается при каждом создании пространства и вступает в силу сразу после сохранения. 0 — встроенное значение по умолчанию 10; отрицательное значение полностью снимает ограничение (не рекомендуется для публичных развёртываний).',self_service_creation_enabled: 'Разрешает обычным пользователям самостоятельно создавать пространства. Если отключено, они могут только присоединяться по приглашению; межпространственные суперпользователи не ограничены.',default_storage_quota_gb: 'Квота хранилища по умолчанию (ГБ) для нового пространства: векторы, оригиналы, текст, индексы и т.д. Читается только при создании — изменения применяются только к новым пространствам и не перезаписывают существующие. 0 или отрицательное значение — встроенное значение по умолчанию 10 ГБ.',- auto_create_api_key: 'Автоматически создаёт API-ключ full_access и возвращает его открытый токен при создании пространства. Включайте только для старых интеграций; по умолчанию отключено.'+ auto_create_api_key: 'Автоматически создаёт API-ключ full_access и возвращает его открытый токен при создании пространства. Включайте только для старых интеграций; по умолчанию отключено.',+ auto_accept_invitation: 'Если включено, приглашение зарегистрированного пользователя по email сразу добавляет его в пространство без подтверждения во входящих. Если выключено, сохраняется схема «отправка приглашения → подтверждение». Вступает в силу сразу после сохранения.'},ssrf: {whitelist: 'Белый список SSRF-защиты. Можно указать example.com / *.foo.com / 10.0.0.0/8 / 2001:db8::1. Вступает в силу сразу после сохранения. Переменная окружения SSRF_WHITELIST_EXTRA по-прежнему задаётся при развёртывании и здесь не переопределяется.'},+ sandbox: {+ docker_enabled: 'Разрешить бэкенд песочницы Docker. Локальный docker.sock равносилен root на хосте, поэтому по умолчанию выключено. Включить может только системный администратор; изменение действует сразу. Включайте только на частной одноузловой установке с примонтированным сокетом демона или удалённым tcp:// с TLS.'+ },auth: {registration_mode: 'Режим самостоятельной регистрации. self_serve = любой может создать аккаунт; invite_only = открытая регистрация отключена, приглашать могут только Owner/Admin. Вступает в силу сразу после сохранения; используйте self_serve осторожно (в публичном интернете появятся спам-регистрации).',default_tenant_mode: 'Политика пространства после открытой регистрации. create_personal создаёт личное пространство с ролью Owner; tenantless создаёт только аккаунт до принятия приглашения или самостоятельного создания пространства.',@@ -2843,11 +2848,15 @@ export default {max_owned_per_user: 'Максимум пространств на пользователя',self_service_creation_enabled: 'Разрешить самостоятельное создание пространств',default_storage_quota_gb: 'Квота хранилища для новых пространств по умолчанию (ГБ)',- auto_create_api_key: 'Автоматически создавать API-ключ для новых пространств'+ auto_create_api_key: 'Автоматически создавать API-ключ для новых пространств',+ auto_accept_invitation: 'Автоматически принимать приглашённых зарегистрированных пользователей'},ssrf: {whitelist: 'Белый список SSRF-защиты'},+ sandbox: {+ docker_enabled: 'Включить песочницу Docker'+ },auth: {registration_mode: 'Режим самостоятельной регистрации',default_tenant_mode: 'Создание пространства по умолчанию',@@ -3074,7 +3083,7 @@ export default {security: {tab: 'Сетевая безопасность {count}',title: 'Сетевая безопасность',- description: 'Доверенные хосты, IP-адреса и сети, обходящие SSRF-защиту.'+ description: 'Белый список SSRF и разрешение песочницы Docker (локальный docker.sock равносилен root на хосте).'},runtime: {tab: 'Среда и параллелизм {count}',@@ -5015,6 +5024,10 @@ export default {e2b: 'Managed MicroVM service or an E2B-compatible deployment',docker: 'Держит долгоживущий контейнер на каждую сессию на этом хосте WeKnora; скрипты и файлы остаются в том же контейнере',},+ dockerDisabledAlert: 'Песочница Docker на этом развёртывании не включена',+ dockerDisabledHint: 'Локальный docker.sock равносилен root на хосте. Для частной одноузловой установки системный администратор может включить это в «Настройки → Системные настройки → Сетевая безопасность».',+ dockerDisabledCard: 'Песочница Docker отключена на этом развёртывании; эта конфигурация больше не создаёт контейнеры',+ dockerHostRisk: 'Пустое значение или unix:// использует демон Docker на машине WeKnora — это равносильно root на этой машине. Только для частной одноузловой установки. Если несколько пространств делят один хост, используйте Cube или E2B. Удалённый tcp:// требует каталог TLS-сертификатов.',addConfig: 'Добавить песочницу',viewClusterGuide: 'Cluster setup guide',configName: 'Config name',diff --git a/frontend/src/i18n/locales/zh-CN.ts b/frontend/src/i18n/locales/zh-CN.tsindex 30cf19226..15c4c298c 100755--- a/frontend/src/i18n/locales/zh-CN.ts+++ b/frontend/src/i18n/locales/zh-CN.ts@@ -2788,7 +2788,8 @@ export default {confirmBtn: '确认保存',cancelBtn: '取消',emptyValue: '(空)',- bodyAuthRegistrationMode: '即将把「{label}」改为:{value}\n\n如果切到 self_serve,公网任何人都可以注册账号 — 务必确认是预期行为。'+ bodyAuthRegistrationMode: '即将把「{label}」改为:{value}\n\n如果切到 self_serve,公网任何人都可以注册账号 — 务必确认是预期行为。',+ bodySandboxDockerEnabled: '打开后,空间管理员可以把沙箱指到本机 Docker。本机 docker.sock 等同宿主机 root,只适合已挂载 daemon 或配了 TLS 远程 tcp:// 的私有化单机。'},enumLabels: {auth: {@@ -2818,11 +2819,15 @@ export default {max_owned_per_user: '每个非超管用户通过自助创建可拥有的最大空间数。每次创建空间时实时读取,修改后立即生效。0 表示使用内置默认值 10;负数表示完全关闭限制(不建议在公开部署使用)。',self_service_creation_enabled: '是否允许非超管用户主动创建空间。关闭后,普通用户只能通过邀请加入已有空间;跨空间超管仍可创建。修改后立即生效。',default_storage_quota_gb: '新建空间时默认分配的存储配额(GB),包含向量、原文、文本、索引等。仅在创建时读取,修改后只对之后新建的空间生效,不会回写已存在的空间。0 或负数表示使用内置默认值 10GB。',- auto_create_api_key: '为新空间自动生成 full_access API Key,并在创建响应中返回明文 token。仅用于兼容依赖旧行为的集成;默认关闭,建议通过 API Key 管理显式创建。'+ auto_create_api_key: '为新空间自动生成 full_access API Key,并在创建响应中返回明文 token。仅用于兼容依赖旧行为的集成;默认关闭,建议通过 API Key 管理显式创建。',+ auto_accept_invitation: '开启后,空间管理员通过邮箱邀请已注册用户时,对方会立即成为成员,不再经过收件箱确认。关闭时保持「发出邀请 → 被邀请人确认」流程。修改后立即生效。'},ssrf: {whitelist: 'SSRF 防护白名单。可填入 example.com / *.foo.com / 10.0.0.0/8 / 2001:db8::1。修改后立即生效。SSRF_WHITELIST_EXTRA 环境变量仍由部署方维护,不在此处覆盖。'},+ sandbox: {+ docker_enabled: '是否允许 Docker 沙箱后端。本机 docker.sock 等同宿主机 root,默认关闭。仅系统管理员可打开;打开后立即生效,无需重启。私有化单机且已挂载 daemon socket,或配置了带 TLS 的远程 tcp:// 时再启用。'+ },auth: {registration_mode: '自助注册模式。self_serve = 任何人可注册账号;invite_only = 关闭公网注册,仅 Owner/Admin 可邀请。修改后立即生效,但谨慎对待 self_serve(公网会接受 spam)。',default_tenant_mode: '公开注册后的空间初始化策略。create_personal 会自动创建个人空间并授予 Owner;tenantless 仅创建账户,用户需要接受邀请或主动创建空间。只影响之后注册的用户。',@@ -2845,11 +2850,15 @@ export default {max_owned_per_user: '每用户最大空间数',self_service_creation_enabled: '允许用户自助创建空间',default_storage_quota_gb: '新空间默认存储配额 (GB)',- auto_create_api_key: '创建空间时自动生成 API Key'+ auto_create_api_key: '创建空间时自动生成 API Key',+ auto_accept_invitation: '邀请已注册用户时自动加入'},ssrf: {whitelist: 'SSRF 防护白名单'},+ sandbox: {+ docker_enabled: '启用 Docker 沙箱'+ },auth: {registration_mode: '自助注册模式',default_tenant_mode: '注册默认空间策略',@@ -3076,7 +3085,7 @@ export default {security: {tab: '网络安全 {count}',title: '网络安全',- description: '管理可绕过 SSRF 防护的受信主机、IP 与网段。'+ description: '管理 SSRF 白名单,以及是否允许 Docker 沙箱(本机 docker.sock 等同宿主机 root)。'},runtime: {tab: '运行与并发 {count}',@@ -5017,6 +5026,10 @@ export default {e2b: 'E2B 托管服务或兼容 E2B 的集群',docker: '在本机 Docker 上为每个会话保留一个长驻容器,脚本和文件都落在同一容器里',},+ dockerDisabledAlert: '当前部署未启用 Docker 沙箱',+ dockerDisabledHint: '本机 docker.sock 等同宿主机 root。仅私有化单机需要时,由系统管理员在「设置 → 系统设置 → 网络安全」中打开。',+ dockerDisabledCard: '部署未启用 Docker 沙箱,此配置不会再创建容器',+ dockerHostRisk: '留空或 unix:// 会使用 WeKnora 所在机器的 Docker 守护进程,权限等同该机 root,只适合私有化单机。多套空间共用同一主机时请改用 Cube 或 E2B。远程 tcp:// 必须填写 TLS 证书目录。',addConfig: '添加沙箱',viewClusterGuide: '集群搭建指南',configName: '配置名称',diff --git a/frontend/src/views/settings/SandboxSettings.vue b/frontend/src/views/settings/SandboxSettings.vueindex 3adbd9a9b..68d074ab4 100644--- a/frontend/src/views/settings/SandboxSettings.vue+++ b/frontend/src/views/settings/SandboxSettings.vue@@ -64,7 +64,21 @@</div><t-loading :loading="loading" size="small" class="sandbox-list-loading">- <div v-if="!loading" class="sandbox-grid">+ <t-alert+ v-if="!loading && dockerTabDisabled && filteredRecords.length > 0"+ theme="warning"+ class="sandbox-docker-banner"+ :message="$t('settings.sandbox.dockerDisabledAlert')"+ >+ <template #description>+ <p>{{ $t('settings.sandbox.dockerDisabledHint') }}</p>+ </template>+ </t-alert>+ <div v-if="!loading && dockerTabDisabled && filteredRecords.length === 0" class="sandbox-docker-disabled">+ <t-empty :description="$t('settings.sandbox.dockerDisabledAlert')" />+ <p class="sandbox-empty-hint">{{ $t('settings.sandbox.dockerDisabledHint') }}</p>+ </div>+ <div v-else-if="!loading" class="sandbox-grid"><div v-for="record in filteredRecords" :key="record.id" class="sandbox-card":class="[`sandbox-card--${record.sandbox_type}`, { 'sandbox-card--clickable': !isLegacyRecord(record) }]":role="isLegacyRecord(record) ? undefined : 'button'"@@ -109,18 +123,18 @@</ul></div></div>- <button type="button" class="sandbox-card sandbox-card--add" @click="openCreate">+ <button v-if="canCreateOnTab" type="button" class="sandbox-card sandbox-card--add" @click="openCreate"><span class="sandbox-card--add__icon" aria-hidden="true"><t-icon name="add" /></span><span class="sandbox-card--add__label">{{ $t('settings.sandbox.addConfig') }}</span></button></div>- <p v-if="!loading && records.length === 0" class="sandbox-empty-hint">+ <p v-if="!loading && !dockerTabDisabled && records.length === 0" class="sandbox-empty-hint">{{ $t('settings.sandbox.noConfigs') }}</p></t-loading><SandboxConfigEditorDrawer v-model:visible="showEditor" :record="editingRecord"- :preset-type="activeType === 'all' ? '' : activeType"+ :preset-type="createPresetType"@saved="load" /><!--@@ -203,6 +217,7 @@ import SandboxBackendBadge from '@/components/settings/SandboxBackendBadge.vue'import SettingDrawer from '@/components/settings/SettingDrawer.vue'import { useConfirmDelete } from '@/components/settings/useConfirmDelete'import { getSession } from '@/api/chat/index'+import { useDeploymentCapabilitiesStore } from '@/stores/deploymentCapabilities'import {deleteSandboxConfig,getSandboxConfigInventory,@@ -218,10 +233,26 @@ import {const { t } = useI18n()const router = useRouter()const confirmDelete = useConfirmDelete()+const deploymentCapabilities = useDeploymentCapabilitiesStore()+const dockerBackendEnabled = computed(() =>+ deploymentCapabilities.isSupported('settings.sandbox.docker'),+)const sandboxGuideUrl = 'https://github.com/Tencent/WeKnora/blob/main/docs/sandbox-cluster.md'-const backendTypes = NAMED_SANDBOX_BACKEND_TYPES+const backendTypes = [...NAMED_SANDBOX_BACKEND_TYPES]++const dockerTabDisabled = computed(() =>+ activeType.value === 'docker' && !dockerBackendEnabled.value,+)++const canCreateOnTab = computed(() => !dockerTabDisabled.value)++const createPresetType = computed(() => {+ if (activeType.value === 'all') return ''+ if (dockerTabDisabled.value) return ''+ return activeType.value+})const loading = ref(false)const policySaving = ref(false)@@ -350,6 +381,7 @@ async function onDeleteConfirmOpen(visible: boolean, record: SandboxConfigRecord}function openCreate() {+ if (!canCreateOnTab.value) returneditingRecord.value = nullshowEditor.value = true}@@ -411,6 +443,12 @@ function buildCardWarnings(record: SandboxConfigRecord): CardWarning[] {})}}+ if (record.sandbox_type === 'docker' && !dockerBackendEnabled.value) {+ warnings.push({+ key: 'docker-disabled',+ text: t('settings.sandbox.dockerDisabledCard'),+ })+ }if (record.sandbox_type === 'docker' && !config.docker?.image?.trim()) {warnings.push({key: 'image',@@ -531,7 +569,10 @@ async function forceRemove(record: SandboxConfigRecord) {await removeRecord(record, true)}-onMounted(load)+onMounted(() => {+ void deploymentCapabilities.ensureLoaded()+ load()+})</script><style lang="less" scoped>@@ -910,12 +951,25 @@ onMounted(load)opacity: 1;}+.sandbox-docker-banner {+ margin-bottom: 12px;+}++.sandbox-docker-disabled {+ padding: 48px 16px 24px;+ text-align: center;+}+.sandbox-empty-hint {margin: 16px 0 0;font-size: 13px;color: var(--td-text-color-placeholder);}+.sandbox-docker-disabled .sandbox-empty-hint {+ margin-top: 8px;+}+.inventory-banner {margin-bottom: 4px;}diff --git a/frontend/src/views/system/SystemSettings.vue b/frontend/src/views/system/SystemSettings.vueindex ea00aacee..02bb34537 100644--- a/frontend/src/views/system/SystemSettings.vue+++ b/frontend/src/views/system/SystemSettings.vue@@ -33,7 +33,25 @@--><div class="system-settings"><div class="section-header">- <h2>{{ t('system.globalSettings.title') }}</h2>+ <div class="section-header__titlewrap">+ <h2>{{ t('system.globalSettings.title') }}</h2>+ <t-popup placement="bottom-start" trigger="hover" :overlay-inner-style="{ maxWidth: '420px' }">+ <button type="button" class="hint-trigger"+ :aria-label="t('system.globalSettings.priorityHint.disclosure')">+ <t-icon name="info-circle" size="16px" />+ </button>+ <template #content>+ <div class="hint-popover">+ <p class="hint-popover__title">{{ t('system.globalSettings.priorityHint.disclosure') }}</p>+ <ul class="hint-popover__list">+ <li>{{ t('system.globalSettings.priorityHint.tier1') }}</li>+ <li>{{ t('system.globalSettings.priorityHint.tier2') }}</li>+ <li>{{ t('system.globalSettings.priorityHint.tier3') }}</li>+ </ul>+ </div>+ </template>+ </t-popup>+ </div><p class="section-description">{{ t('system.globalSettings.description') }}</p>@@ -49,18 +67,6 @@</div><template v-else>- <div class="settings-intro-panel">- <div class="priority-hint-title">- <t-icon name="info-circle" />- <span>{{ t('system.globalSettings.priorityHint.disclosure') }}</span>- </div>- <ul class="priority-hint-list">- <li>{{ t('system.globalSettings.priorityHint.tier1') }}</li>- <li>{{ t('system.globalSettings.priorityHint.tier2') }}</li>- <li>{{ t('system.globalSettings.priorityHint.tier3') }}</li>- </ul>- </div>-<t-tabs v-model="activeSettingsSection" class="settings-section-tabs"><t-tab-panel value="access" :label="sectionTabLabel('access')" /><t-tab-panel value="tenant" :label="sectionTabLabel('tenant')" />@@ -73,15 +79,12 @@/></t-tabs>- <section class="settings-section-panel" :aria-labelledby="`settings-section-${activeSettingsSection}`">+ <section class="settings-section-panel" :aria-label="activeSectionTitle"><divclass="settings-section-intro":class="{ 'settings-section-intro--runtime': activeSettingsSection === 'runtime' }">- <div>- <h3 :id="`settings-section-${activeSettingsSection}`">{{ activeSectionTitle }}</h3>- <p>{{ activeSectionDescription }}</p>- </div>+ <p>{{ activeSectionDescription }}</p><t-tag v-if="activeSettingsSection === 'runtime'" theme="warning" variant="light" size="small">{{ t('system.globalSettings.sections.runtime.restartHint') }}</t-tag>@@ -265,6 +268,28 @@class="setting-input"@change="onChange(item)"/>+ <t-popconfirm+ v-else-if="item.value_type === 'bool' && isHighRiskKey(item.key)"+ v-model:visible="highRiskPopconfirm.visible"+ :content="highRiskPopconfirm.content"+ :theme="highRiskPopconfirm.theme"+ :confirm-btn="highRiskPopconfirm.confirmBtn"+ :cancel-btn="t('system.globalSettings.confirm.cancelBtn')"+ :popup-props="PROGRAMMATIC_POPCONFIRM_PROPS"+ placement="left"+ @confirm="highRiskPopconfirm.finish(true)"+ @cancel="highRiskPopconfirm.finish(false)"+ @visible-change="highRiskPopconfirm.onVisibleChange"+ >+ <div class="setting-control-anchor">+ <t-switch+ v-model="editValues[item.key]"+ :aria-label="keyLabel(item.key)"+ :disabled="savingKey === item.key"+ @change="onHighRiskBoolChange(item)"+ />+ </div>+ </t-popconfirm><t-switchv-else-if="item.value_type === 'bool'"v-model="editValues[item.key]"@@ -495,14 +520,14 @@ import {resetUserPassword,type SystemSettingItem,} from '@/api/system'-import {- getAuthConfig,-} from '@/api/auth'+import { getAuthConfig } from '@/api/auth'import { useAuthStore } from '@/stores/auth'+import { useDeploymentCapabilitiesStore } from '@/stores/deploymentCapabilities'import { newPasswordRules, PASSWORD_SPECIAL_CHARS } from '@/utils/passwordPolicy'import { isSettingValueDirty, resolveCurrentSetting } from './systemSettingsEdit'const authStore = useAuthStore()+const deploymentCapabilities = useDeploymentCapabilitiesStore()const currentUserId = computed(() => authStore.currentUserId)const { t, tm, te, locale } = useI18n()@@ -533,12 +558,14 @@ function settingDescription(item: { key: string; description?: string }): string// PUT. ssrf.whitelist is not here — it uses per-tag confirm instead.const HIGH_RISK_KEYS = new Set<string>(['auth.registration_mode',+ 'sandbox.docker_enabled',])const HIGH_IMPACT_KEYS = new Set<string>(['auth.registration_mode','tenant.auto_create_api_key','ssrf.whitelist',+ 'sandbox.docker_enabled',])function isHighRiskKey(key: string): boolean {@@ -638,6 +665,7 @@ const SETTINGS_SECTION_KEYS: Record<Exclude<SettingsSection, 'other'>, readonlytenant: ['tenant.default_storage_quota_gb','tenant.auto_create_api_key',+ 'tenant.auto_accept_invitation',],runtime: ['asynq.core_concurrency',@@ -648,7 +676,7 @@ const SETTINGS_SECTION_KEYS: Record<Exclude<SettingsSection, 'other'>, readonly'asynq.wiki_concurrency','model.max_concurrency',],- security: ['ssrf.whitelist'],+ security: ['ssrf.whitelist', 'sandbox.docker_enabled'],}const activeSettingsSection = ref<SettingsSection>('access')@@ -976,6 +1004,33 @@ async function onHighRiskSelectChange(item: SystemSettingItem) {await persistSetting(currentItem)}+async function onHighRiskBoolChange(item: SystemSettingItem) {+ const currentItem = resolveCurrentSetting(settingsByKey.value, item.key)+ if (!currentItem) return+ const newValue = editValues[item.key]+ if (!isDirty(currentItem)) return++ editValues[item.key] = currentItem.value+ if (newValue !== true) {+ editValues[item.key] = newValue+ await persistSetting(currentItem)+ return+ }++ const ok = await highRiskPopconfirm.ask({+ content: t('system.globalSettings.confirm.bodySandboxDockerEnabled'),+ theme: 'danger',+ confirmBtn: {+ content: t('system.globalSettings.confirm.confirmBtn'),+ theme: 'danger',+ },+ })+ if (!ok) return++ editValues[item.key] = true+ await persistSetting(currentItem)+}+function confirmSsrfListEntryChange(action: 'add' | 'remove',entry: string,@@ -1082,6 +1137,11 @@ function hasBulkAction(item: SystemSettingItem): boolean {return item.key === 'tenant.default_storage_quota_gb'}+async function refreshSandboxDockerCapability(key: string) {+ if (key !== 'sandbox.docker_enabled') return+ await deploymentCapabilities.ensureLoaded(true)+}+function bulkActionConfirmBody(item: SystemSettingItem): string {// Use the canonical (saved) value, not the in-progress edit, so the// operator sees exactly what will be written. The button is disabled@@ -1128,6 +1188,7 @@ async function resetSetting(item: SystemSettingItem) {await loadSettings()markSettingSaved(item)MessagePlugin.success(t('system.globalSettings.reset.success'))+ await refreshSandboxDockerCapability(item.key)} catch (err: any) {const msg = err?.message || t('system.globalSettings.reset.failed')saveAnnouncement.value = msg@@ -1154,6 +1215,7 @@ async function persistSetting(item: SystemSettingItem) {: updated.valuemarkSettingSaved(updated)MessagePlugin.success(t('system.globalSettings.messages.saveSuccess'))+ await refreshSandboxDockerCapability(item.key)} catch (err: any) {const msg = err?.message || t('system.globalSettings.messages.saveFailed')saveAnnouncement.value = msg@@ -1315,46 +1377,60 @@ onUnmounted(() => {font-size: 20px;font-weight: 600;color: var(--td-text-color-primary);- margin: 0 0 8px 0;+ margin: 0;}.section-description {font-size: 14px;color: var(--td-text-color-secondary);- margin: 0;+ margin: 8px 0 0;line-height: 1.5;}}--.settings-intro-panel {- margin-bottom: 18px;- padding: 12px 14px;- border: 1px solid var(--td-component-stroke);- border-radius: 6px;- background: var(--td-bg-color-secondarycontainer);+.section-header__titlewrap {+ display: flex;+ align-items: center;+ gap: 6px;}-.priority-hint-title {- display: flex;+.hint-trigger {+ display: inline-flex;align-items: center;- gap: 7px;- margin-bottom: 8px;- font-size: 13px;- font-weight: 500;- color: var(--td-text-color-secondary);+ justify-content: center;+ padding: 2px;+ border: none;+ border-radius: 4px;+ background: transparent;+ color: var(--td-text-color-placeholder);+ cursor: help;+ line-height: 1;- .t-icon {+ &:hover,+ &:focus-visible {color: var(--td-brand-color);}}-.priority-hint-list {+.hint-popover {+ display: flex;+ flex-direction: column;+ gap: 8px;+}++.hint-popover__title {margin: 0;- padding: 0 0 0 20px;- font-size: 13px;- line-height: 1.65;color: var(--td-text-color-primary);+ font-size: 13px;+ font-weight: 600;+}++.hint-popover__list {+ margin: 0;+ padding: 0 0 0 18px;+ font-size: 12px;+ line-height: 1.6;+ color: var(--td-text-color-secondary);list-style: disc;li + li {@@ -1387,13 +1463,6 @@ onUnmounted(() => {padding: 0 0 12px;border-bottom: 1px solid var(--td-component-stroke);- h3 {- margin: 0 0 4px;- font-size: 16px;- line-height: 1.4;- color: var(--td-text-color-primary);- }-p {margin: 0;font-size: 13px;diff --git a/helm/templates/app.yaml b/helm/templates/app.yamlindex f0e18a22f..d555766a4 100644--- a/helm/templates/app.yaml+++ b/helm/templates/app.yaml@@ -119,6 +119,11 @@ spec:value: {{ .Values.app.env.AUTO_RECOVER_DIRTY | quote }}- name: CONCURRENCY_POOL_SIZEvalue: {{ .Values.app.env.CONCURRENCY_POOL_SIZE | quote }}+ # Docker sandbox is off unless the deployer opts in. A workspace+ # admin who can save a Docker config can create containers on+ # whatever Engine API this process can reach (often host root).+ - name: WEKNORA_SANDBOX_DOCKER_ENABLED+ value: {{ .Values.app.env.WEKNORA_SANDBOX_DOCKER_ENABLED | default "false" | quote }}{{- if .Values.neo4j.enabled }}# Neo4j configuration (for GraphRAG)# NEO4J_ENABLE 是知识图谱的唯一开关(Go 代码认它,不认 ENABLE_GRAPH_RAG)。diff --git a/helm/values.yaml b/helm/values.yamlindex b36ddc686..17a128795 100644--- a/helm/values.yaml+++ b/helm/values.yaml@@ -97,6 +97,10 @@ app:STREAM_MANAGER_TYPE: redisCONCURRENCY_POOL_SIZE: "5"TZ: UTC+ # Docker sandbox talks to a local Engine API (often docker.sock = host root).+ # Leave false unless this is a private single-node install that also mounts+ # the daemon socket or points at a remote tcp:// daemon with TLS.+ WEKNORA_SANDBOX_DOCKER_ENABLED: "false"# -- Additional environment variablesextraEnv: []diff --git a/internal/application/service/system_setting.go b/internal/application/service/system_setting.goindex cd4541e8f..604366e92 100644--- a/internal/application/service/system_setting.go+++ b/internal/application/service/system_setting.go@@ -20,6 +20,7 @@ import ("github.com/Tencent/WeKnora/internal/config""github.com/Tencent/WeKnora/internal/logger""github.com/Tencent/WeKnora/internal/models/limiter"+ "github.com/Tencent/WeKnora/internal/sandbox""github.com/Tencent/WeKnora/internal/types""github.com/Tencent/WeKnora/internal/types/interfaces""github.com/Tencent/WeKnora/internal/utils"@@ -126,6 +127,14 @@ var registry = map[string]settingSpec{Description: "SSRF 防护白名单。可填入 example.com / *.foo.com / 10.0.0.0/8 / 2001:db8::1。" +"修改后立即生效。SSRF_WHITELIST_EXTRA 环境变量仍由部署方维护,不在此处覆盖。",},+ "sandbox.docker_enabled": {+ Type: "bool",+ EnvName: sandbox.DockerBackendEnabledEnv,+ Default: false,+ Category: "security",+ Description: "是否允许 Docker 沙箱后端。本机 docker.sock 等同宿主机 root,默认关闭。" ++ "仅系统管理员可打开;打开后立即生效,无需重启。私有化单机且已挂载 daemon socket,或配置了带 TLS 的远程 tcp:// 时再启用。",+ },"auth.registration_mode": {Type: "string",EnvName: "", // No env fallback — handler passes cfg.Auth.RegistrationMode as default@@ -395,6 +404,7 @@ func (s *systemSettingService) preload(ctx context.Context) {// Add new bridges here as more env vars get migrated.s.applySSRFWhitelist(ctx)s.applyModelMaxConcurrency(ctx)+ s.applyDockerBackendEnabled(ctx)}// encodeDefault produces the JSONB encoding for a spec's built-in@@ -488,6 +498,8 @@ func (s *systemSettingService) dispatchSideEffects(ctx context.Context, changedKs.applySSRFWhitelist(ctx)case "model.max_concurrency":s.applyModelMaxConcurrency(ctx)+ case sandbox.DockerBackendEnabledSettingKey:+ s.applyDockerBackendEnabled(ctx)}}@@ -531,6 +543,12 @@ func (s *systemSettingService) applyModelMaxConcurrency(ctx context.Context) {logger.Infof(ctx, "[system_settings] model.max_concurrency applied (limit=%d)", limit)}+func (s *systemSettingService) applyDockerBackendEnabled(ctx context.Context) {+ enabled := s.GetBool(ctx, sandbox.DockerBackendEnabledSettingKey, sandbox.DockerBackendEnabledEnv, false)+ sandbox.SetDockerBackendEnabled(enabled)+ logger.Infof(ctx, "[system_settings] sandbox.docker_enabled applied (enabled=%v)", enabled)+}+// publishChange fans the change out to peers. Best-effort: a Redis// outage logs a warning but does not fail the Update — the DB write// already succeeded and our local cache is up-to-date. Other replicasdiff --git a/internal/application/service/tenant_sandbox_config.go b/internal/application/service/tenant_sandbox_config.goindex db953584d..77394cc81 100644--- a/internal/application/service/tenant_sandbox_config.go+++ b/internal/application/service/tenant_sandbox_config.go@@ -337,7 +337,11 @@ func SanitizeSandboxConfig(merged := types.MergeSandboxConfigForUpdate(incoming, existing)if merged.SandboxType != "" {- if _, err := sandbox.ParseSandboxType(merged.SandboxType); err != nil {+ parsed, err := sandbox.ParseSandboxType(merged.SandboxType)+ if err != nil {+ return nil, err+ }+ if err := sandbox.EnsureDockerBackendAllowed(parsed); err != nil {return nil, err}}@@ -393,7 +397,7 @@ func validateNamedSandboxBackend(cfg *types.TenantSandboxConfig) error {if !sandbox.IsNamedSandboxBackendType(cfg.SandboxType) {return fmt.Errorf("%w", ErrNamedSandboxBackendUnsupported)}- return nil+ return sandbox.EnsureDockerBackendAllowed(sandbox.SandboxType(cfg.SandboxType))}func filterPublicSandboxConfigs(@@ -575,6 +579,9 @@ func (s *TenantSandboxConfigService) QueryTemplates(merged.E2B.TemplateID = "__catalog__"}case string(sandbox.SandboxTypeDocker):+ if err := sandbox.EnsureDockerBackendAllowed(sandbox.SandboxTypeDocker); err != nil {+ return nil, err+ }// Docker's template is an image, and the catalog step is where the// admin picks one. The standard image stands in until they do, so the// effective-config validation below has something to accept.diff --git a/internal/application/service/tenant_sandbox_config_test.go b/internal/application/service/tenant_sandbox_config_test.goindex 96be778e6..f38ad79f7 100644--- a/internal/application/service/tenant_sandbox_config_test.go+++ b/internal/application/service/tenant_sandbox_config_test.go@@ -1428,6 +1428,9 @@ func TestSanitizeSandboxConfigRefusesSecretsWithoutAESKey(t *testing.T) {require.Error(t, err)// A config without secrets is still allowed in that deployment.+ sandbox.ClearDockerBackendEnabledOverride()+ t.Cleanup(sandbox.ClearDockerBackendEnabledOverride)+ t.Setenv(sandbox.DockerBackendEnabledEnv, "true")_, err = SanitizeSandboxConfig(&types.TenantSandboxConfig{SandboxType: "docker",Docker: &types.DockerSandboxConfig{Image: "weknora:test"},@@ -1442,6 +1445,9 @@ func TestSandboxesStillLiveErrorSupportsErrorsIs(t *testing.T) {}func TestCreateAcceptsDockerNamedSandboxBackend(t *testing.T) {+ sandbox.ClearDockerBackendEnabledOverride()+ t.Cleanup(sandbox.ClearDockerBackendEnabledOverride)+ t.Setenv(sandbox.DockerBackendEnabledEnv, "true")repo := &fakeConfigRepo{}svc := newTestConfigService(t, repo, nil, stubAgentRepo{})@@ -1467,6 +1473,9 @@ func TestCreateRejectsRemovedLocalBackend(t *testing.T) {}func TestCreateRejectsDockerWithoutImage(t *testing.T) {+ sandbox.ClearDockerBackendEnabledOverride()+ t.Cleanup(sandbox.ClearDockerBackendEnabledOverride)+ t.Setenv(sandbox.DockerBackendEnabledEnv, "true")svc := newTestConfigService(t, &fakeConfigRepo{}, nil, stubAgentRepo{})_, err := svc.Create(context.Background(), 7, CreateSandboxConfigInput{@@ -1477,6 +1486,22 @@ func TestCreateRejectsDockerWithoutImage(t *testing.T) {require.ErrorIs(t, err, sandbox.ErrSandboxConfigIncomplete)}+func TestCreateRejectsDockerWhenDisabled(t *testing.T) {+ sandbox.ClearDockerBackendEnabledOverride()+ t.Cleanup(sandbox.ClearDockerBackendEnabledOverride)+ t.Setenv(sandbox.DockerBackendEnabledEnv, "")+ svc := newTestConfigService(t, &fakeConfigRepo{}, nil, stubAgentRepo{})++ _, err := svc.Create(context.Background(), 7, CreateSandboxConfigInput{+ Name: "docker-dev",+ Config: &types.TenantSandboxConfig{+ SandboxType: "docker",+ Docker: &types.DockerSandboxConfig{Image: "weknora:test"},+ },+ })+ require.ErrorIs(t, err, sandbox.ErrDockerBackendDisabled)+}+func TestWorkspaceScriptsDisabledPolicy(t *testing.T) {repo := &fakeConfigRepo{}svc := newTestConfigService(t, repo, nil, stubAgentRepo{})diff --git a/internal/handler/deployment_capabilities.go b/internal/handler/deployment_capabilities.goindex e6d885884..9c8d905a6 100644--- a/internal/handler/deployment_capabilities.go+++ b/internal/handler/deployment_capabilities.go@@ -4,6 +4,7 @@ import ("net/http""strings"+ "github.com/Tencent/WeKnora/internal/sandbox""github.com/gin-gonic/gin")@@ -20,6 +21,7 @@ var DeploymentCapabilityKeys = []string{"settings.vectorstore","settings.storage","settings.sandbox",+ "settings.sandbox.docker",}// DeploymentCapability describes whether a deployment exposes a feature route.@@ -46,6 +48,7 @@ type DeploymentFeatureAvailability struct {VectorStore boolStorage boolSandbox bool+ SandboxDocker bool}func supportedDeploymentCapability(supported bool) DeploymentCapability {@@ -66,19 +69,29 @@ func BuildDeploymentCapabilities(organizations.Reason = "not_supported_in_lite"}+ sandboxDocker := DeploymentCapability{+ Supported: available.Sandbox && available.SandboxDocker,+ }+ if available.Sandbox && !available.SandboxDocker {+ sandboxDocker.Reason = "docker_backend_disabled"+ } else if !available.Sandbox {+ sandboxDocker.Reason = "route_not_registered"+ }+return DeploymentCapabilitiesData{Edition: edition,Capabilities: map[string]DeploymentCapability{- "organizations": organizations,- "agents": supportedDeploymentCapability(available.Agents),- "integrations.im": supportedDeploymentCapability(available.IM),- "integrations.embed": supportedDeploymentCapability(available.Embed),- "integrations.api": supportedDeploymentCapability(available.API),- "settings.mcp": supportedDeploymentCapability(available.MCP),- "settings.websearch": supportedDeploymentCapability(available.WebSearch),- "settings.vectorstore": supportedDeploymentCapability(available.VectorStore),- "settings.storage": supportedDeploymentCapability(available.Storage),- "settings.sandbox": supportedDeploymentCapability(available.Sandbox),+ "organizations": organizations,+ "agents": supportedDeploymentCapability(available.Agents),+ "integrations.im": supportedDeploymentCapability(available.IM),+ "integrations.embed": supportedDeploymentCapability(available.Embed),+ "integrations.api": supportedDeploymentCapability(available.API),+ "settings.mcp": supportedDeploymentCapability(available.MCP),+ "settings.websearch": supportedDeploymentCapability(available.WebSearch),+ "settings.vectorstore": supportedDeploymentCapability(available.VectorStore),+ "settings.storage": supportedDeploymentCapability(available.Storage),+ "settings.sandbox": supportedDeploymentCapability(available.Sandbox),+ "settings.sandbox.docker": sandboxDocker,},}}@@ -99,6 +112,28 @@ func (h *SystemHandler) GetDeploymentCapabilities(c *gin.Context) {c.JSON(http.StatusOK, gin.H{"code": 0,"msg": "success",- "data": h.deploymentCapabilities,+ "data": overlayLiveDockerSandboxCapability(h.deploymentCapabilities),})}++// overlayLiveDockerSandboxCapability replaces the startup snapshot's Docker+// flag with the live 3-tier value so a System Settings toggle is visible+// without restarting the process.+func overlayLiveDockerSandboxCapability(data DeploymentCapabilitiesData) DeploymentCapabilitiesData {+ caps := make(map[string]DeploymentCapability, len(data.Capabilities))+ for key, capability := range data.Capabilities {+ caps[key] = capability+ }+ sandboxCap := caps["settings.sandbox"]+ docker := DeploymentCapability{+ Supported: sandboxCap.Supported && sandbox.DockerBackendEnabled(),+ }+ if sandboxCap.Supported && !docker.Supported {+ docker.Reason = "docker_backend_disabled"+ } else if !sandboxCap.Supported {+ docker.Reason = "route_not_registered"+ }+ caps["settings.sandbox.docker"] = docker+ data.Capabilities = caps+ return data+}diff --git a/internal/handler/deployment_capabilities_test.go b/internal/handler/deployment_capabilities_test.goindex 2b4ff8ecf..c3981c9e6 100644--- a/internal/handler/deployment_capabilities_test.go+++ b/internal/handler/deployment_capabilities_test.go@@ -8,6 +8,8 @@ import ("slices""strings""testing"++ "github.com/Tencent/WeKnora/internal/sandbox")func TestDeploymentCapabilityKeysMatchFrontend(t *testing.T) {@@ -42,6 +44,31 @@ func TestBuildDeploymentCapabilitiesIncludesAllKeys(t *testing.T) {}}+func TestOverlayLiveDockerSandboxCapabilityIgnoresStartupSnapshot(t *testing.T) {+ sandbox.ClearDockerBackendEnabledOverride()+ t.Cleanup(sandbox.ClearDockerBackendEnabledOverride)+ t.Setenv(sandbox.DockerBackendEnabledEnv, "")++ snapshot := BuildDeploymentCapabilities("standard", DeploymentFeatureAvailability{+ Sandbox: true,+ SandboxDocker: true,+ })+ live := overlayLiveDockerSandboxCapability(snapshot)+ docker := live.Capabilities["settings.sandbox.docker"]+ if docker.Supported {+ t.Fatal("live env off must hide docker even if the startup snapshot was on")+ }+ if docker.Reason != "docker_backend_disabled" {+ t.Fatalf("reason = %q, want docker_backend_disabled", docker.Reason)+ }++ t.Setenv(sandbox.DockerBackendEnabledEnv, "true")+ enabled := overlayLiveDockerSandboxCapability(snapshot)+ if !enabled.Capabilities["settings.sandbox.docker"].Supported {+ t.Fatal("live env true must expose docker")+ }+}+func readFrontendDeploymentCapabilityKeys() ([]string, error) {_, thisFile, _, ok := runtime.Caller(0)if !ok {diff --git a/internal/handler/sandbox_config.go b/internal/handler/sandbox_config.goindex 98e4ddcd0..9ec3c2ccf 100644--- a/internal/handler/sandbox_config.go+++ b/internal/handler/sandbox_config.go@@ -201,7 +201,8 @@ func respondSandboxConfigServiceError(c *gin.Context, err error) {stderrors.Is(err, service.ErrNamedSandboxBackendUnsupported),stderrors.Is(err, sandbox.ErrUnsupportedSandboxType),stderrors.Is(err, sandbox.ErrUnsafeOutboundURL),- stderrors.Is(err, sandbox.ErrSandboxConfigIncomplete):+ stderrors.Is(err, sandbox.ErrSandboxConfigIncomplete),+ stderrors.Is(err, sandbox.ErrDockerBackendDisabled):c.Error(apperrors.NewBadRequestError(err.Error()))default:c.Error(err)diff --git a/internal/router/deployment_capabilities.go b/internal/router/deployment_capabilities.goindex 9daffaaac..aab2f63a8 100644--- a/internal/router/deployment_capabilities.go+++ b/internal/router/deployment_capabilities.go@@ -1,6 +1,9 @@package router-import "github.com/Tencent/WeKnora/internal/handler"+import (+ "github.com/Tencent/WeKnora/internal/handler"+ "github.com/Tencent/WeKnora/internal/sandbox"+)func deploymentCapabilitiesFromRouter(params RouterParams) handler.DeploymentCapabilitiesData {return handler.BuildDeploymentCapabilities(handler.Edition, handler.DeploymentFeatureAvailability{@@ -8,12 +11,17 @@ func deploymentCapabilitiesFromRouter(params RouterParams) handler.DeploymentCapAgents: params.CustomAgentHandler != nil,IM: params.IMHandler != nil,// Match RegisterEmbedChannelRoutes: management routes depend on handler only.- Embed: params.EmbedChannelHandler != nil,- API: params.TenantHandler != nil && params.TenantAPIKeyService != nil,- MCP: params.MCPServiceHandler != nil && params.MCPCredentialsHandler != nil && params.MCPOAuthHandler != nil,- WebSearch: params.WebSearchHandler != nil && params.WebSearchProviderHandler != nil && params.WebSearchCredentialsHandler != nil,- VectorStore: params.VectorStoreHandler != nil,- Storage: params.StorageBackendHandler != nil,- Sandbox: params.SandboxConfigHandler != nil,+ Embed: params.EmbedChannelHandler != nil,+ API: params.TenantHandler != nil && params.TenantAPIKeyService != nil,+ MCP: params.MCPServiceHandler != nil &&+ params.MCPCredentialsHandler != nil &&+ params.MCPOAuthHandler != nil,+ WebSearch: params.WebSearchHandler != nil &&+ params.WebSearchProviderHandler != nil &&+ params.WebSearchCredentialsHandler != nil,+ VectorStore: params.VectorStoreHandler != nil,+ Storage: params.StorageBackendHandler != nil,+ Sandbox: params.SandboxConfigHandler != nil,+ SandboxDocker: sandbox.DockerBackendEnabled(),})}diff --git a/internal/router/deployment_capabilities_test.go b/internal/router/deployment_capabilities_test.goindex 041c70692..7363b7379 100644--- a/internal/router/deployment_capabilities_test.go+++ b/internal/router/deployment_capabilities_test.go@@ -40,6 +40,24 @@ func TestBuildDeploymentCapabilitiesHidesOrganizationsInLite(t *testing.T) {}}+func TestBuildDeploymentCapabilitiesHidesDockerUnlessOptedIn(t *testing.T) {+ result := handler.BuildDeploymentCapabilities("standard", allDeploymentFeaturesAvailable())+ docker := result.Capabilities["settings.sandbox.docker"]+ if docker.Supported {+ t.Fatal("docker sandbox must stay disabled until the deployment opts in")+ }+ if docker.Reason != "docker_backend_disabled" {+ t.Fatalf("docker reason = %q, want docker_backend_disabled", docker.Reason)+ }++ available := allDeploymentFeaturesAvailable()+ available.SandboxDocker = true+ enabled := handler.BuildDeploymentCapabilities("standard", available)+ if !enabled.Capabilities["settings.sandbox.docker"].Supported {+ t.Fatal("SandboxDocker true must expose the docker backend")+ }+}+func TestBuildDeploymentCapabilitiesReflectsMissingRoutes(t *testing.T) {available := allDeploymentFeaturesAvailable()available.Embed = falsediff --git a/internal/sandbox/docker_enabled.go b/internal/sandbox/docker_enabled.gonew file mode 100644index 000000000..0d85f9d2c--- /dev/null+++ b/internal/sandbox/docker_enabled.go@@ -0,0 +1,69 @@+package sandbox++import (+ "errors"+ "os"+ "strconv"+ "strings"+ "sync/atomic"+)++// DockerBackendEnabledEnv is the process-level fallback for the Docker+// sandbox backend. System Settings (sandbox.docker_enabled) override it+// when a row has been pushed by SystemSettingService.+//+// A workspace admin who can save a Docker config can create containers on+// whatever Engine API this process can reach — typically the host's+// docker.sock, which is host root. It is therefore off until a+// SystemAdmin or deployer opts in.+const DockerBackendEnabledEnv = "WEKNORA_SANDBOX_DOCKER_ENABLED"++// DockerBackendEnabledSettingKey is the system_settings registry key.+const DockerBackendEnabledSettingKey = "sandbox.docker_enabled"++// ErrDockerBackendDisabled is returned when a Docker sandbox config is saved,+// probed, or resolved and the process has not opted in.+var ErrDockerBackendDisabled = errors.New(+ "sandbox: docker backend is disabled; enable it in System Settings or set WEKNORA_SANDBOX_DOCKER_ENABLED=true",+)++// dockerBackendEnabledOverride is the runtime-tunable source. Nil means+// "SystemSettingService has not pushed yet"; DockerBackendEnabled then+// reads the env, matching the preload window and tests that only Setenv.+var dockerBackendEnabledOverride atomic.Pointer[bool]++// SetDockerBackendEnabled records the resolved 3-tier value (DB > env >+// false). Called at system_settings preload, Update, Reset, and pubsub reload.+func SetDockerBackendEnabled(enabled bool) {+ v := enabled+ dockerBackendEnabledOverride.Store(&v)+}++// ClearDockerBackendEnabledOverride restores env-only resolution. Tests that+// construct SystemSettingService can otherwise leak a preload push into later+// Setenv-based cases in the same package.+func ClearDockerBackendEnabledOverride() {+ dockerBackendEnabledOverride.Store(nil)+}++// DockerBackendEnabled reports whether this process may run the Docker sandbox+// backend. Empty or unparsable env values are false.+func DockerBackendEnabled() bool {+ if p := dockerBackendEnabledOverride.Load(); p != nil {+ return *p+ }+ parsed, err := strconv.ParseBool(strings.TrimSpace(os.Getenv(DockerBackendEnabledEnv)))+ return err == nil && parsed+}++// EnsureDockerBackendAllowed is the choke point for every path that would+// talk to a Docker daemon on behalf of a workspace config.+func EnsureDockerBackendAllowed(t SandboxType) error {+ if t != SandboxTypeDocker {+ return nil+ }+ if DockerBackendEnabled() {+ return nil+ }+ return ErrDockerBackendDisabled+}diff --git a/internal/sandbox/docker_enabled_test.go b/internal/sandbox/docker_enabled_test.gonew file mode 100644index 000000000..b531f4343--- /dev/null+++ b/internal/sandbox/docker_enabled_test.go@@ -0,0 +1,66 @@+package sandbox++import "testing"++func isolateDockerEnabled(t *testing.T) {+ t.Helper()+ ClearDockerBackendEnabledOverride()+ t.Cleanup(ClearDockerBackendEnabledOverride)+}++func TestDockerBackendEnabledDefaultsOff(t *testing.T) {+ isolateDockerEnabled(t)+ t.Setenv(DockerBackendEnabledEnv, "")+ if DockerBackendEnabled() {+ t.Fatal("empty env must leave the docker backend disabled")+ }+ if err := EnsureDockerBackendAllowed(SandboxTypeDocker); err != ErrDockerBackendDisabled {+ t.Fatalf("EnsureDockerBackendAllowed(docker) = %v, want ErrDockerBackendDisabled", err)+ }+ if err := EnsureDockerBackendAllowed(SandboxTypeCube); err != nil {+ t.Fatalf("EnsureDockerBackendAllowed(cube) = %v, want nil", err)+ }+}++func TestDockerBackendEnabledAcceptsParseBoolTrue(t *testing.T) {+ isolateDockerEnabled(t)+ for _, raw := range []string{"true", "TRUE", "1", "t"} {+ t.Run(raw, func(t *testing.T) {+ isolateDockerEnabled(t)+ t.Setenv(DockerBackendEnabledEnv, raw)+ if !DockerBackendEnabled() {+ t.Fatalf("%q should enable the docker backend", raw)+ }+ if err := EnsureDockerBackendAllowed(SandboxTypeDocker); err != nil {+ t.Fatalf("EnsureDockerBackendAllowed(docker) = %v, want nil", err)+ }+ })+ }+}++func TestDockerBackendEnabledRejectsFalsey(t *testing.T) {+ isolateDockerEnabled(t)+ for _, raw := range []string{"false", "0", "no", "yes", "on"} {+ t.Run(raw, func(t *testing.T) {+ isolateDockerEnabled(t)+ t.Setenv(DockerBackendEnabledEnv, raw)+ if DockerBackendEnabled() {+ t.Fatalf("%q must not enable the docker backend", raw)+ }+ })+ }+}++func TestSetDockerBackendEnabledOverridesEnv(t *testing.T) {+ isolateDockerEnabled(t)+ t.Setenv(DockerBackendEnabledEnv, "false")+ SetDockerBackendEnabled(true)+ if !DockerBackendEnabled() {+ t.Fatal("system-settings push must enable even when env is false")+ }+ SetDockerBackendEnabled(false)+ t.Setenv(DockerBackendEnabledEnv, "true")+ if DockerBackendEnabled() {+ t.Fatal("system-settings false must win over env true")+ }+}diff --git a/internal/sandbox/tenant_resolver.go b/internal/sandbox/tenant_resolver.goindex dd3653cc1..594a2c5df 100644--- a/internal/sandbox/tenant_resolver.go+++ b/internal/sandbox/tenant_resolver.go@@ -175,6 +175,9 @@ func (r *tenantSandboxResolver) Resolve(if err != nil {return nil, err}+ if err := EnsureDockerBackendAllowed(effective.Type); err != nil {+ return nil, err+ }switch effective.Type {case SandboxTypeDisabled:@@ -248,6 +251,9 @@ func NewRemoteClientForCheck(cfg *Config) (RemoteSandboxClient, error) {return NewE2BRemoteClientWithPool(cfg, NewSandboxGatewayTransportPoolWithPolicy(nil,OutboundURLPolicy{AllowPrivate: cfg.AllowPrivateEndpoints}))case SandboxTypeDocker:+ if err := EnsureDockerBackendAllowed(SandboxTypeDocker); err != nil {+ return nil, err+ }return NewDockerRemoteClientForCheck(cfg)default:return nil, fmt.Errorf("sandbox: provider %q cannot be probed", cfg.Type)diff --git a/internal/sandbox/tenant_resolver_test.go b/internal/sandbox/tenant_resolver_test.goindex 3813916e6..6316b9306 100644--- a/internal/sandbox/tenant_resolver_test.go+++ b/internal/sandbox/tenant_resolver_test.go@@ -109,6 +109,8 @@ func TestResolveBuildsSessionBoundManagerForDocker(t *testing.T) {// machine running the tests points its docker CLI at: a developer on a// tcp:// daemon would otherwise trip the TLS requirement.t.Setenv("DOCKER_HOST", "unix:///var/run/docker.sock")+ isolateDockerEnabled(t)+ t.Setenv(DockerBackendEnabledEnv, "true")resolver, fallback := newTestResolver(t, &stubTenantConfigLoader{result: ResolvedTenantSandboxConfig{@@ -134,6 +136,29 @@ func TestResolveBuildsSessionBoundManagerForDocker(t *testing.T) {require.NotNil(t, capabilities.SessionFileStore())}+func TestResolveRefusesDockerWhenDisabled(t *testing.T) {+ isolateDockerEnabled(t)+ t.Setenv(DockerBackendEnabledEnv, "false")+ t.Setenv("DOCKER_HOST", "unix:///var/run/docker.sock")++ resolver, _ := newTestResolver(t, &stubTenantConfigLoader{+ result: ResolvedTenantSandboxConfig{+ Config: &types.TenantSandboxConfig{+ SandboxType: "docker",+ Docker: &types.DockerSandboxConfig{+ Image: "wechatopenai/weknora-sandbox:test",+ },+ },+ Found: true,+ },+ })++ mgr, err := resolver.Resolve(context.Background(), 42, "cfg-docker")++ require.Nil(t, mgr)+ require.ErrorIs(t, err, ErrDockerBackendDisabled)+}+// The image is this backend's template. Without it there is nothing to create a// sandbox from, so the config must be refused up front rather than at the first// execution.diff --git a/website-docs/01-getting-started/02-installation.md b/website-docs/01-getting-started/02-installation.mdindex cd67705d6..4df84b142 100644--- a/website-docs/01-getting-started/02-installation.md+++ b/website-docs/01-getting-started/02-installation.md@@ -102,7 +102,7 @@ docker compose up -d| `dex`(含 `full`) | `dex` | 5556 | OIDC 测试用 IdP(配置在 `misc/dex-config.yaml`) || `langfuse`(含 `full`) | `langfuse-db-init`、`langfuse-clickhouse`、`langfuse-minio`、`langfuse-worker`、`langfuse-web` | 3000(UI)/ 9100/9101(专用 MinIO) | 自建 Langfuse 可观测栈,复用 WeKnora 的 postgres(新建 `langfuse` 库)与 redis(DB 1) || `odl-hybrid` | `odl-hybrid` | expose 5002 | OpenDataLoader/Docling PDF 混合解析后端(仅本地构建,配 `DOCREADER_ODL_HYBRID` 使用) |-| `full` | `sandbox`、`mcp` 及上述带 full 标记的服务 | mcp: `${MCP_PORT:-8082}:8000` | `sandbox` 仅用于 build/pull 镜像(`command: ["true"]`,非常驻),app 执行 Skills 时按需 `docker run`;`mcp` 为 MCP Server |+| `full` | `sandbox`、`mcp` 及上述带 full 标记的服务 | mcp: `${MCP_PORT:-8082}:8000` | `sandbox` 仅用于 build/pull 镜像(`command: ["true"]`,非常驻)。Docker 沙箱默认关闭,需设 `WEKNORA_SANDBOX_DOCKER_ENABLED=true` 并挂载 `docker.sock`(等同宿主机 root);Cube/E2B 不依赖本机 daemon。`mcp` 为 MCP Server |app 容器的 `environment` 段落是全量环境变量清单(数据库、向量库、对象存储、Docreader 调优、租户策略、OIDC 等),详见 [04-configuration.md](./04-configuration.md)。diff --git a/website-docs/01-getting-started/04-configuration.md b/website-docs/01-getting-started/04-configuration.mdindex 2839a5f31..f69c960fa 100644--- a/website-docs/01-getting-started/04-configuration.md+++ b/website-docs/01-getting-started/04-configuration.md@@ -250,7 +250,8 @@ AWS S3 的 `S3_ACCESS_KEY` / `S3_SECRET_KEY` 可以**同时留空**,此时走| 名称 | 默认值 | 说明 || --- | --- | --- |-| Sandbox 配置 | 设置页按空间维护 | 后端、凭据、模板、超时和私网访问策略不再读取 `WEKNORA_SANDBOX_*` |+| Sandbox 配置 | 设置页按空间维护 | 后端、凭据、模板、超时和私网访问策略按空间保存 |+| `WEKNORA_SANDBOX_DOCKER_ENABLED` | false | Docker 沙箱后端回退开关。系统管理员也可在「设置 → 系统设置」打开(DB 优先,立即生效)。默认关闭,因为本机 `docker.sock` 等同宿主机 root || `WEKNORA_SKILLS_DIR` | 空(镜像内 /app/skills/preloaded) | 自定义 Skills 目录 || `WEKNORA_AGENT_LLM_TIMEOUT` | 120s | Agent 单次 LLM 调用超时(Go duration 或纯数字秒) || `WEKNORA_AGENT_TOOL_APPROVAL_TIMEOUT` / `_FAIL_OPEN` | 600s / fail-close | MCP 工具人工审批等待与失败策略 |