WeKnora/internal/handler/deployment_capabilities_tes...

142 lines
4.6 KiB
Go
Raw Normal View History

package handler
import (
"os"
"path/filepath"
"regexp"
"runtime"
"slices"
"strings"
"testing"
"github.com/Tencent/WeKnora/internal/sandbox"
feat(sandbox): run unpinned Lite sessions on the host OS sandbox (#3549) * feat(sandbox): resolve workspace paths through WorkspaceLayout Keep remote sessions on the /workspace contract, while file, shell, and artifact code follow the session layout instead of hardcoded paths. * fix(sandbox): fail closed on host layout lookup and restore the shell blacklist Treat host vs remote as an explicit origin, refuse inspect outside ReadRoots, and skip collection when the output tree is missing or equals the project root. * fix(sandbox): close leftover fail-open holes in the layout path Keep host copy, collection, and prompt text from falling back to /workspace when a lookup fails or an adapter returns unclean roots. * fix(sandbox): satisfy golangci-lint on the layout helpers Wrap new copy and test lines to 120 columns, and add the exported comments revive requires. * fix(sandbox): gofmt the read_file layout copy wrap * feat(sandbox): add host as an OS-enforced backend type Host is not a named/pinnable config: each command is a fresh local process, unlike Docker, Cube, and E2B. * feat(session): persist Lite host workspace directory Empty means an auto-allocated folder. Standard edition leaves the column unused so the shared session model still loads. SQLite also gains the tenant skill tables Lite shell_exec already expects. * feat(localsandbox): adapt the host OS sandbox to session interfaces File tools stay outside Seatbelt and are bounded by PathGuard. A revoked project directory fails closed instead of allocating a replacement workspace. * feat(sandbox): run unpinned Lite sessions on the host backend Lite opts into host explicitly; web stays disabled when no named remote config exists. Host workspaces are not destroyed or auto-committed. * feat(desktop): pick and persist host project directories The native folder dialog is the authorization path; typed paths are rejected. settings.sandbox.host tells the client when this edition can use it. * fix(sandbox): fail closed on Lite host layout lookup misses Unpinned host sessions were described as /workspace when pin read or sandbox resolve failed. Prompts and attachment staging now share the same fallback so Lite never pretends the remote tree exists. * fix(frontend): keep settings.sandbox.host in sync with the backend keys TestDeploymentCapabilityKeysMatchFrontend requires the lists to match. Host stays fail-closed like docker so a missed probe does not show Lite-only UI. * fix(lint): satisfy golangci-lint on the host sandbox wiring Check c.Error, wrap lines over 120 columns, put context first on versionsWorkspace, and document exported adapter methods. --------- Co-authored-by: hailongzhao <hailongzhao@tencent.com>
2026-09-22 11:35:03 +00:00
"github.com/stretchr/testify/require"
)
func TestDeploymentCapabilityKeysMatchFrontend(t *testing.T) {
frontendKeys, err := readFrontendDeploymentCapabilityKeys()
if err != nil {
t.Fatalf("read frontend capability keys: %v", err)
}
if !slices.Equal(DeploymentCapabilityKeys, frontendKeys) {
t.Fatalf("backend keys = %#v, frontend keys = %#v", DeploymentCapabilityKeys, frontendKeys)
}
}
func TestBuildDeploymentCapabilitiesIncludesAllKeys(t *testing.T) {
result := BuildDeploymentCapabilities("standard", DeploymentFeatureAvailability{
Organizations: true,
Agents: true,
IM: true,
Embed: true,
API: true,
MCP: true,
WebSearch: true,
VectorStore: true,
Storage: true,
Sandbox: true,
})
for _, key := range DeploymentCapabilityKeys {
if _, ok := result.Capabilities[key]; !ok {
t.Fatalf("missing capability key %q", key)
}
}
}
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 {
return nil, os.ErrInvalid
}
repoRoot := filepath.Clean(filepath.Join(filepath.Dir(thisFile), "..", ".."))
frontendPath := filepath.Join(repoRoot, "frontend", "src", "config", "deploymentCapabilities.ts")
content, err := os.ReadFile(frontendPath)
if err != nil {
return nil, err
}
re := regexp.MustCompile(`(?s)export const DEPLOYMENT_CAPABILITY_KEYS = \[(.*?)\]`)
match := re.FindSubmatch(content)
if len(match) < 2 {
return nil, os.ErrInvalid
}
var keys []string
for _, line := range strings.Split(string(match[1]), "\n") {
line = strings.TrimSpace(strings.TrimRight(line, ","))
if line == "" {
continue
}
line = strings.Trim(line, `'`)
keys = append(keys, line)
}
return keys, nil
}
feat(sandbox): run unpinned Lite sessions on the host OS sandbox (#3549) * feat(sandbox): resolve workspace paths through WorkspaceLayout Keep remote sessions on the /workspace contract, while file, shell, and artifact code follow the session layout instead of hardcoded paths. * fix(sandbox): fail closed on host layout lookup and restore the shell blacklist Treat host vs remote as an explicit origin, refuse inspect outside ReadRoots, and skip collection when the output tree is missing or equals the project root. * fix(sandbox): close leftover fail-open holes in the layout path Keep host copy, collection, and prompt text from falling back to /workspace when a lookup fails or an adapter returns unclean roots. * fix(sandbox): satisfy golangci-lint on the layout helpers Wrap new copy and test lines to 120 columns, and add the exported comments revive requires. * fix(sandbox): gofmt the read_file layout copy wrap * feat(sandbox): add host as an OS-enforced backend type Host is not a named/pinnable config: each command is a fresh local process, unlike Docker, Cube, and E2B. * feat(session): persist Lite host workspace directory Empty means an auto-allocated folder. Standard edition leaves the column unused so the shared session model still loads. SQLite also gains the tenant skill tables Lite shell_exec already expects. * feat(localsandbox): adapt the host OS sandbox to session interfaces File tools stay outside Seatbelt and are bounded by PathGuard. A revoked project directory fails closed instead of allocating a replacement workspace. * feat(sandbox): run unpinned Lite sessions on the host backend Lite opts into host explicitly; web stays disabled when no named remote config exists. Host workspaces are not destroyed or auto-committed. * feat(desktop): pick and persist host project directories The native folder dialog is the authorization path; typed paths are rejected. settings.sandbox.host tells the client when this edition can use it. * fix(sandbox): fail closed on Lite host layout lookup misses Unpinned host sessions were described as /workspace when pin read or sandbox resolve failed. Prompts and attachment staging now share the same fallback so Lite never pretends the remote tree exists. * fix(frontend): keep settings.sandbox.host in sync with the backend keys TestDeploymentCapabilityKeysMatchFrontend requires the lists to match. Host stays fail-closed like docker so a missed probe does not show Lite-only UI. * fix(lint): satisfy golangci-lint on the host sandbox wiring Check c.Error, wrap lines over 120 columns, put context first on versionsWorkspace, and document exported adapter methods. --------- Co-authored-by: hailongzhao <hailongzhao@tencent.com>
2026-09-22 11:35:03 +00:00
func TestHostSandboxCapabilityFollowsAvailability(t *testing.T) {
data := BuildDeploymentCapabilities("lite", DeploymentFeatureAvailability{
Sandbox: true,
SandboxHost: true,
})
require.True(t, data.Capabilities["settings.sandbox.host"].Supported)
off := BuildDeploymentCapabilities("lite", DeploymentFeatureAvailability{
Sandbox: true,
})
require.False(t, off.Capabilities["settings.sandbox.host"].Supported)
require.Equal(t, "platform_unsupported",
off.Capabilities["settings.sandbox.host"].Reason)
}
feat(lite): install and run skills on the host (#3661) * fix(desktop): keep Lite signed in with a stable JWT secret Auto-setup fell through to the login form, and a newly generated signing key replaced the HMAC already used for presigned links. Reuse an existing HMAC, fill only a placeholder JWT secret, and clear a sticky auto-setup failure so the desktop window can enter the local account. * fix(desktop): make wails dev start locally and store uploads at home The dev app has no copied config, and the repo env asks for Redis and the Docker path /data/files. Stay on the repo config, use the in-memory stream manager when Redis is unset, write uploads to ~/.weknora/data/files, and allow dragging the top of the window. * feat(lite): install and run skills on the host instead of a remote sandbox Lite has no sandbox image, so skills are stored under ~/.weknora/skills as version directories with a live symlink, and chats execute them in the host Seatbelt. The settings UI no longer asks which sandbox to install into. The base profile opens /tmp, chat commands may use the network, and a failed ready-write rolls the symlink back to the previous version. * fix(ci): align Lite skill checks with the JWT split and lint limits The desktop signing test still expected the session secret to equal the AES key, and the skill settings source test still looked for the old i18n keys. Wrap the lines golangci-lint rejects so the PR checks can pass. * fix(ci): separate multi-line test helpers for gofumpt gofumpt requires a blank line after a multi-line function. The host skill fakes were still packed together, so lint failed on the first one. * fix(lite): address review findings on host skill install - Ask mode denies network again, and /tmp writes open only with a writable root, so nothing runs unapproved. - Lite still reports and accepts the workspace script switch; the Skills page offers to re-enable it when it is off. - The host process refuses symlinks the installer planted before it clears the install cache or reads the env declaration. - An existing signing or AES key stays the signer and is never copied into signing.key; sessions then get their own jwt.key. - Skill env capture writes under the host target on Lite. - Sweep keeps the previous version and skips skills another process holds the lock for. - Terminal and desktop panels never resolve remote sandboxes on Lite. - A detached install stream resubscribes instead of freezing. - Upload migration follows the bundle name and the old relative path. --------- Co-authored-by: hailongzhao <hailongzhao@tencent.com> Co-authored-by: wizardchen <wizardchen@tencent.com>
2026-09-24 13:30:34 +00:00
func TestRemoteSandboxCapabilityIsOffOnLiteDesktop(t *testing.T) {
on := BuildDeploymentCapabilities("standard", DeploymentFeatureAvailability{Sandbox: true, SandboxRemote: true})
require.True(t, on.Capabilities["settings.sandbox.remote"].Supported)
off := BuildDeploymentCapabilities("lite", DeploymentFeatureAvailability{
Sandbox: true, SandboxRemote: false, SandboxHost: true,
})
require.False(t, off.Capabilities["settings.sandbox.remote"].Supported)
require.Equal(t, "not_supported_in_lite", off.Capabilities["settings.sandbox.remote"].Reason)
none := BuildDeploymentCapabilities("standard", DeploymentFeatureAvailability{})
require.Equal(t, "route_not_registered", none.Capabilities["settings.sandbox.remote"].Reason)
}
feat(sandbox): 双模式沙箱分配的基础(门控关闭,线上行为不变) (#4507) * refactor(sandbox): move workspace layout and path rules into a leaf package internal/sandbox/workspace owns the remote layout (root, input, output, GitDir, skills root) and the lexical path rules. The sandbox root package re-exports them through aliases, so callers keep their imports. No behaviour change. * feat(sandbox): add the allocation domain model Pure types for placing a session: session/user mode, the user-mode admission whitelist (web account or API external user only, with a fixed fallback reason otherwise), the shared-machine identity and its digest, the empty-retention bounds and the deployment gate. * feat(sandbox): add machine and session admission leases Registry of in-flight operations per shared machine and per session, with Redis and in-memory implementations. Leases renew only while still live, report loss at a local deadline measured from the request send time, and Bind cancels a context when any held lease or barrier is lost. Holding or renewing only ever extends the scope key's lifetime. * feat(sandbox): add allocation_mode and empty retention to sandbox configs Configs gain allocation_mode (session|user, default session) and user_sandbox_empty_retention_days (0 = default 7, up to 90). Updates that omit them keep the stored values. Switching a config to user requires the deployment gate (WEKNORA_SANDBOX_USER_ALLOCATION plus Redis), exposed as the settings.sandbox.user_allocation capability. The gate stays closed in this build regardless of the env var: the session manager does not place sessions by their assignment yet, so a user-mode placement would be recorded for a session that still runs on its own machine. * feat(session): record the server-verified owner auth source sessions.owner_auth_source records how user_id was authenticated when the session was created or its owner first bound: web, API direct header or signed token, API key, MCP endpoint, embed, IM, internal. The auth middleware puts the source on the context, CreateSession stamps it and ignores client input, owner binding (MCP ask, embed backfill) records the entry's own source, and a fork inherits it. Rows from before the column stay empty, which means unknown. Per-user sandbox allocation reads it to tell a verified person from a shared entry; the owner's kind follows from the source and user_id, so it is not stored separately. * feat(sandbox): persist session placements and shared-machine registry session_sandbox_assignments records each session's placement once: its config pair, the shared machine digest ('' for a machine of its own), when it was released and when its directory cleanup is due. Mode and layout follow from the digest. sandbox_user_machines holds the identity behind each digest and the empty-retention clock. ClaimPlacement writes the assignment and projects the session pin in one transaction that locks the session row, then the machine row, before inserting. RetireSessions releases assignments under the same locks and writes a tombstone for a session that was never placed, so no placement lands after a deletion began. The repository is also exercised on the schema the shipped SQLite migrations create. * feat(sandbox): place sessions through the allocation service sandboxalloc decides a session's placement on first remote use and records it with the pin: sessions that already used a per-session sandbox stay on it, maintenance sessions are always dedicated, and only an eligible owner on a user-mode config with the gate open shares a machine. A placed session resolves straight from its assignment; a released one is refused. Skill maintenance sessions record a maintenance placement and are removed if that fails. * fix(sandbox): retry placement when the sandbox config cannot be read A failed config load was stored as session mode, so the session could never join a shared machine after the error cleared. * fix(sandbox): satisfy golangci-lint on the allocation foundations Wrap lines past 120 characters, comment exported names, and clear the two staticcheck findings so the pull request lint job can pass. --------- Co-authored-by: hailongzhao <hailongzhao@tencent.com>
2026-10-20 04:28:30 +00:00
func TestBuildDeploymentCapabilitiesUserAllocation(t *testing.T) {
off := BuildDeploymentCapabilities("standard", DeploymentFeatureAvailability{Sandbox: true, SandboxRemote: true})
require.False(t, off.Capabilities["settings.sandbox.user_allocation"].Supported)
require.Equal(t, "deployment_gate_off", off.Capabilities["settings.sandbox.user_allocation"].Reason)
on := BuildDeploymentCapabilities("standard", DeploymentFeatureAvailability{
Sandbox: true, SandboxRemote: true, SandboxUserAllocation: true,
})
require.True(t, on.Capabilities["settings.sandbox.user_allocation"].Supported)
}