From 7d688cb8d360f51ca68e918f4769ff1a20e9202d Mon Sep 17 00:00:00 2001 From: nullptr-error <104547331+nullptr-error@users.noreply.github.com> Date: Mon, 21 Sep 2026 13:24:05 +0800 Subject: [PATCH] feat(localsandbox): add host OS sandbox core and macOS Seatbelt backend (#3472) * feat(localsandbox): add host OS sandbox core and macOS Seatbelt backend Introduce a standalone localsandbox package so Lite can run agent commands on the user's machine under Seatbelt, without linking this into cmd/server or changing remote sandbox behavior. * fix(localsandbox): stop post-wait Kill, deny credential files, and refuse swapped roots Seatbelt was SIGKILL-ing the process group after every successful Wait, credential write denies omitted literal matches for files, PathGuard followed a replaced workspace root, and the login-shell test never ran -lc. * fix(localsandbox): tighten app-data deny, env inherit, and post-wait Kill Keep ask/full from silently widening to auto, stop inheriting host secrets, and make session workspaces survive midnight so the Seatbelt kernel stays fail-closed before adapter wiring. * fix(localsandbox): pass gofmt, errcheck, and revive on the new package CI now lints from the merge base, so the host sandbox needs formatted tests, checked Close() results, and exported comments. * fix(localsandbox): refuse broad workspaces and stop leaking host secrets Keep the host sandbox fail-closed before adapter wiring: home/Users/Volumes cannot be the workspace, login shells no longer re-import rc secrets, and Service applies the env allowlist on every Run. Also close the Lstat TOCTOU and post-wait Kill window. * fix(localsandbox): check Close() in seatbelt spawn tests * fix(localsandbox): deny host temp dirs and refuse leftover wide workspaces file-read* still left /tmp and /var/folders readable, and Build/Relax accepted /private/var, /System/Volumes/Data, and ~/Library/** as a workspace, which re-opened the private deny. Also re-open only ~/.local/bin. --------- Co-authored-by: hailongzhao Co-authored-by: wizardchen --- go.mod | 2 +- internal/agent/tools/shell_env_extract.go | 31 +- internal/localsandbox/aliases.go | 133 +++++ internal/localsandbox/backend_darwin.go | 18 + internal/localsandbox/backend_other.go | 18 + internal/localsandbox/backend_test.go | 19 + internal/localsandbox/backend_windows.go | 10 + internal/localsandbox/core/backend.go | 68 +++ internal/localsandbox/core/backend_test.go | 12 + internal/localsandbox/core/denial.go | 148 +++++ internal/localsandbox/core/denial_test.go | 102 ++++ internal/localsandbox/core/env.go | 108 ++++ internal/localsandbox/core/env_test.go | 61 +++ internal/localsandbox/core/pathguard.go | 128 +++++ internal/localsandbox/core/pathguard_file.go | 177 ++++++ .../localsandbox/core/pathguard_file_other.go | 110 ++++ .../localsandbox/core/pathguard_file_unix.go | 187 +++++++ .../core/pathguard_file_unix_test.go | 141 +++++ .../core/pathguard_fileinfo_unix.go | 59 ++ .../localsandbox/core/pathguard_mtime_unix.go | 13 + internal/localsandbox/core/pathguard_test.go | 112 ++++ internal/localsandbox/core/policy.go | 255 +++++++++ internal/localsandbox/core/policy_builder.go | 309 +++++++++++ .../localsandbox/core/policy_builder_test.go | 336 ++++++++++++ internal/localsandbox/core/policy_test.go | 131 +++++ internal/localsandbox/core/workspace.go | 163 ++++++ internal/localsandbox/core/workspace_test.go | 157 ++++++ internal/localsandbox/rootlock.go | 62 +++ internal/localsandbox/seatbelt/backend.go | 323 +++++++++++ .../localsandbox/seatbelt/backend_test.go | 473 ++++++++++++++++ internal/localsandbox/seatbelt/base.sbpl | 39 ++ internal/localsandbox/seatbelt/compiler.go | 171 ++++++ .../localsandbox/seatbelt/compiler_test.go | 165 ++++++ internal/localsandbox/service.go | 291 ++++++++++ internal/localsandbox/service_test.go | 516 ++++++++++++++++++ internal/localsandbox/winhost/backend.go | 24 + internal/utils/shell_assignment.go | 41 ++ internal/utils/shell_assignment_test.go | 29 + 38 files changed, 5113 insertions(+), 29 deletions(-) create mode 100644 internal/localsandbox/aliases.go create mode 100644 internal/localsandbox/backend_darwin.go create mode 100644 internal/localsandbox/backend_other.go create mode 100644 internal/localsandbox/backend_test.go create mode 100644 internal/localsandbox/backend_windows.go create mode 100644 internal/localsandbox/core/backend.go create mode 100644 internal/localsandbox/core/backend_test.go create mode 100644 internal/localsandbox/core/denial.go create mode 100644 internal/localsandbox/core/denial_test.go create mode 100644 internal/localsandbox/core/env.go create mode 100644 internal/localsandbox/core/env_test.go create mode 100644 internal/localsandbox/core/pathguard.go create mode 100644 internal/localsandbox/core/pathguard_file.go create mode 100644 internal/localsandbox/core/pathguard_file_other.go create mode 100644 internal/localsandbox/core/pathguard_file_unix.go create mode 100644 internal/localsandbox/core/pathguard_file_unix_test.go create mode 100644 internal/localsandbox/core/pathguard_fileinfo_unix.go create mode 100644 internal/localsandbox/core/pathguard_mtime_unix.go create mode 100644 internal/localsandbox/core/pathguard_test.go create mode 100644 internal/localsandbox/core/policy.go create mode 100644 internal/localsandbox/core/policy_builder.go create mode 100644 internal/localsandbox/core/policy_builder_test.go create mode 100644 internal/localsandbox/core/policy_test.go create mode 100644 internal/localsandbox/core/workspace.go create mode 100644 internal/localsandbox/core/workspace_test.go create mode 100644 internal/localsandbox/rootlock.go create mode 100644 internal/localsandbox/seatbelt/backend.go create mode 100644 internal/localsandbox/seatbelt/backend_test.go create mode 100644 internal/localsandbox/seatbelt/base.sbpl create mode 100644 internal/localsandbox/seatbelt/compiler.go create mode 100644 internal/localsandbox/seatbelt/compiler_test.go create mode 100644 internal/localsandbox/service.go create mode 100644 internal/localsandbox/service_test.go create mode 100644 internal/localsandbox/winhost/backend.go create mode 100644 internal/utils/shell_assignment.go create mode 100644 internal/utils/shell_assignment_test.go diff --git a/go.mod b/go.mod index c70e42eb..f41067f7 100644 --- a/go.mod +++ b/go.mod @@ -341,7 +341,7 @@ require ( golang.org/x/arch v0.23.0 // indirect golang.org/x/exp v0.0.0-20260112195511-716be5621a96 // indirect golang.org/x/oauth2 v0.36.0 // indirect - golang.org/x/sys v0.46.0 // indirect + golang.org/x/sys v0.46.0 golang.org/x/telemetry v0.0.0-20260508192327-42602be52be6 // indirect golang.org/x/text v0.38.0 // indirect golang.org/x/tools v0.45.0 // indirect diff --git a/internal/agent/tools/shell_env_extract.go b/internal/agent/tools/shell_env_extract.go index 4ca3171e..08186d1a 100644 --- a/internal/agent/tools/shell_env_extract.go +++ b/internal/agent/tools/shell_env_extract.go @@ -1,28 +1,13 @@ package tools import ( - "regexp" "strings" -) -// assignmentPattern finds NAME=value in a model-built shell command. -// It is not used on user chat text. The name must be UPPER_SNAKE_CASE so -// flags like --model and URLs are not treated as environment variables. -var assignmentPattern = regexp.MustCompile( - `(?:^|[;|&\s])(?:export\s+)?([A-Z_][A-Z0-9_]{0,127})=(?:"([^"]*)"|'([^']*)'|([^\s;|&]+))`, + "github.com/Tencent/WeKnora/internal/utils" ) func extractExportedEnv(command string) map[string]string { - out := map[string]string{} - for _, match := range assignmentPattern.FindAllStringSubmatch(command, -1) { - name := match[1] - value := match[2] + match[3] + match[4] - if name == "" || value == "" { - continue - } - out[name] = value - } - return out + return utils.ExtractShellAssignments(command) } func collectUsedSkillEnv(command string, toolEnv map[string]string) map[string]string { @@ -36,16 +21,6 @@ func collectUsedSkillEnv(command string, toolEnv map[string]string) map[string]s return out } -// maskCommandAssignments replaces the value of every NAME=value assignment with -// a placeholder. A command is logged at Info, and passing a credential inline is -// a documented way to hand a skill its key, so the raw string must never reach -// the log. func maskCommandAssignments(command string) string { - return assignmentPattern.ReplaceAllStringFunc(command, func(match string) string { - eq := strings.Index(match, "=") - if eq < 0 { - return match - } - return match[:eq+1] + "***" - }) + return utils.MaskCommandAssignments(command) } diff --git a/internal/localsandbox/aliases.go b/internal/localsandbox/aliases.go new file mode 100644 index 00000000..444d97a1 --- /dev/null +++ b/internal/localsandbox/aliases.go @@ -0,0 +1,133 @@ +// Package localsandbox runs untrusted commands on the user's own machine +// under OS-enforced restrictions. It is independent of the remote sandbox +// stack in internal/sandbox: the two share no domain model. +package localsandbox + +import "github.com/Tencent/WeKnora/internal/localsandbox/core" + +// The facade re-exports the core contract as aliases (not new types), so a +// core.Policy and a localsandbox.Policy are the same type to the compiler and +// no conversion is ever needed at the boundary. +type ( + // Policy is the platform-neutral permission declaration compiled by a Backend. + Policy = core.Policy + // WritableRoot is one writable subtree plus read-only carve-outs inside it. + WritableRoot = core.WritableRoot + // NetworkMode is the coarse network stance of a Policy. + NetworkMode = core.NetworkMode + // Command is one execution request. + Command = core.Command + // ExitStatus is the platform-neutral outcome of one sandboxed process. + ExitStatus = core.ExitStatus + // Denial is the heuristic verdict on whether a failure came from the sandbox. + Denial = core.Denial + // DenialReason classifies why a sandboxed process is believed to have failed. + DenialReason = core.DenialReason + // Backend is the contract every platform implementation satisfies. + Backend = core.Backend + // Prepared is an opaque handle to one compiled policy. + Prepared = core.Prepared + // Process is a running sandboxed command. + Process = core.Process + // PathGuard validates filesystem access performed by WeKnora itself. + PathGuard = core.PathGuard + // Workspace is where one session's work happens. + Workspace = core.Workspace + // WorkspaceKind distinguishes a user-picked project from a session dir. + WorkspaceKind = core.WorkspaceKind + // WorkspaceResolver maps a session to the directory the agent may work in. + WorkspaceResolver = core.WorkspaceResolver + // ProjectLookup reports whether a session is bound to a user-selected project. + ProjectLookup = core.ProjectLookup + // DirLayout names the roots the resolver allocates under. + DirLayout = core.DirLayout + // ApprovalMode is the user's chosen permission stance for a session. + ApprovalMode = core.ApprovalMode + // PolicyBuilder derives a Policy from an approval mode and a workspace. + PolicyBuilder = core.PolicyBuilder + // Grant is a permission the user has already approved. + Grant = core.Grant +) + +const ( + // NetworkDenied blocks all traffic. Default. + NetworkDenied = core.NetworkDenied + // NetworkLoopback permits only the ports listed in Policy.LoopbackPorts. + NetworkLoopback = core.NetworkLoopback + // NetworkUnrestricted applies no network restriction. + NetworkUnrestricted = core.NetworkUnrestricted + + // ModeAsk reads the workspace but asks before every write or command. + ModeAsk = core.ModeAsk + // ModeAuto works freely inside the workspace. Default and currently shipped. + ModeAuto = core.ModeAuto + // ModeFull runs without any sandbox. Not shipped. + ModeFull = core.ModeFull + + // WorkspaceProject is a directory the user picked. + WorkspaceProject = core.WorkspaceProject + // WorkspaceSession is auto-allocated per session under the session root. + WorkspaceSession = core.WorkspaceSession + + // DenialNone means the failure was not classified as a sandbox denial. + DenialNone = core.DenialNone + // DenialOperationNotPermitted matches "operation not permitted" in process output. + DenialOperationNotPermitted = core.DenialOperationNotPermitted + // DenialPermissionDenied matches "permission denied" in process output. + DenialPermissionDenied = core.DenialPermissionDenied + // DenialReadOnlyFileSystem matches "read-only file system" in process output. + DenialReadOnlyFileSystem = core.DenialReadOnlyFileSystem + // DenialPolicy matches an explicit sandbox marker or a withheld-network failure. + DenialPolicy = core.DenialPolicy +) + +var ( + // ErrUnsupportedPlatform is returned where no OS-enforced sandbox exists. + ErrUnsupportedPlatform = core.ErrUnsupportedPlatform + // ErrFullAccessHasNoPolicy is returned when building a policy for ModeFull. + ErrFullAccessHasNoPolicy = core.ErrFullAccessHasNoPolicy + // ErrApprovalModeNotShipped is returned when Service is asked for an unshipped mode. + ErrApprovalModeNotShipped = core.ErrApprovalModeNotShipped + // ErrPathDenied is returned for every rejected path. + ErrPathDenied = core.ErrPathDenied + // ErrWorkspaceTooBroad is returned when a workspace or grant is too wide. + ErrWorkspaceTooBroad = core.ErrWorkspaceTooBroad +) + +// BuildCommandEnv filters the host environment and overlays explicit vars. +// Adapters must not pass os.Environ(); skill keys belong in the explicit map. +func BuildCommandEnv(explicit map[string]string, extraPATH []string) map[string]string { + return core.BuildCommandEnv(explicit, extraPATH) +} + +// ParseApprovalMode normalizes a stored preference. Unknown values become +// Auto; known-but-unshipped modes are returned unchanged so Service can refuse +// them instead of silently widening access. +func ParseApprovalMode(raw string) ApprovalMode { return core.ParseApprovalMode(raw) } + +// NewPathGuard returns a PathGuard for p. +func NewPathGuard(p Policy) *PathGuard { return core.NewPathGuard(p) } + +// NewPolicyBuilder returns a PolicyBuilder scoped to homeDir and appDataDir. +func NewPolicyBuilder(homeDir, appDataDir string) *PolicyBuilder { + return core.NewPolicyBuilder(homeDir, appDataDir) +} + +// NewWorkspaceResolver returns a WorkspaceResolver for layout and projects. +func NewWorkspaceResolver(layout DirLayout, projects ProjectLookup) WorkspaceResolver { + return core.NewWorkspaceResolver(layout, projects) +} + +// PathUnder reports whether child is inside root after cleaning both paths. +func PathUnder(child, root string) bool { return core.PathUnder(child, root) } + +// ClassifyDenial inspects a failed execution for signs of a sandbox denial. +func ClassifyDenial(status ExitStatus, stdout, stderr string) Denial { + return core.ClassifyDenial(status, stdout, stderr) +} + +// ClassifyRunDenial is the verdict Service acts on, including network denials +// when the policy withheld the network. +func ClassifyRunDenial(p Policy, status ExitStatus, stdout, stderr string) Denial { + return core.ClassifyRunDenial(p, status, stdout, stderr) +} diff --git a/internal/localsandbox/backend_darwin.go b/internal/localsandbox/backend_darwin.go new file mode 100644 index 00000000..0d26b862 --- /dev/null +++ b/internal/localsandbox/backend_darwin.go @@ -0,0 +1,18 @@ +//go:build darwin + +package localsandbox + +import ( + "context" + + "github.com/Tencent/WeKnora/internal/localsandbox/core" + "github.com/Tencent/WeKnora/internal/localsandbox/seatbelt" + "github.com/Tencent/WeKnora/internal/logger" +) + +// NewBackend returns the platform backend. The build tag on this file is the +// only place the OS is selected; no other code may branch on runtime.GOOS. +func NewBackend() (core.Backend, error) { + logger.Infof(context.Background(), "[LocalSandbox] using seatbelt backend") + return seatbelt.New() +} diff --git a/internal/localsandbox/backend_other.go b/internal/localsandbox/backend_other.go new file mode 100644 index 00000000..9a245de4 --- /dev/null +++ b/internal/localsandbox/backend_other.go @@ -0,0 +1,18 @@ +//go:build !darwin && !windows + +package localsandbox + +import ( + "context" + "fmt" + + "github.com/Tencent/WeKnora/internal/localsandbox/core" + "github.com/Tencent/WeKnora/internal/logger" +) + +// NewBackend has no implementation outside macOS and Windows. +func NewBackend() (core.Backend, error) { + err := fmt.Errorf("%w: only macOS is supported today", core.ErrUnsupportedPlatform) + logger.Errorf(context.Background(), "[LocalSandbox] %v", err) + return nil, err +} diff --git a/internal/localsandbox/backend_test.go b/internal/localsandbox/backend_test.go new file mode 100644 index 00000000..76a8efba --- /dev/null +++ b/internal/localsandbox/backend_test.go @@ -0,0 +1,19 @@ +package localsandbox + +import ( + "testing" + + "github.com/stretchr/testify/require" +) + +// Every platform must answer the availability question without panicking and +// without mutating the machine. +func TestNewBackendReportsAvailability(t *testing.T) { + backend, err := NewBackend() + if err != nil { + require.ErrorIs(t, err, ErrUnsupportedPlatform) + return + } + require.NotEmpty(t, backend.Name()) + _ = backend.Available() +} diff --git a/internal/localsandbox/backend_windows.go b/internal/localsandbox/backend_windows.go new file mode 100644 index 00000000..b7ef4385 --- /dev/null +++ b/internal/localsandbox/backend_windows.go @@ -0,0 +1,10 @@ +//go:build windows + +package localsandbox + +import ( + "github.com/Tencent/WeKnora/internal/localsandbox/core" + "github.com/Tencent/WeKnora/internal/localsandbox/winhost" +) + +func NewBackend() (core.Backend, error) { return winhost.New() } diff --git a/internal/localsandbox/core/backend.go b/internal/localsandbox/core/backend.go new file mode 100644 index 00000000..a673221d --- /dev/null +++ b/internal/localsandbox/core/backend.go @@ -0,0 +1,68 @@ +package core + +import ( + "context" + "errors" + "fmt" + "io" +) + +// ErrUnsupportedPlatform is returned by NewBackend where no OS-enforced +// sandbox is implemented. Callers must not fall back to running unsandboxed. +var ErrUnsupportedPlatform = errors.New("localsandbox: no sandbox backend on this platform") + +// Command is one execution request. Argv is passed as a slice rather than a +// command string so paths containing spaces need no quoting anywhere. +type Command struct { + Argv []string + Env map[string]string + Cwd string + Stdin []byte +} + +// Validate reports whether the command has a non-empty argv. +func (c Command) Validate() error { + if len(c.Argv) == 0 || c.Argv[0] == "" { + return fmt.Errorf("localsandbox: command argv is empty") + } + return nil +} + +// Prepared is an opaque handle to one compiled policy. macOS stores the sbpl +// text and its -D parameters; Windows will store a restricted token handle, +// capability SIDs and refreshed ACL state. Callers must not inspect it — that +// opacity is what lets the two platforms differ completely. +type Prepared interface { + // Fingerprint reports which Policy this was prepared from. + Fingerprint() string + // Close releases resources held since preparation. + Close() error +} + +// Process is a running sandboxed command. +type Process interface { + Stdout() io.Reader + Stderr() io.Reader + // Wait blocks until exit. Cancelling ctx terminates the whole process tree. + Wait(ctx context.Context) (ExitStatus, error) + // Kill terminates the whole process tree, not just the root process. + Kill() error + PID() int +} + +// Backend is the contract every platform implementation satisfies. +type Backend interface { + Name() string + // Available reports whether this machine can enforce the sandbox. It must + // not modify anything. + Available() error + // EnsureReady performs one-time installation. No-op on macOS; on Windows + // it will prompt for elevation. + EnsureReady(ctx context.Context) error + // Prepare compiles a policy into its platform-native form. + Prepare(ctx context.Context, p Policy) (Prepared, error) + // Spawn starts a process under a prepared policy. + Spawn(ctx context.Context, prep Prepared, cmd Command) (Process, error) + // TearDown removes persistent state created by EnsureReady. No-op on macOS. + TearDown(ctx context.Context) error +} diff --git a/internal/localsandbox/core/backend_test.go b/internal/localsandbox/core/backend_test.go new file mode 100644 index 00000000..77ddc47a --- /dev/null +++ b/internal/localsandbox/core/backend_test.go @@ -0,0 +1,12 @@ +package core + +import ( + "testing" + + "github.com/stretchr/testify/require" +) + +func TestCommandRequiresArgv(t *testing.T) { + require.Error(t, Command{Cwd: "/tmp"}.Validate()) + require.NoError(t, Command{Argv: []string{"/bin/echo", "hi"}, Cwd: "/tmp"}.Validate()) +} diff --git a/internal/localsandbox/core/denial.go b/internal/localsandbox/core/denial.go new file mode 100644 index 00000000..b17ea660 --- /dev/null +++ b/internal/localsandbox/core/denial.go @@ -0,0 +1,148 @@ +package core + +import ( + "regexp" + "strings" + "time" +) + +// ExitStatus is the platform-neutral outcome of one sandboxed process. +type ExitStatus struct { + Code int + Killed bool + Duration time.Duration +} + +// DenialReason classifies why a sandboxed process is believed to have failed. +type DenialReason int + +const ( + // DenialNone means the failure was not classified as a sandbox denial. + DenialNone DenialReason = iota + // DenialOperationNotPermitted matches "operation not permitted" in process output. + DenialOperationNotPermitted + // DenialPermissionDenied matches "permission denied" in process output. + DenialPermissionDenied + // DenialReadOnlyFileSystem matches "read-only file system" in process output. + DenialReadOnlyFileSystem + // DenialPolicy matches an explicit sandbox marker or a withheld-network failure. + DenialPolicy +) + +// denialSnippetLimit bounds how much output travels with a denial report. +const denialSnippetLimit = 512 + +// Denial is the heuristic verdict on whether a failure came from the sandbox. +// +// The kernel reports nothing structured: a denied process simply fails. This +// classification therefore drives UX decisions (show an approval card) and +// must never be used as a security judgement. +type Denial struct { + Reason DenialReason + // Path is parsed out of the error text; empty when parsing failed. + Path string + Snippet string +} + +// IsDenied reports whether this verdict represents a sandbox denial. +func (d Denial) IsDenied() bool { return d.Reason != DenialNone } + +var denialMarkers = []struct { + needle string + reason DenialReason +}{ + {"operation not permitted", DenialOperationNotPermitted}, + {"permission denied", DenialPermissionDenied}, + {"read-only file system", DenialReadOnlyFileSystem}, + {"sandbox", DenialPolicy}, +} + +// denialPathPattern captures the path preceding a known denial marker, e.g. +// "touch: /a/b: Operation not permitted". +var denialPathPattern = regexp.MustCompile( + `(?i)((?:/|\./|\.\./)[^\s:]*(?:[^\s:]|\\ )*)` + + `\s*:\s*(?:operation not permitted|permission denied|read-only file system)`) + +// ClassifyDenial inspects a failed execution for signs of a sandbox denial. +func ClassifyDenial(status ExitStatus, stdout, stderr string) Denial { + if status.Killed || status.Code == 0 { + return Denial{} + } + // 2 is shell misuse, 126 is "found but not executable", 127 is "not found". + switch status.Code { + case 2, 126, 127: + return Denial{} + } + + combined := stderr + "\n" + stdout + lowered := strings.ToLower(combined) + for _, marker := range denialMarkers { + if !strings.Contains(lowered, marker.needle) { + continue + } + return Denial{ + Reason: marker.reason, + Path: firstDenialPath(combined), + Snippet: truncateSnippet(combined), + } + } + return Denial{} +} + +var networkDenialMarkers = []string{ + "could not resolve host", + "couldn't connect to server", + "could not connect to server", + "connection refused", + "network is unreachable", +} + +// LooksLikeNetworkDenial reports DNS/connect failures that Seatbelt produces +// instead of EPERM when network rules are absent. Callers must only consult +// this when Policy.Network is NetworkDenied; a real DNS failure under +// NetworkUnrestricted is not a sandbox denial. +func LooksLikeNetworkDenial(status ExitStatus, stdout, stderr string) bool { + if status.Killed || status.Code == 0 { + return false + } + switch status.Code { + case 2, 126, 127: + return false + } + lowered := strings.ToLower(stderr + "\n" + stdout) + for _, marker := range networkDenialMarkers { + if strings.Contains(lowered, marker) { + return true + } + } + return false +} + +// ClassifyRunDenial is the verdict the Service acts on. Network denials are +// only considered when the policy actually withheld the network, so a genuine +// DNS outage under NetworkUnrestricted is not mistaken for a sandbox block. +func ClassifyRunDenial(p Policy, status ExitStatus, stdout, stderr string) Denial { + if d := ClassifyDenial(status, stdout, stderr); d.IsDenied() { + return d + } + if p.Network == NetworkDenied && LooksLikeNetworkDenial(status, stdout, stderr) { + return Denial{Reason: DenialPolicy, Snippet: truncateSnippet(stderr + "\n" + stdout)} + } + return Denial{} +} + +func firstDenialPath(output string) string { + match := denialPathPattern.FindStringSubmatch(output) + if len(match) < 2 { + return "" + } + return strings.TrimSpace(match[1]) +} + +func truncateSnippet(output string) string { + trimmed := strings.TrimSpace(output) + if len(trimmed) <= denialSnippetLimit { + return trimmed + } + return trimmed[len(trimmed)-denialSnippetLimit:] +} diff --git a/internal/localsandbox/core/denial_test.go b/internal/localsandbox/core/denial_test.go new file mode 100644 index 00000000..165213c1 --- /dev/null +++ b/internal/localsandbox/core/denial_test.go @@ -0,0 +1,102 @@ +package core + +import ( + "testing" + "time" + + "github.com/stretchr/testify/require" +) + +func TestClassifyDenialIgnoresSuccess(t *testing.T) { + d := ClassifyDenial(ExitStatus{Code: 0}, "", "operation not permitted") + require.Equal(t, DenialNone, d.Reason) + require.False(t, d.IsDenied()) +} + +func TestClassifyDenialDetectsOperationNotPermitted(t *testing.T) { + d := ClassifyDenial(ExitStatus{Code: 1}, "", + "touch: /Users/dev/outside.txt: Operation not permitted") + require.Equal(t, DenialOperationNotPermitted, d.Reason) + require.Equal(t, "/Users/dev/outside.txt", d.Path) +} + +func TestClassifyDenialDetectsPermissionDenied(t *testing.T) { + d := ClassifyDenial(ExitStatus{Code: 1}, "", "bash: /etc/hosts: Permission denied") + require.Equal(t, DenialPermissionDenied, d.Reason) +} + +func TestClassifyDenialDetectsReadOnlyFileSystem(t *testing.T) { + d := ClassifyDenial(ExitStatus{Code: 1}, "", "cannot create: Read-only file system") + require.Equal(t, DenialReadOnlyFileSystem, d.Reason) +} + +// Shell misuse, permission-bit failures and missing commands share exit codes +// with real denials; excluding them keeps the false-positive rate down. +func TestClassifyDenialIgnoresShellMisuseExitCodes(t *testing.T) { + for _, code := range []int{2, 126, 127} { + d := ClassifyDenial(ExitStatus{Code: code}, "", "command not found") + require.Equal(t, DenialNone, d.Reason, "exit code %d", code) + } +} + +func TestClassifyDenialIgnoresUnrelatedFailure(t *testing.T) { + d := ClassifyDenial(ExitStatus{Code: 1}, "", "syntax error near unexpected token") + require.Equal(t, DenialNone, d.Reason) +} + +func TestClassifyDenialTreatsKilledAsNotDenied(t *testing.T) { + d := ClassifyDenial( + ExitStatus{Code: -1, Killed: true, Duration: time.Second}, "", "") + require.Equal(t, DenialNone, d.Reason) +} + +func TestClassifyDenialTruncatesSnippet(t *testing.T) { + long := "" + for i := 0; i < 2000; i++ { + long += "x" + } + d := ClassifyDenial(ExitStatus{Code: 1}, "", long+" Operation not permitted") + require.LessOrEqual(t, len(d.Snippet), denialSnippetLimit) +} + +// curl under NetworkDenied fails at DNS (exit 6) or connect (exit 7), not EPERM. +// ClassifyDenial must leave those alone; Service applies this helper only when +// the policy actually denied the network. +func TestLooksLikeNetworkDenialDetectsCurlDNS(t *testing.T) { + require.True(t, LooksLikeNetworkDenial( + ExitStatus{Code: 6}, + "", + "curl: (6) Could not resolve host: example.com", + )) +} + +func TestLooksLikeNetworkDenialDetectsConnectFailure(t *testing.T) { + require.True(t, LooksLikeNetworkDenial( + ExitStatus{Code: 7}, + "", + "curl: (7) Failed to connect to 127.0.0.1 port 9: Couldn't connect to server", + )) +} + +func TestLooksLikeNetworkDenialIgnoresUnrelatedExitSix(t *testing.T) { + require.False(t, LooksLikeNetworkDenial( + ExitStatus{Code: 1}, + "", + "syntax error near unexpected token", + )) +} + +func TestClassifyRunDenialTreatsBlockedDNSAsDenialWhenNetworkDenied(t *testing.T) { + p := Policy{Network: NetworkDenied} + d := ClassifyRunDenial(p, ExitStatus{Code: 6}, "", + "curl: (6) Could not resolve host: example.com") + require.Equal(t, DenialPolicy, d.Reason) +} + +// The same failure under an unrestricted policy is a real outage, not a block. +func TestClassifyRunDenialIgnoresDNSWhenNetworkAllowed(t *testing.T) { + p := Policy{Network: NetworkUnrestricted} + d := ClassifyRunDenial(p, ExitStatus{Code: 6}, "", + "curl: (6) Could not resolve host: example.com") + require.Equal(t, DenialNone, d.Reason) +} diff --git a/internal/localsandbox/core/env.go b/internal/localsandbox/core/env.go new file mode 100644 index 00000000..f5e9433c --- /dev/null +++ b/internal/localsandbox/core/env.go @@ -0,0 +1,108 @@ +package core + +import ( + "os" + "strings" +) + +// inheritedEnvNames is the host environment the sandbox may see. Anything +// else (AWS_*, GITHUB_TOKEN, DYLD_*, SSH_AUTH_SOCK…) stays in the parent. +var inheritedEnvNames = map[string]struct{}{ + "PATH": {}, "HOME": {}, "USER": {}, "LOGNAME": {}, "SHELL": {}, + "TERM": {}, "LANG": {}, "LC_ALL": {}, "LC_CTYPE": {}, "LC_MESSAGES": {}, + "TZ": {}, +} + +// blockedExplicitEnvNames are never taken from RunRequest.Env. Skill keys +// (AWS_*, *_TOKEN) must still overlay; these are loader-injection knobs. +var blockedExplicitEnvNames = map[string]struct{}{ + "DYLD_INSERT_LIBRARIES": {}, "DYLD_LIBRARY_PATH": {}, "DYLD_FRAMEWORK_PATH": {}, + "LD_PRELOAD": {}, "LD_LIBRARY_PATH": {}, +} + +// FilterInheritedEnv keeps only the allowlisted names from a raw environ. +func FilterInheritedEnv(environ []string) []string { + out := make([]string, 0, len(inheritedEnvNames)) + for _, kv := range environ { + name, _, ok := strings.Cut(kv, "=") + if !ok { + continue + } + if _, allowed := inheritedEnvNames[name]; allowed || strings.HasPrefix(name, "LC_") { + out = append(out, kv) + } + } + return out +} + +// EnvSlice flattens env into NAME=value entries. +func EnvSlice(env map[string]string) []string { + out := make([]string, 0, len(env)) + for k, v := range env { + out = append(out, k+"="+v) + } + return out +} + +// BuildCommandEnv is the Service-layer env contract: start from a filtered +// inherit, overlay the caller's explicit vars, then prepend extra PATH +// entries (toolchain bins). A nil or empty explicit map both mean "no extra +// vars" — they must not wipe PATH. +// +// Explicit keys are the caller's responsibility: this is how skill credentials +// reach the child. Adapters must not pass os.Environ() here. Loader-injection +// names are dropped even when explicit. +func BuildCommandEnv(explicit map[string]string, extraPATH []string) map[string]string { + out := environToMap(FilterInheritedEnv(os.Environ())) + for k, v := range explicit { + if k == "" { + continue + } + if _, blocked := blockedExplicitEnvNames[k]; blocked { + continue + } + out[k] = v + } + if len(extraPATH) > 0 { + out["PATH"] = joinPATH(extraPATH, out["PATH"]) + } + return out +} + +func environToMap(environ []string) map[string]string { + out := make(map[string]string, len(environ)) + for _, kv := range environ { + name, value, ok := strings.Cut(kv, "=") + if !ok || name == "" { + continue + } + out[name] = value + } + return out +} + +func joinPATH(extra []string, existing string) string { + seen := make(map[string]struct{}, len(extra)+8) + parts := make([]string, 0, len(extra)+8) + for _, p := range extra { + if p == "" { + continue + } + if _, ok := seen[p]; ok { + continue + } + seen[p] = struct{}{} + parts = append(parts, p) + } + for _, p := range strings.Split(existing, string(os.PathListSeparator)) { + if p == "" { + continue + } + if _, ok := seen[p]; ok { + continue + } + seen[p] = struct{}{} + parts = append(parts, p) + } + return strings.Join(parts, string(os.PathListSeparator)) +} diff --git a/internal/localsandbox/core/env_test.go b/internal/localsandbox/core/env_test.go new file mode 100644 index 00000000..f687ab55 --- /dev/null +++ b/internal/localsandbox/core/env_test.go @@ -0,0 +1,61 @@ +package core + +import ( + "os" + "strings" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestFilterInheritedEnvDropsSecrets(t *testing.T) { + got := FilterInheritedEnv([]string{ + "PATH=/bin", + "HOME=/Users/dev", + "AWS_SECRET_ACCESS_KEY=super-secret", + "GITHUB_TOKEN=gho_secret", + "LC_CTYPE=UTF-8", + }) + joined := strings.Join(got, "\n") + require.Contains(t, joined, "PATH=/bin") + require.Contains(t, joined, "HOME=/Users/dev") + require.Contains(t, joined, "LC_CTYPE=UTF-8") + require.NotContains(t, joined, "super-secret") + require.NotContains(t, joined, "GITHUB_TOKEN") +} + +func TestBuildCommandEnvEmptyMapKeepsFilteredPATH(t *testing.T) { + t.Setenv("PATH", "/bin:/usr/bin") + t.Setenv("AWS_SECRET_ACCESS_KEY", "super-secret") + + got := BuildCommandEnv(map[string]string{}, nil) + require.Equal(t, "/bin:/usr/bin", got["PATH"]) + _, hasSecret := got["AWS_SECRET_ACCESS_KEY"] + require.False(t, hasSecret) + + gotNil := BuildCommandEnv(nil, nil) + require.Equal(t, got["PATH"], gotNil["PATH"]) +} + +func TestBuildCommandEnvOverlaysExplicitAndPrependsPATH(t *testing.T) { + t.Setenv("PATH", "/bin") + got := BuildCommandEnv(map[string]string{ + "FOO": "bar", + }, []string{"/opt/tools/bin"}) + require.Equal(t, "bar", got["FOO"]) + require.True(t, strings.HasPrefix(got["PATH"], "/opt/tools/bin"+string(os.PathListSeparator))) + require.Contains(t, got["PATH"], "/bin") +} + +func TestBuildCommandEnvDropsLoaderInjectionFromExplicit(t *testing.T) { + got := BuildCommandEnv(map[string]string{ + "AWS_SECRET_ACCESS_KEY": "skill-key", + "DYLD_INSERT_LIBRARIES": "/tmp/evil.dylib", + "LD_PRELOAD": "/tmp/evil.so", + }, nil) + require.Equal(t, "skill-key", got["AWS_SECRET_ACCESS_KEY"]) + _, hasDYLD := got["DYLD_INSERT_LIBRARIES"] + require.False(t, hasDYLD) + _, hasPreload := got["LD_PRELOAD"] + require.False(t, hasPreload) +} diff --git a/internal/localsandbox/core/pathguard.go b/internal/localsandbox/core/pathguard.go new file mode 100644 index 00000000..497eee45 --- /dev/null +++ b/internal/localsandbox/core/pathguard.go @@ -0,0 +1,128 @@ +package core + +import ( + "errors" + "fmt" + "os" + "path/filepath" +) + +// ErrPathDenied is returned for every rejected path. Callers surface it to +// the model as a scope error, so it deliberately carries no distinction +// between "outside the workspace" and "explicitly denied" — telling the +// model which secret paths exist is itself a small leak. +var ErrPathDenied = errors.New("localsandbox: path is outside the permitted workspace") + +// PathGuard validates filesystem access performed by WeKnora itself, which +// runs with the user's full privileges and therefore cannot be constrained by +// the OS sandbox. It derives from the same Policy the backend compiles, so +// both paths enforce the same rules. +// +// Policy.PrivateRoots has no counterpart here on purpose: this guard is an +// allowlist (a read must land under a writable or readable root), so a path +// inside a private subtree that was not re-opened is already refused. The +// Seatbelt profile needs the explicit deny only because its base grants +// blanket file-read*. +type PathGuard struct { + writable []WritableRoot + readable []string + denyRead []string +} + +// NewPathGuard builds a PathGuard from p. The guard copies the policy's path +// lists so later mutations of p do not change enforcement. +func NewPathGuard(p Policy) *PathGuard { + g := &PathGuard{ + writable: append([]WritableRoot(nil), p.WritableRoots...), + readable: append([]string(nil), p.ReadableRoots...), + denyRead: append([]string(nil), p.DenyRead...), + } + return g +} + +// CheckWrite reports whether writing path is permitted after following +// symlinks. It is a policy probe, not a safe I/O primitive: a parent can be +// replaced between this check and a later os.WriteFile. Trusted file tools +// must use WriteFile / ReadFile / MkdirAll / Lstat / CheckDir instead. +func (g *PathGuard) CheckWrite(path string) (string, error) { + resolved, err := g.resolve(path) + if err != nil { + return "", err + } + if g.denied(resolved) { + return "", fmt.Errorf("%w: %q", ErrPathDenied, path) + } + for _, root := range g.writable { + if !PathUnder(resolved, root.Path) { + continue + } + for _, ro := range root.ReadOnlySubpaths { + if PathUnder(resolved, ro) { + return "", fmt.Errorf("%w: %q is read-only", ErrPathDenied, path) + } + } + return resolved, nil + } + return "", fmt.Errorf("%w: %q", ErrPathDenied, path) +} + +// CheckRead returns the resolved absolute path when reading is permitted. +func (g *PathGuard) CheckRead(path string) (string, error) { + resolved, err := g.resolve(path) + if err != nil { + return "", err + } + if g.denied(resolved) { + return "", fmt.Errorf("%w: %q", ErrPathDenied, path) + } + for _, root := range g.writable { + if PathUnder(resolved, root.Path) { + return resolved, nil + } + } + for _, root := range g.readable { + if PathUnder(resolved, root) { + return resolved, nil + } + } + return "", fmt.Errorf("%w: %q", ErrPathDenied, path) +} + +func (g *PathGuard) denied(resolved string) bool { + for _, deny := range g.denyRead { + if PathUnder(resolved, deny) { + return true + } + } + return false +} + +// resolve cleans the path and resolves symlinks. The target may not exist yet +// (a file about to be created), so it resolves the longest existing prefix and +// re-joins the remainder. Resolving only the existing prefix is what stops a +// symlinked parent directory from widening the guard. +func (g *PathGuard) resolve(path string) (string, error) { + if path == "" || !filepath.IsAbs(path) { + return "", fmt.Errorf("%w: %q is not absolute", ErrPathDenied, path) + } + cur := filepath.Clean(path) + remainder := "" + for { + resolved, err := filepath.EvalSymlinks(cur) + if err == nil { + if remainder == "" { + return resolved, nil + } + return filepath.Join(resolved, remainder), nil + } + if !os.IsNotExist(err) { + return "", fmt.Errorf("%w: %q: %v", ErrPathDenied, path, err) + } + parent := filepath.Dir(cur) + if parent == cur { + return "", fmt.Errorf("%w: %q has no existing ancestor", ErrPathDenied, path) + } + remainder = filepath.Join(filepath.Base(cur), remainder) + cur = parent + } +} diff --git a/internal/localsandbox/core/pathguard_file.go b/internal/localsandbox/core/pathguard_file.go new file mode 100644 index 00000000..665c5421 --- /dev/null +++ b/internal/localsandbox/core/pathguard_file.go @@ -0,0 +1,177 @@ +package core + +import ( + "fmt" + "os" + "path/filepath" + "strings" +) + +func cleanAbs(path string) (string, error) { + if path == "" || !filepath.IsAbs(path) { + return "", fmt.Errorf("%w: %q is not absolute", ErrPathDenied, path) + } + return filepath.Clean(path), nil +} + +func relativeInside(root, path string) (string, error) { + rel, err := filepath.Rel(root, path) + if err != nil { + return "", err + } + rel = filepath.Clean(rel) + if rel == "." { + return ".", nil + } + if rel == ".." || strings.HasPrefix(rel, ".."+string(filepath.Separator)) { + return "", ErrPathDenied + } + return rel, nil +} + +func relParts(rel string) []string { + rel = filepath.Clean(rel) + if rel == "." || rel == "" { + return nil + } + return strings.Split(rel, string(filepath.Separator)) +} + +// allowWrite maps path onto one writable root using the lexical path. The +// file I/O helpers then walk that relative path with O_NOFOLLOW so a swapped +// parent cannot smuggle the write outside the workspace. +func (g *PathGuard) allowWrite(path string) (root, rel string, err error) { + path, err = cleanAbs(path) + if err != nil { + return "", "", err + } + if g.denied(path) { + return "", "", fmt.Errorf("%w: %q", ErrPathDenied, path) + } + for _, wr := range g.writable { + if !PathUnder(path, wr.Path) { + continue + } + for _, ro := range wr.ReadOnlySubpaths { + if PathUnder(path, ro) { + return "", "", fmt.Errorf("%w: %q is read-only", ErrPathDenied, path) + } + } + rel, err = relativeInside(wr.Path, path) + if err != nil { + continue + } + return wr.Path, rel, nil + } + return "", "", fmt.Errorf("%w: %q", ErrPathDenied, path) +} + +func (g *PathGuard) allowRead(path string) (root, rel string, err error) { + path, err = cleanAbs(path) + if err != nil { + return "", "", err + } + if g.denied(path) { + return "", "", fmt.Errorf("%w: %q", ErrPathDenied, path) + } + for _, wr := range g.writable { + if !PathUnder(path, wr.Path) { + continue + } + rel, err = relativeInside(wr.Path, path) + if err != nil { + continue + } + return wr.Path, rel, nil + } + for _, readable := range g.readable { + if !PathUnder(path, readable) { + continue + } + rel, err = relativeInside(readable, path) + if err != nil { + continue + } + return readable, rel, nil + } + return "", "", fmt.Errorf("%w: %q", ErrPathDenied, path) +} + +// WriteFile creates or replaces path after walking from a writable root +// without following symlinks. +func (g *PathGuard) WriteFile(path string, data []byte, perm os.FileMode) error { + root, rel, err := g.allowWrite(path) + if err != nil { + return err + } + if rel == "." { + return fmt.Errorf("%w: %q", ErrPathDenied, path) + } + return g.writeRel(root, rel, path, data, perm) +} + +// ReadFile reads path after walking from an allowed root without following +// symlinks. +func (g *PathGuard) ReadFile(path string) ([]byte, error) { + root, rel, err := g.allowRead(path) + if err != nil { + return nil, err + } + return g.readRel(root, rel, path) +} + +// MkdirAll creates path and its parents without following symlinks. +func (g *PathGuard) MkdirAll(path string, perm os.FileMode) error { + root, rel, err := g.allowWrite(path) + if err != nil { + return err + } + return g.mkdirRel(root, rel, path, perm) +} + +// Lstat returns info for path without following a final symlink. +func (g *PathGuard) Lstat(path string) (os.FileInfo, error) { + root, rel, err := g.allowRead(path) + if err != nil { + return nil, err + } + return g.lstatRel(root, rel, path) +} + +// CheckDir returns path after walking from a workspace root without following +// symlinks. Service uses this for work_dir so a swapped parent cannot move +// the child process's cwd outside the workspace. +func (g *PathGuard) CheckDir(path string) (string, error) { + root, rel, err := g.allowDir(path) + if err != nil { + return "", err + } + if err := g.dirRel(root, rel, path); err != nil { + return "", err + } + if rel == "." { + return root, nil + } + return filepath.Join(root, rel), nil +} + +func (g *PathGuard) allowDir(path string) (root, rel string, err error) { + path, err = cleanAbs(path) + if err != nil { + return "", "", err + } + if g.denied(path) { + return "", "", fmt.Errorf("%w: %q", ErrPathDenied, path) + } + for _, wr := range g.writable { + if !PathUnder(path, wr.Path) { + continue + } + rel, err = relativeInside(wr.Path, path) + if err != nil { + continue + } + return wr.Path, rel, nil + } + return "", "", fmt.Errorf("%w: %q", ErrPathDenied, path) +} diff --git a/internal/localsandbox/core/pathguard_file_other.go b/internal/localsandbox/core/pathguard_file_other.go new file mode 100644 index 00000000..79f7e4de --- /dev/null +++ b/internal/localsandbox/core/pathguard_file_other.go @@ -0,0 +1,110 @@ +//go:build !unix + +package core + +import ( + "fmt" + "os" + "path/filepath" +) + +func (g *PathGuard) writeRel(root, rel, orig string, data []byte, perm os.FileMode) error { + target, err := joinNoFollow(root, rel, orig) + if err != nil { + return err + } + if err := os.MkdirAll(filepath.Dir(target), 0o755); err != nil { + return err + } + return os.WriteFile(target, data, perm) +} + +func (g *PathGuard) readRel(root, rel, orig string) ([]byte, error) { + target, err := joinNoFollow(root, rel, orig) + if err != nil { + return nil, err + } + return os.ReadFile(target) +} + +func (g *PathGuard) mkdirRel(root, rel, orig string, perm os.FileMode) error { + target, err := joinNoFollow(root, rel, orig) + if err != nil { + return err + } + return os.MkdirAll(target, perm) +} + +func (g *PathGuard) dirRel(root, rel, orig string) error { + target, err := joinNoFollow(root, rel, orig) + if err != nil { + return err + } + info, err := os.Lstat(target) + if err != nil { + return err + } + if info.Mode()&os.ModeSymlink != 0 || !info.IsDir() { + return fmt.Errorf("%w: %q", ErrPathDenied, orig) + } + return nil +} + +func (g *PathGuard) lstatRel(root, rel, orig string) (os.FileInfo, error) { + if rel == "." { + info, err := os.Lstat(root) + if err != nil { + return nil, err + } + if info.Mode()&os.ModeSymlink != 0 { + return nil, fmt.Errorf("%w: %q", ErrPathDenied, orig) + } + return info, nil + } + parent := filepath.Dir(rel) + if parent != "." { + if _, err := joinNoFollow(root, parent, orig); err != nil { + return nil, err + } + } else { + info, err := os.Lstat(root) + if err != nil { + return nil, err + } + if info.Mode()&os.ModeSymlink != 0 { + return nil, fmt.Errorf("%w: %q", ErrPathDenied, orig) + } + } + return os.Lstat(filepath.Join(root, rel)) +} + +// joinNoFollow lexically joins rel onto root and refuses any component that +// is already a symlink. Host sandbox is not shipped off unix, so this is a +// best-effort stand-in for tests; it cannot close the openat window. +func joinNoFollow(root, rel, orig string) (string, error) { + cur := root + info, err := os.Lstat(cur) + if err != nil { + return "", err + } + if info.Mode()&os.ModeSymlink != 0 { + return "", fmt.Errorf("%w: %q", ErrPathDenied, orig) + } + for _, part := range relParts(rel) { + cur = filepath.Join(cur, part) + info, err = os.Lstat(cur) + if err != nil { + if os.IsNotExist(err) { + continue + } + return "", err + } + if info.Mode()&os.ModeSymlink != 0 { + return "", fmt.Errorf("%w: %q", ErrPathDenied, orig) + } + } + if rel == "." { + return root, nil + } + return filepath.Join(root, rel), nil +} diff --git a/internal/localsandbox/core/pathguard_file_unix.go b/internal/localsandbox/core/pathguard_file_unix.go new file mode 100644 index 00000000..e9fc716a --- /dev/null +++ b/internal/localsandbox/core/pathguard_file_unix.go @@ -0,0 +1,187 @@ +//go:build unix + +package core + +import ( + "errors" + "fmt" + "io" + "os" + "strings" + + "golang.org/x/sys/unix" +) + +func (g *PathGuard) writeRel(root, rel, orig string, data []byte, perm os.FileMode) error { + fd, err := walkOpen(root, rel, true, unix.O_WRONLY|unix.O_CREAT|unix.O_TRUNC, uint32(perm.Perm())) + if err != nil { + return mapWalkErr(orig, err) + } + f := os.NewFile(uintptr(fd), orig) + defer func() { _ = f.Close() }() + n, err := f.Write(data) + if err != nil { + return err + } + if n < len(data) { + return io.ErrShortWrite + } + return nil +} + +func (g *PathGuard) readRel(root, rel, orig string) ([]byte, error) { + fd, err := walkOpen(root, rel, false, unix.O_RDONLY, 0) + if err != nil { + return nil, mapWalkErr(orig, err) + } + f := os.NewFile(uintptr(fd), orig) + defer func() { _ = f.Close() }() + return io.ReadAll(f) +} + +func (g *PathGuard) mkdirRel(root, rel, orig string, perm os.FileMode) error { + if rel == "." { + return nil + } + fd, err := walkOpen(root, rel, true, unix.O_RDONLY|unix.O_DIRECTORY, uint32(perm.Perm())) + if err != nil { + return mapWalkErr(orig, err) + } + return unix.Close(fd) +} + +func (g *PathGuard) dirRel(root, rel, orig string) error { + fd, err := walkOpen(root, rel, false, unix.O_RDONLY|unix.O_DIRECTORY, 0) + if err != nil { + return mapWalkErr(orig, err) + } + return unix.Close(fd) +} + +func (g *PathGuard) lstatRel(root, rel, orig string) (os.FileInfo, error) { + parts := relParts(rel) + if len(parts) == 0 { + info, err := os.Lstat(root) + if err != nil { + return nil, err + } + if info.Mode()&os.ModeSymlink != 0 { + return nil, fmt.Errorf("%w: %q", ErrPathDenied, orig) + } + return info, nil + } + parentRel := strings.Join(parts[:len(parts)-1], string(os.PathSeparator)) + if parentRel == "" { + parentRel = "." + } + fd, err := walkOpen(root, parentRel, false, unix.O_RDONLY|unix.O_DIRECTORY, 0) + if err != nil { + return nil, mapWalkErr(orig, err) + } + defer func() { _ = unix.Close(fd) }() + name := parts[len(parts)-1] + var st unix.Stat_t + if err := unix.Fstatat(fd, name, &st, unix.AT_SYMLINK_NOFOLLOW); err != nil { + return nil, mapWalkErr(orig, err) + } + return fileInfoFromUnixStat(name, st), nil +} + +func walkOpen(root, rel string, mkdir bool, lastFlags int, lastPerm uint32) (int, error) { + parts := relParts(rel) + if len(parts) == 0 { + flags := unix.O_RDONLY | unix.O_DIRECTORY | unix.O_NOFOLLOW | unix.O_CLOEXEC + if !mkdir && lastFlags&unix.O_DIRECTORY == 0 { + flags = lastFlags | unix.O_NOFOLLOW | unix.O_CLOEXEC + } + fd, err := unix.Open(root, flags, lastPerm) + if err != nil { + return -1, mapRootOpenErr(root, err) + } + return fd, nil + } + fd, err := unix.Open(root, unix.O_RDONLY|unix.O_DIRECTORY|unix.O_NOFOLLOW|unix.O_CLOEXEC, 0) + if err != nil { + return -1, mapRootOpenErr(root, err) + } + for i, part := range parts { + if part == "" || part == "." { + continue + } + if part == ".." { + _ = unix.Close(fd) + return -1, ErrPathDenied + } + last := i == len(parts)-1 + if mkdir && (!last || lastFlags&unix.O_DIRECTORY != 0) { + mode := uint32(0o755) + if last && lastPerm != 0 { + mode = lastPerm + } + if err := unix.Mkdirat(fd, part, mode); err != nil && !os.IsExist(err) { + _ = unix.Close(fd) + return -1, err + } + } + flags := unix.O_RDONLY | unix.O_DIRECTORY | unix.O_NOFOLLOW | unix.O_CLOEXEC + perm := uint32(0) + if last { + flags = lastFlags | unix.O_NOFOLLOW | unix.O_CLOEXEC + perm = lastPerm + } + next, err := unix.Openat(fd, part, flags, perm) + if err != nil { + mapped := mapOpenatErr(fd, part, err) + _ = unix.Close(fd) + return -1, mapped + } + _ = unix.Close(fd) + fd = next + } + return fd, nil +} + +func mapRootOpenErr(root string, err error) error { + if err == nil { + return nil + } + if errors.Is(err, unix.ELOOP) { + return ErrPathDenied + } + var st unix.Stat_t + if e := unix.Lstat(root, &st); e == nil { + if st.Mode&unix.S_IFMT == unix.S_IFLNK { + return ErrPathDenied + } + } + return err +} + +func mapOpenatErr(dirfd int, name string, err error) error { + if err == nil { + return nil + } + if errors.Is(err, unix.ELOOP) { + return ErrPathDenied + } + var st unix.Stat_t + if e := unix.Fstatat(dirfd, name, &st, unix.AT_SYMLINK_NOFOLLOW); e == nil { + if st.Mode&unix.S_IFMT == unix.S_IFLNK { + return ErrPathDenied + } + } + return err +} + +func mapWalkErr(path string, err error) error { + if err == nil { + return nil + } + if errors.Is(err, ErrPathDenied) { + return fmt.Errorf("%w: %q", ErrPathDenied, path) + } + if errors.Is(err, unix.ELOOP) { + return fmt.Errorf("%w: %q", ErrPathDenied, path) + } + return err +} diff --git a/internal/localsandbox/core/pathguard_file_unix_test.go b/internal/localsandbox/core/pathguard_file_unix_test.go new file mode 100644 index 00000000..3b8f4c24 --- /dev/null +++ b/internal/localsandbox/core/pathguard_file_unix_test.go @@ -0,0 +1,141 @@ +//go:build unix + +package core + +import ( + "os" + "path/filepath" + "testing" + + "github.com/stretchr/testify/require" +) + +// The file tools run unsandboxed. Check-then-os.WriteFile follows a parent +// that is swapped for a symlink in the window between the two. +func TestPathGuardWriteFileDoesNotFollowReplacedParent(t *testing.T) { + root, g := guardFixture(t) + inner := filepath.Join(root, "out") + require.NoError(t, os.Mkdir(inner, 0o755)) + secrets := filepath.Join(filepath.Dir(root), "secrets") + + resolved, err := g.CheckWrite(filepath.Join(inner, "a.txt")) + require.NoError(t, err) + require.Equal(t, filepath.Join(inner, "a.txt"), resolved) + + require.NoError(t, os.Remove(inner)) + require.NoError(t, os.Symlink(secrets, inner)) + + err = g.WriteFile(filepath.Join(root, "out", "a.txt"), []byte("pwned"), 0o644) + require.ErrorIs(t, err, ErrPathDenied) + + _, statErr := os.Stat(filepath.Join(secrets, "a.txt")) + require.Error(t, statErr) + require.True(t, os.IsNotExist(statErr)) +} + +func TestPathGuardWriteFileDoesNotFollowInWorkspaceSymlink(t *testing.T) { + root, g := guardFixture(t) + realDir := filepath.Join(root, "real") + require.NoError(t, os.Mkdir(realDir, 0o755)) + require.NoError(t, os.Symlink(realDir, filepath.Join(root, "link"))) + + err := g.WriteFile(filepath.Join(root, "link", "x.txt"), []byte("x"), 0o644) + require.ErrorIs(t, err, ErrPathDenied) + _, statErr := os.Stat(filepath.Join(realDir, "x.txt")) + require.True(t, os.IsNotExist(statErr)) +} + +// Seatbelt denies unlinking the workspace directory so it cannot be swapped +// for a symlink. PathGuard still has to refuse if that happens anyway: file +// tools do not run inside sandbox-exec. +func TestPathGuardWriteFileDoesNotFollowReplacedRoot(t *testing.T) { + root, g := guardFixture(t) + outside := filepath.Join(filepath.Dir(root), "outside") + require.NoError(t, os.Mkdir(outside, 0o755)) + + require.NoError(t, os.RemoveAll(root)) + require.NoError(t, os.Symlink(outside, root)) + + err := g.WriteFile(filepath.Join(root, "pwned.txt"), []byte("x"), 0o644) + require.ErrorIs(t, err, ErrPathDenied) + _, statErr := os.Stat(filepath.Join(outside, "pwned.txt")) + require.True(t, os.IsNotExist(statErr)) +} + +func TestPathGuardReadFileDoesNotFollowSymlinkEscape(t *testing.T) { + root, g := guardFixture(t) + secrets := filepath.Join(filepath.Dir(root), "secrets", "id_rsa") + require.NoError(t, os.WriteFile(secrets, []byte("key"), 0o644)) + require.NoError(t, os.Symlink(secrets, filepath.Join(root, "stolen"))) + + _, err := g.ReadFile(filepath.Join(root, "stolen")) + require.ErrorIs(t, err, ErrPathDenied) +} + +func TestPathGuardLstatDoesNotFollowReplacedParent(t *testing.T) { + root, g := guardFixture(t) + inner := filepath.Join(root, "out") + require.NoError(t, os.Mkdir(inner, 0o755)) + require.NoError(t, os.WriteFile(filepath.Join(inner, "a.txt"), []byte("in"), 0o644)) + secrets := filepath.Join(filepath.Dir(root), "secrets") + require.NoError(t, os.WriteFile(filepath.Join(secrets, "a.txt"), []byte("KEY"), 0o644)) + + info, err := g.Lstat(filepath.Join(inner, "a.txt")) + require.NoError(t, err) + require.Equal(t, int64(2), info.Size()) + + require.NoError(t, os.RemoveAll(inner)) + require.NoError(t, os.Symlink(secrets, inner)) + + _, err = g.Lstat(filepath.Join(root, "out", "a.txt")) + require.ErrorIs(t, err, ErrPathDenied) +} + +func TestPathGuardReadFileReadableFileRoot(t *testing.T) { + base, err := filepath.EvalSymlinks(t.TempDir()) + require.NoError(t, err) + root := filepath.Join(base, "My Project") + require.NoError(t, os.MkdirAll(root, 0o755)) + rc := filepath.Join(base, "notes.txt") + require.NoError(t, os.WriteFile(rc, []byte("ok"), 0o644)) + + p := Policy{ + WritableRoots: []WritableRoot{{Path: root}}, + ReadableRoots: []string{rc}, + Cwd: root, + } + require.NoError(t, p.Validate()) + g := NewPathGuard(p) + got, err := g.ReadFile(rc) + require.NoError(t, err) + require.Equal(t, []byte("ok"), got) +} + +func TestPathGuardLstatReportsFinalSymlink(t *testing.T) { + root, g := guardFixture(t) + target := filepath.Join(root, "real.txt") + require.NoError(t, os.WriteFile(target, []byte("hi"), 0o644)) + link := filepath.Join(root, "alias.txt") + require.NoError(t, os.Symlink(target, link)) + + info, err := g.Lstat(link) + require.NoError(t, err) + require.NotZero(t, info.Mode()&os.ModeSymlink) +} + +func TestPathGuardCheckDirDoesNotFollowReplacedParent(t *testing.T) { + root, g := guardFixture(t) + inner := filepath.Join(root, "out") + require.NoError(t, os.Mkdir(inner, 0o755)) + secrets := filepath.Join(filepath.Dir(root), "secrets") + + got, err := g.CheckDir(inner) + require.NoError(t, err) + require.Equal(t, inner, got) + + require.NoError(t, os.Remove(inner)) + require.NoError(t, os.Symlink(secrets, inner)) + + _, err = g.CheckDir(inner) + require.ErrorIs(t, err, ErrPathDenied) +} diff --git a/internal/localsandbox/core/pathguard_fileinfo_unix.go b/internal/localsandbox/core/pathguard_fileinfo_unix.go new file mode 100644 index 00000000..1b97b893 --- /dev/null +++ b/internal/localsandbox/core/pathguard_fileinfo_unix.go @@ -0,0 +1,59 @@ +//go:build unix + +package core + +import ( + "os" + "time" + + "golang.org/x/sys/unix" +) + +type unixFileInfo struct { + name string + size int64 + mode os.FileMode + modTime time.Time + sys unix.Stat_t +} + +func (fi unixFileInfo) Name() string { return fi.name } +func (fi unixFileInfo) Size() int64 { return fi.size } +func (fi unixFileInfo) Mode() os.FileMode { return fi.mode } +func (fi unixFileInfo) ModTime() time.Time { return fi.modTime } +func (fi unixFileInfo) IsDir() bool { return fi.mode.IsDir() } +func (fi unixFileInfo) Sys() any { return &fi.sys } + +func fileInfoFromUnixStat(name string, st unix.Stat_t) os.FileInfo { + mode := os.FileMode(st.Mode & 0o777) + switch st.Mode & unix.S_IFMT { + case unix.S_IFLNK: + mode |= os.ModeSymlink + case unix.S_IFDIR: + mode |= os.ModeDir + case unix.S_IFIFO: + mode |= os.ModeNamedPipe + case unix.S_IFSOCK: + mode |= os.ModeSocket + case unix.S_IFBLK: + mode |= os.ModeDevice + case unix.S_IFCHR: + mode |= os.ModeDevice | os.ModeCharDevice + } + if st.Mode&unix.S_ISUID != 0 { + mode |= os.ModeSetuid + } + if st.Mode&unix.S_ISGID != 0 { + mode |= os.ModeSetgid + } + if st.Mode&unix.S_ISVTX != 0 { + mode |= os.ModeSticky + } + return unixFileInfo{ + name: name, + size: st.Size, + mode: mode, + modTime: statModTime(st), + sys: st, + } +} diff --git a/internal/localsandbox/core/pathguard_mtime_unix.go b/internal/localsandbox/core/pathguard_mtime_unix.go new file mode 100644 index 00000000..2a336d10 --- /dev/null +++ b/internal/localsandbox/core/pathguard_mtime_unix.go @@ -0,0 +1,13 @@ +//go:build unix + +package core + +import ( + "time" + + "golang.org/x/sys/unix" +) + +func statModTime(st unix.Stat_t) time.Time { + return time.Unix(st.Mtim.Sec, st.Mtim.Nsec) +} diff --git a/internal/localsandbox/core/pathguard_test.go b/internal/localsandbox/core/pathguard_test.go new file mode 100644 index 00000000..12b4b42e --- /dev/null +++ b/internal/localsandbox/core/pathguard_test.go @@ -0,0 +1,112 @@ +package core + +import ( + "os" + "path/filepath" + "testing" + + "github.com/stretchr/testify/require" +) + +// guardFixture builds a real on-disk workspace so EvalSymlinks has something +// to resolve. The directory name contains a space on purpose. +func guardFixture(t *testing.T) (root string, g *PathGuard) { + t.Helper() + base, err := filepath.EvalSymlinks(t.TempDir()) + require.NoError(t, err) + + root = filepath.Join(base, "My Project") + require.NoError(t, os.MkdirAll(filepath.Join(root, ".git"), 0o755)) + secrets := filepath.Join(base, "secrets") + require.NoError(t, os.MkdirAll(secrets, 0o755)) + + p := Policy{ + WritableRoots: []WritableRoot{{ + Path: root, + ReadOnlySubpaths: []string{filepath.Join(root, ".git")}, + }}, + DenyRead: []string{secrets}, + Cwd: root, + } + require.NoError(t, p.Validate()) + return root, NewPathGuard(p) +} + +func TestPathGuardAllowsWriteInsideRoot(t *testing.T) { + root, g := guardFixture(t) + got, err := g.CheckWrite(filepath.Join(root, "sub", "new.txt")) + require.NoError(t, err) + require.Equal(t, filepath.Join(root, "sub", "new.txt"), got) +} + +func TestPathGuardRejectsWriteOutsideRoot(t *testing.T) { + root, g := guardFixture(t) + _, err := g.CheckWrite(filepath.Join(filepath.Dir(root), "outside.txt")) + require.ErrorIs(t, err, ErrPathDenied) +} + +func TestPathGuardRejectsWriteToReadOnlySubpath(t *testing.T) { + root, g := guardFixture(t) + _, err := g.CheckWrite(filepath.Join(root, ".git", "config")) + require.ErrorIs(t, err, ErrPathDenied) +} + +func TestPathGuardRejectsDotDotEscape(t *testing.T) { + root, g := guardFixture(t) + _, err := g.CheckWrite(filepath.Join(root, "..", "escaped.txt")) + require.ErrorIs(t, err, ErrPathDenied) +} + +// A symlink inside the workspace pointing out of it must not widen the guard. +func TestPathGuardRejectsSymlinkEscape(t *testing.T) { + root, g := guardFixture(t) + target := filepath.Dir(root) + link := filepath.Join(root, "escape") + require.NoError(t, os.Symlink(target, link)) + + _, err := g.CheckWrite(filepath.Join(link, "pwned.txt")) + require.ErrorIs(t, err, ErrPathDenied) +} + +func TestPathGuardRejectsReadOfDeniedPath(t *testing.T) { + root, g := guardFixture(t) + secrets := filepath.Join(filepath.Dir(root), "secrets", "id_rsa") + _, err := g.CheckRead(secrets) + require.ErrorIs(t, err, ErrPathDenied) +} + +func TestPathGuardAllowsReadOfReadOnlySubpath(t *testing.T) { + root, g := guardFixture(t) + _, err := g.CheckRead(filepath.Join(root, ".git", "config")) + require.NoError(t, err) +} + +func TestPathGuardRejectsRelativePath(t *testing.T) { + _, g := guardFixture(t) + _, err := g.CheckRead("relative/path.txt") + require.ErrorIs(t, err, ErrPathDenied) +} + +func TestPathGuardWriteFileCreatesInsideRoot(t *testing.T) { + root, g := guardFixture(t) + path := filepath.Join(root, "sub", "new.txt") + require.NoError(t, g.WriteFile(path, []byte("hello"), 0o644)) + got, err := os.ReadFile(path) + require.NoError(t, err) + require.Equal(t, []byte("hello"), got) +} + +func TestPathGuardWriteFileRejectsOutsideRoot(t *testing.T) { + root, g := guardFixture(t) + err := g.WriteFile(filepath.Join(filepath.Dir(root), "outside.txt"), []byte("nope"), 0o644) + require.ErrorIs(t, err, ErrPathDenied) +} + +func TestPathGuardReadFileReturnsContents(t *testing.T) { + root, g := guardFixture(t) + path := filepath.Join(root, "notes.txt") + require.NoError(t, os.WriteFile(path, []byte("hi"), 0o644)) + got, err := g.ReadFile(path) + require.NoError(t, err) + require.Equal(t, []byte("hi"), got) +} diff --git a/internal/localsandbox/core/policy.go b/internal/localsandbox/core/policy.go new file mode 100644 index 00000000..d539831f --- /dev/null +++ b/internal/localsandbox/core/policy.go @@ -0,0 +1,255 @@ +// Package core holds the platform-neutral sandbox contract: policy, path +// checks, workspace identity, and denial classification. Platform backends +// live in sibling packages. +package core + +import ( + "crypto/sha256" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "path/filepath" + "runtime" + "sort" + "strings" +) + +// NetworkMode is the coarse network stance. The sandbox layer decides whether +// traffic can leave at all; deciding which hosts are reachable is a proxy's +// job and is out of scope here. +type NetworkMode int + +const ( + // NetworkDenied blocks all traffic. Default. + NetworkDenied NetworkMode = iota + // NetworkLoopback permits only the ports listed in Policy.LoopbackPorts. + NetworkLoopback + // NetworkUnrestricted applies no network restriction. + NetworkUnrestricted +) + +// WritableRoot is one writable subtree plus the read-only carve-outs inside it. +type WritableRoot struct { + // Path is an absolute, cleaned host path. + Path string + // ReadOnlySubpaths sit inside Path but must not be written, typically + // Path/.git. + ReadOnlySubpaths []string +} + +// Policy is the platform-neutral permission declaration. It is a value +// object: comparable by Fingerprint, free of side effects, safe to copy. +type Policy struct { + WritableRoots []WritableRoot + // ReadableRoots are re-opened after PrivateRoots is denied, so this is + // also the list that decides what survives inside a private subtree. + // An entry may name a file (a shell startup script), not just a directory. + ReadableRoots []string + // PrivateRoots are subtrees denied read wholesale — in practice the user's + // home directory. WritableRoots and ReadableRoots are re-opened inside + // them; DenyRead still wins over both. + // + // This exists because macOS cannot enforce a read allowlist for us: the + // base profile must grant blanket file-read* or sandbox-exec aborts the + // child (see seatbelt/base.sbpl). Denying the one subtree that holds the + // user's data is what turns that back into a meaningful boundary. + PrivateRoots []string + DenyRead []string + Network NetworkMode + LoopbackPorts []int + Cwd string +} + +var ( + // ErrNoWritableRoot is returned when a policy names no writable root. + ErrNoWritableRoot = errors.New("localsandbox: policy has no writable root") + // ErrFilesystemRoot is returned when a policy target is "/" or a volume root. + ErrFilesystemRoot = errors.New("localsandbox: a filesystem root cannot be a policy target") + // ErrCwdOutsideRoots is returned when Policy.Cwd is outside every writable root. + ErrCwdOutsideRoots = errors.New("localsandbox: cwd is outside every writable root") + // ErrRelativePath is returned when a policy path is not absolute. + ErrRelativePath = errors.New("localsandbox: policy paths must be absolute") + // ErrDenyReadCoversRoot is returned when a deny-read entry covers a writable root. + ErrDenyReadCoversRoot = errors.New("localsandbox: deny-read entry covers a writable root") + // ErrWorkspaceTooBroad is returned when a workspace or grant is $HOME, + // an ancestor of $HOME, or another well-known wide root. Sandboxing + // those paths would re-open the private home (or every user) as the + // workspace and collapse the read boundary to a credential denylist. + ErrWorkspaceTooBroad = errors.New("localsandbox: workspace is too broad to sandbox") +) + +// wellKnownWideRoots cannot be a workspace, a Relax write grant, or a +// writable root. Exact match only: /tmp/project is fine, /tmp is not. +// /private/var and /System/Volumes/Data are listed separately because they +// are not the same path as /private or /System. +var wellKnownWideRoots = []string{ + "/Users", "/Volumes", "/private", "/tmp", "/var", "/etc", + "/System", "/Library", "/opt", "/home", + "/private/var", "/private/tmp", "/private/etc", + "/var/folders", + "/System/Volumes", "/System/Volumes/Data", +} + +func isWellKnownWideRoot(p string) bool { + if p == "" || !filepath.IsAbs(p) { + return false + } + p = filepath.Clean(p) + for _, wide := range wellKnownWideRoots { + if !filepath.IsAbs(wide) { + continue + } + if PathUnder(p, filepath.Clean(wide)) && PathUnder(filepath.Clean(wide), p) { + return true + } + } + return false +} + +// caseInsensitivePaths reports whether path comparison must ignore case. +// APFS is case-insensitive by default, so this is not a Windows-only concern. +func caseInsensitivePaths() bool { + return runtime.GOOS == "windows" || runtime.GOOS == "darwin" +} + +// isFilesystemRoot reports whether p is "/" or a volume root such as "C:\". +func isFilesystemRoot(p string) bool { + return filepath.Dir(p) == p +} + +// PathUnder reports whether child is root itself or lies beneath it. Both +// arguments must already be absolute and cleaned. +func PathUnder(child, root string) bool { + if child == "" || root == "" { + return false + } + if caseInsensitivePaths() { + child = strings.ToLower(child) + root = strings.ToLower(root) + } + if child == root { + return true + } + if !strings.HasSuffix(root, string(filepath.Separator)) { + root += string(filepath.Separator) + } + return strings.HasPrefix(child, root) +} + +func checkAbsolute(paths ...string) error { + for _, p := range paths { + if p == "" || !filepath.IsAbs(p) || filepath.Clean(p) != p { + return fmt.Errorf("%w: %q", ErrRelativePath, p) + } + } + return nil +} + +// Validate enforces the invariants every backend relies on. +// Ask mode may have no writable roots; cwd must then sit under a readable root. +func (p Policy) Validate() error { + for _, root := range p.WritableRoots { + if err := checkAbsolute(root.Path); err != nil { + return err + } + if isFilesystemRoot(root.Path) { + return fmt.Errorf("%w: writable root %q", ErrFilesystemRoot, root.Path) + } + if isWellKnownWideRoot(root.Path) { + return fmt.Errorf("%w: writable root %q", ErrWorkspaceTooBroad, root.Path) + } + if err := checkAbsolute(root.ReadOnlySubpaths...); err != nil { + return err + } + for _, sub := range root.ReadOnlySubpaths { + if !PathUnder(sub, root.Path) { + return fmt.Errorf( + "localsandbox: read-only subpath %q is outside writable root %q", sub, root.Path) + } + } + } + if err := checkAbsolute(p.ReadableRoots...); err != nil { + return err + } + if err := checkAbsolute(p.PrivateRoots...); err != nil { + return err + } + // A private root covering a writable root is the normal case: the project + // lives in the home directory. Only "/" is refused, because denying it + // would also cut off the system paths exec itself reads. + for _, private := range p.PrivateRoots { + if isFilesystemRoot(private) { + return fmt.Errorf("%w: private root %q", ErrFilesystemRoot, private) + } + } + if err := checkAbsolute(p.DenyRead...); err != nil { + return err + } + for _, deny := range p.DenyRead { + if isFilesystemRoot(deny) { + return fmt.Errorf("%w: deny-read %q", ErrFilesystemRoot, deny) + } + for _, root := range p.WritableRoots { + if PathUnder(root.Path, deny) { + return fmt.Errorf("%w: %q covers %q", ErrDenyReadCoversRoot, deny, root.Path) + } + } + } + if err := checkAbsolute(p.Cwd); err != nil { + return err + } + if len(p.WritableRoots) == 0 { + for _, root := range p.ReadableRoots { + if PathUnder(p.Cwd, root) { + return nil + } + } + return ErrNoWritableRoot + } + for _, root := range p.WritableRoots { + if PathUnder(p.Cwd, root.Path) { + return nil + } + } + return fmt.Errorf("%w: %q", ErrCwdOutsideRoots, p.Cwd) +} + +// Fingerprint is a stable digest used to decide whether an existing Prepared +// still matches the requested policy. Ordering is normalised so that two +// policies describing the same permissions hash identically. +func (p Policy) Fingerprint() string { + norm := p.canonical() + encoded, err := json.Marshal(norm) + if err != nil { + // json.Marshal on this shape cannot fail; keep the signature simple. + panic(fmt.Sprintf("localsandbox: fingerprint encode: %v", err)) + } + sum := sha256.Sum256(encoded) + return hex.EncodeToString(sum[:]) +} + +func (p Policy) canonical() Policy { + out := Policy{ + WritableRoots: make([]WritableRoot, len(p.WritableRoots)), + ReadableRoots: append([]string(nil), p.ReadableRoots...), + PrivateRoots: append([]string(nil), p.PrivateRoots...), + DenyRead: append([]string(nil), p.DenyRead...), + Network: p.Network, + LoopbackPorts: append([]int(nil), p.LoopbackPorts...), + Cwd: p.Cwd, + } + for i, root := range p.WritableRoots { + subs := append([]string(nil), root.ReadOnlySubpaths...) + sort.Strings(subs) + out.WritableRoots[i] = WritableRoot{Path: root.Path, ReadOnlySubpaths: subs} + } + sort.Slice(out.WritableRoots, func(i, j int) bool { + return out.WritableRoots[i].Path < out.WritableRoots[j].Path + }) + sort.Strings(out.ReadableRoots) + sort.Strings(out.PrivateRoots) + sort.Strings(out.DenyRead) + sort.Ints(out.LoopbackPorts) + return out +} diff --git a/internal/localsandbox/core/policy_builder.go b/internal/localsandbox/core/policy_builder.go new file mode 100644 index 00000000..7b090a93 --- /dev/null +++ b/internal/localsandbox/core/policy_builder.go @@ -0,0 +1,309 @@ +package core + +import ( + "errors" + "fmt" + "os" + "path/filepath" + "strings" +) + +// ApprovalMode is the user-facing permission stance for a turn. +type ApprovalMode string + +const ( + // ModeAsk reads the workspace but asks before every write or command. + ModeAsk ApprovalMode = "ask" + // ModeAuto works freely inside the workspace and asks only when a command + // needs to reach outside it. Default. + ModeAuto ApprovalMode = "auto" + // ModeFull runs without any sandbox. + ModeFull ApprovalMode = "full" +) + +// Known reports whether m names one of the three stances at all. +func (m ApprovalMode) Known() bool { + switch m { + case ModeAsk, ModeAuto, ModeFull: + return true + default: + return false + } +} + +// Shipped reports whether this build can serve m end to end. +// +// This is the single source of truth for "which modes exist today", and it +// lives beside the enum rather than in whatever reads the preferences file. +// Both of the other two need machinery above the sandbox that is phase 2: +// ModeAsk compiles to a valid policy with nothing writable and relies on an +// approval round-trip to widen it per command, and ModeFull is by definition +// the absence of a policy. +func (m ApprovalMode) Shipped() bool { + return m == ModeAuto +} + +// ParseApprovalMode normalizes a stored preference. +// +// Unknown values fall back to ModeAuto so a typo cannot stop the agent. +// Known-but-unshipped modes are returned unchanged: mapping ask→auto would +// widen access, and Service refuses a mode it cannot honour. +func ParseApprovalMode(raw string) ApprovalMode { + mode := ApprovalMode(strings.ToLower(strings.TrimSpace(raw))) + if mode.Known() { + return mode + } + return ModeAuto +} + +// ErrFullAccessHasNoPolicy signals that ModeFull is not a wide policy but the +// absence of one. Callers must branch on it explicitly. +var ErrFullAccessHasNoPolicy = errors.New("localsandbox: full access runs without a sandbox policy") + +// ErrApprovalModeNotShipped reports a mode this build cannot enforce. It is a +// refusal, not a downgrade: ModeAsk is stricter than ModeAuto, so quietly +// running the turn under auto would widen access past what was asked for. +var ErrApprovalModeNotShipped = errors.New("localsandbox: approval mode is not available in this build") + +// credentialDirNames are denied last, so they stay denied even when they sit +// inside a directory homeReadableNames re-opened (~/.cargo/credentials.toml is +// the motivating case). +var credentialDirNames = []string{ + ".ssh", ".aws", ".gnupg", ".kube", ".docker", ".npmrc", ".config/gh", + ".netrc", ".git-credentials", ".config/git/credentials", ".pypirc", ".password-store", + ".config/gcloud", ".azure", ".terraform.d", + ".cargo/credentials", ".cargo/credentials.toml", ".gem/credentials", + ".m2/settings.xml", ".gradle/gradle.properties", + "Library/Keychains", +} + +// homeReadableNames are re-opened after the home directory is denied. +// +// Without them the agent cannot run a toolchain the user installed per-user +// (nvm, pyenv, rustup...), which is most of them. The list is deliberately +// about build tooling: it is the smallest set that keeps ordinary development +// working, and anything not on it stays invisible. +var homeReadableNames = []string{ + ".asdf", ".bun", ".cargo", ".deno", ".gem", ".gradle", + ".npm", ".nvm", ".pnpm-store", ".pyenv", ".rbenv", ".rustup", + ".sdkman", ".volta", ".yarn", + // Only the bin dir: ~/.local/share holds app state and tokens. + ".local/bin", +} + +// toolchainBinNames are prepended onto PATH so the agent can run per-user +// toolchains without sourcing shell rc files (those files often hold API keys). +var toolchainBinNames = []string{ + ".cargo/bin", ".local/bin", ".deno/bin", ".bun/bin", + ".pyenv/shims", ".rbenv/shims", ".asdf/shims", ".yarn/bin", +} + +// extraPrivateRoots tighten Seatbelt's blanket file-read* on darwin. +// /Users and /Volumes cover other homes and mounted disks; /tmp and /var +// (plus their /private aliases) cover host temp dirs that hold tokens. +// Seatbelt matches the resolved vnode, so denying /private/tmp also +// blocks /tmp and denying /private/var also blocks /var/folders. +var extraPrivateRoots = []string{ + "/Users", "/Volumes", + "/tmp", "/private/tmp", + "/var", "/private/var", +} + +// platformReadRoots are extra readable paths for Windows / PathGuard. +// Darwin Seatbelt ignores them for availability: the base profile already +// grants unfiltered file-read* (see spec 6.1). Keeping the list makes the +// Policy fingerprint comparable across platforms. +var platformReadRoots = []string{ + "/usr/lib", "/usr/share", "/usr/bin", "/bin", "/sbin", "/usr/sbin", + "/usr/libexec", "/System", "/Library/Apple", "/private/etc", + "/opt/homebrew", "/usr/local", +} + +// PolicyBuilder derives a Policy from an approval mode and a workspace. +type PolicyBuilder struct { + homeDir string + appDataDir string +} + +// NewPolicyBuilder returns a builder scoped to the user's home and app-data dirs. +func NewPolicyBuilder(homeDir, appDataDir string) *PolicyBuilder { + return &PolicyBuilder{ + homeDir: filepath.Clean(homeDir), + appDataDir: filepath.Clean(appDataDir), + } +} + +// Build derives a policy from the mode and the workspace. Pure: no IO, so it +// is directly unit-testable. +func (b *PolicyBuilder) Build(mode ApprovalMode, ws Workspace) (Policy, error) { + if mode == ModeFull { + return Policy{}, ErrFullAccessHasNoPolicy + } + if err := b.rejectBroadWorkspace(ws.Root); err != nil { + return Policy{}, err + } + + p := Policy{ + Network: NetworkDenied, + Cwd: ws.Root, + ReadableRoots: b.readableRoots(ws), + PrivateRoots: b.privateRoots(), + DenyRead: b.denyRead(), + } + + switch mode { + case ModeAuto: + root := WritableRoot{Path: ws.Root} + if ws.ProtectGit { + // Losing .git to a hallucinated rm -rf is unrecoverable, and it is + // the least appropriate thing for an LLM to decide unilaterally. + root.ReadOnlySubpaths = []string{filepath.Join(ws.Root, ".git")} + } + p.WritableRoots = []WritableRoot{root} + case ModeAsk: + // Nothing is writable up front; approved commands are re-prepared + // through Relax. Cwd stays the workspace so the process has a home. + p.WritableRoots = nil + p.Cwd = ws.Root + default: + return Policy{}, fmt.Errorf("localsandbox: unknown approval mode %q", mode) + } + + if err := p.Validate(); err != nil { + return Policy{}, err + } + return p, nil +} + +// privateRoots denies the user's home. Everything the agent legitimately +// needs inside it comes back through readableRoots. +func (b *PolicyBuilder) privateRoots() []string { + var roots []string + if b.homeDir != "" && b.homeDir != string(filepath.Separator) { + roots = append(roots, b.homeDir) + } + for _, extra := range extraPrivateRoots { + cleaned := filepath.Clean(extra) + if !filepath.IsAbs(cleaned) || isFilesystemRoot(cleaned) { + continue + } + if samePath(cleaned, b.homeDir) { + continue + } + roots = append(roots, cleaned) + } + return roots +} + +func (b *PolicyBuilder) readableRoots(ws Workspace) []string { + roots := append([]string(nil), platformReadRoots...) + roots = append(roots, ws.Root) + for _, name := range homeReadableNames { + roots = append(roots, filepath.Join(b.homeDir, filepath.FromSlash(name))) + } + return roots +} + +// ToolchainBins returns existing per-user and platform toolchain directories +// that should be prepended to PATH. It is the substitute for sourcing rc files. +func (b *PolicyBuilder) ToolchainBins() []string { + var out []string + for _, name := range toolchainBinNames { + p := filepath.Join(b.homeDir, filepath.FromSlash(name)) + if info, err := os.Stat(p); err == nil && info.IsDir() { + out = append(out, p) + } + } + if matches, err := filepath.Glob(filepath.Join(b.homeDir, ".nvm", "versions", "node", "*", "bin")); err == nil { + for _, p := range matches { + if info, err := os.Stat(p); err == nil && info.IsDir() { + out = append(out, p) + } + } + } + for _, p := range []string{"/opt/homebrew/bin", "/usr/local/bin"} { + if info, err := os.Stat(p); err == nil && info.IsDir() { + out = append(out, p) + } + } + return out +} + +func (b *PolicyBuilder) rejectBroadWorkspace(root string) error { + root = filepath.Clean(root) + if root == "" || !filepath.IsAbs(root) { + return fmt.Errorf("%w: %q", ErrRelativePath, root) + } + if isFilesystemRoot(root) { + return fmt.Errorf("%w: %q", ErrFilesystemRoot, root) + } + if b.homeDir != "" && b.homeDir != string(filepath.Separator) { + home := filepath.Clean(b.homeDir) + if PathUnder(home, root) { + return fmt.Errorf("%w: %q covers the home directory", ErrWorkspaceTooBroad, root) + } + library := filepath.Join(home, "Library") + if PathUnder(root, library) { + return fmt.Errorf("%w: %q", ErrWorkspaceTooBroad, root) + } + } + if isWellKnownWideRoot(root) { + return fmt.Errorf("%w: %q", ErrWorkspaceTooBroad, root) + } + return nil +} + +func samePath(a, b string) bool { + if a == "" || b == "" { + return false + } + return PathUnder(a, b) && PathUnder(b, a) +} + +func (b *PolicyBuilder) denyRead() []string { + deny := make([]string, 0, len(credentialDirNames)+1) + for _, name := range credentialDirNames { + deny = append(deny, filepath.Join(b.homeDir, filepath.FromSlash(name))) + } + // The whole app-data tree, not just data/: rewriting prefs or keys + // here would let the sandbox lift its own constraints. Validate + // rejects a workspace that sits inside this path. + if b.appDataDir != "" && b.appDataDir != string(filepath.Separator) { + deny = append(deny, b.appDataDir) + } + return deny +} + +// Grant is one approved escalation. +type Grant struct { + WritePath string + AllowNetwork bool +} + +// Relax derives a wider policy after the user approved an escalation. It never +// removes a deny-read entry: those are the only mechanism enforcing them. +func (b *PolicyBuilder) Relax(base Policy, g Grant) (Policy, error) { + out := base + out.WritableRoots = append([]WritableRoot(nil), base.WritableRoots...) + + if g.WritePath != "" { + path := filepath.Clean(g.WritePath) + if err := b.rejectBroadWorkspace(path); err != nil { + return Policy{}, err + } + for _, deny := range base.DenyRead { + if PathUnder(path, deny) { + return Policy{}, fmt.Errorf( + "localsandbox: %q is read-denied and cannot be granted", path) + } + } + out.WritableRoots = append(out.WritableRoots, WritableRoot{Path: path}) + } + if g.AllowNetwork { + out.Network = NetworkUnrestricted + } + if err := out.Validate(); err != nil { + return Policy{}, err + } + return out, nil +} diff --git a/internal/localsandbox/core/policy_builder_test.go b/internal/localsandbox/core/policy_builder_test.go new file mode 100644 index 00000000..7cfa99ff --- /dev/null +++ b/internal/localsandbox/core/policy_builder_test.go @@ -0,0 +1,336 @@ +package core + +import ( + "path/filepath" + "testing" + + "github.com/stretchr/testify/require" +) + +func builderFixture(t *testing.T) (*PolicyBuilder, Workspace) { + t.Helper() + home := filepath.Join(t.TempDir(), "home") + appData := filepath.Join(home, "App Support", "WeKnora Lite") + ws := Workspace{ + Kind: WorkspaceProject, + Root: filepath.Join(home, "My Project"), + ProtectGit: true, + } + return NewPolicyBuilder(home, appData), ws +} + +func TestBuildAutoModeMakesWorkspaceWritable(t *testing.T) { + b, ws := builderFixture(t) + p, err := b.Build(ModeAuto, ws) + require.NoError(t, err) + + require.Equal(t, ws.Root, p.Cwd) + require.Equal(t, NetworkDenied, p.Network) + + var roots []string + for _, r := range p.WritableRoots { + roots = append(roots, r.Path) + } + require.Contains(t, roots, ws.Root) + require.Len(t, roots, 1) +} + +func TestBuildProtectsGitWhenWorkspaceAsksForIt(t *testing.T) { + b, ws := builderFixture(t) + p, err := b.Build(ModeAuto, ws) + require.NoError(t, err) + + for _, r := range p.WritableRoots { + if r.Path == ws.Root { + require.Contains(t, r.ReadOnlySubpaths, filepath.Join(ws.Root, ".git")) + return + } + } + t.Fatal("workspace root missing from policy") +} + +// A session workspace's .git belongs to the agent, so it is not protected. +func TestBuildDoesNotProtectGitForSessionWorkspace(t *testing.T) { + b, ws := builderFixture(t) + ws.Kind = WorkspaceSession + ws.ProtectGit = false + + p, err := b.Build(ModeAuto, ws) + require.NoError(t, err) + for _, r := range p.WritableRoots { + require.Empty(t, r.ReadOnlySubpaths) + } +} + +// Ask mode still compiles a sandbox; approval is enforced above this layer. +func TestBuildAskModeKeepsWorkspaceReadableButNotWritable(t *testing.T) { + b, ws := builderFixture(t) + p, err := b.Build(ModeAsk, ws) + require.NoError(t, err) + + require.Contains(t, p.ReadableRoots, ws.Root) + require.Empty(t, p.WritableRoots) + require.Equal(t, ws.Root, p.Cwd) +} + +// Full access has no policy at all; representing it as a very wide policy +// would invite treating it as "still sandboxed". +// Which modes this build can actually serve is a property of the sandbox, not +// of whatever happens to read the preferences file. One list, here. +func TestApprovalModeShippedIsAutoOnly(t *testing.T) { + require.True(t, ModeAuto.Shipped()) + require.False(t, ModeAsk.Shipped(), "ask needs the approval round-trip") + require.False(t, ModeFull.Shipped(), "full needs the unsandboxed path") + require.False(t, ApprovalMode("yolo").Shipped()) + + require.True(t, ModeAsk.Known(), "ask is a real mode, just not shipped yet") + require.False(t, ApprovalMode("yolo").Known()) +} + +// Unknown values fall back to Auto so a typo cannot stop the agent. +// Known-but-unshipped modes stay themselves: mapping ask→auto would widen +// access past what was asked for, and Service refuses them instead. +func TestParseApprovalModeKeepsKnownModes(t *testing.T) { + require.Equal(t, ModeAuto, ParseApprovalMode("auto")) + require.Equal(t, ModeAuto, ParseApprovalMode(" AUTO ")) + require.Equal(t, ModeAsk, ParseApprovalMode("ask")) + require.Equal(t, ModeFull, ParseApprovalMode("full")) + for _, raw := range []string{"", "yolo"} { + require.Equal(t, ModeAuto, ParseApprovalMode(raw), raw) + } +} + +func TestBuildFullAccessHasNoPolicy(t *testing.T) { + b, ws := builderFixture(t) + _, err := b.Build(ModeFull, ws) + require.ErrorIs(t, err, ErrFullAccessHasNoPolicy) +} + +func TestBuildDeniesReadingCredentialDirectories(t *testing.T) { + b, ws := builderFixture(t) + p, err := b.Build(ModeAuto, ws) + require.NoError(t, err) + + require.Contains(t, p.DenyRead, filepath.Join(b.homeDir, ".ssh")) + require.Contains(t, p.DenyRead, filepath.Join(b.homeDir, ".aws")) + require.Contains(t, p.DenyRead, filepath.Join(b.homeDir, ".config", "git", "credentials")) + require.Contains(t, p.DenyRead, b.appDataDir) +} + +// Seatbelt cannot enforce a read allowlist on darwin (dropping the blanket +// file-read* aborts exec), so the home directory is denied wholesale and the +// few paths a build legitimately needs are re-opened after it. +func TestBuildMakesHomePrivate(t *testing.T) { + b, ws := builderFixture(t) + p, err := b.Build(ModeAuto, ws) + require.NoError(t, err) + + require.Contains(t, p.PrivateRoots, b.homeDir) +} + +// The workspace normally lives inside the home directory, so the private deny +// covers it. It has to be re-opened or the agent cannot read its own files. +func TestBuildReAllowsWorkspaceInsidePrivateHome(t *testing.T) { + b, ws := builderFixture(t) + p, err := b.Build(ModeAuto, ws) + require.NoError(t, err) + + require.True(t, PathUnder(ws.Root, b.homeDir), "fixture must put the workspace in home") + require.Contains(t, p.ReadableRoots, ws.Root) +} + +// Per-user toolchains (nvm, pyenv, cargo) and the login shell's startup files +// live in home. Denying them would leave the agent unable to run node at all. +func TestBuildReAllowsToolchainsButNotShellStartupFiles(t *testing.T) { + b, ws := builderFixture(t) + p, err := b.Build(ModeAuto, ws) + require.NoError(t, err) + + require.Contains(t, p.ReadableRoots, filepath.Join(b.homeDir, ".nvm")) + require.Contains(t, p.ReadableRoots, filepath.Join(b.homeDir, ".cargo")) + require.Contains(t, p.ReadableRoots, filepath.Join(b.homeDir, ".local", "bin")) + require.NotContains(t, p.ReadableRoots, filepath.Join(b.homeDir, ".zshrc")) + require.NotContains(t, p.ReadableRoots, filepath.Join(b.homeDir, ".profile")) + require.NotContains(t, p.ReadableRoots, filepath.Join(b.homeDir, ".cache")) + require.NotContains(t, p.ReadableRoots, filepath.Join(b.homeDir, ".local")) + require.NotContains(t, p.ReadableRoots, filepath.Join(b.homeDir, "Library", "Caches")) +} + +// A re-opened toolchain directory must not carry its credential file back in. +// DenyRead is emitted last, so it wins over the re-allow. +func TestBuildKeepsCredentialsDeniedInsideReAllowedToolchains(t *testing.T) { + b, ws := builderFixture(t) + p, err := b.Build(ModeAuto, ws) + require.NoError(t, err) + + require.Contains(t, p.ReadableRoots, filepath.Join(b.homeDir, ".cargo")) + require.Contains(t, p.DenyRead, filepath.Join(b.homeDir, ".cargo", "credentials.toml")) + require.Contains(t, p.DenyRead, filepath.Join(b.homeDir, "Library", "Keychains")) + require.Contains(t, p.DenyRead, filepath.Join(b.homeDir, ".netrc")) +} + +func TestBuildDoesNotDenyWorkspaceRoot(t *testing.T) { + b, ws := builderFixture(t) + p, err := b.Build(ModeAuto, ws) + require.NoError(t, err) + + for _, deny := range p.DenyRead { + require.False(t, PathUnder(ws.Root, deny), + "workspace %q must not be covered by deny-read %q", ws.Root, deny) + } +} + +func TestBuildIncludesPlatformRuntimeReadRoots(t *testing.T) { + b, ws := builderFixture(t) + p, err := b.Build(ModeAuto, ws) + require.NoError(t, err) + require.Contains(t, p.ReadableRoots, "/usr/lib") +} + +func TestRelaxAddsWritePathAndNetwork(t *testing.T) { + b, ws := builderFixture(t) + base, err := b.Build(ModeAuto, ws) + require.NoError(t, err) + + extra := filepath.Join(b.homeDir, "Other Dir") + relaxed, err := b.Relax(base, Grant{WritePath: extra, AllowNetwork: true}) + require.NoError(t, err) + + var roots []string + for _, r := range relaxed.WritableRoots { + roots = append(roots, r.Path) + } + require.Contains(t, roots, extra) + require.Equal(t, NetworkUnrestricted, relaxed.Network) + require.NotEqual(t, base.Fingerprint(), relaxed.Fingerprint()) +} + +// Relaxation must never be able to unlock a denied credential directory. +func TestRelaxRefusesToGrantDeniedPath(t *testing.T) { + b, ws := builderFixture(t) + base, err := b.Build(ModeAuto, ws) + require.NoError(t, err) + + _, err = b.Relax(base, Grant{WritePath: filepath.Join(b.homeDir, ".ssh")}) + require.Error(t, err) +} + +func TestBuildRefusesHomeAsWorkspace(t *testing.T) { + b, ws := builderFixture(t) + ws.Root = b.homeDir + ws.ProtectGit = true + + _, err := b.Build(ModeAuto, ws) + require.ErrorIs(t, err, ErrWorkspaceTooBroad) +} + +func TestBuildRefusesUsersAsWorkspace(t *testing.T) { + if !filepath.IsAbs("/Users") { + t.Skip("not a unix path layout") + } + b, _ := builderFixture(t) + _, err := b.Build(ModeAuto, Workspace{Kind: WorkspaceProject, Root: "/Users"}) + require.ErrorIs(t, err, ErrWorkspaceTooBroad) +} + +func TestBuildRefusesHomeLibraryAsWorkspace(t *testing.T) { + b, ws := builderFixture(t) + ws.Root = filepath.Join(b.homeDir, "Library") + _, err := b.Build(ModeAuto, ws) + require.ErrorIs(t, err, ErrWorkspaceTooBroad) +} + +func TestBuildMakesOtherUsersAndVolumesPrivate(t *testing.T) { + b, ws := builderFixture(t) + p, err := b.Build(ModeAuto, ws) + require.NoError(t, err) + if filepath.IsAbs("/Users") { + require.Contains(t, p.PrivateRoots, "/Users") + } + if filepath.IsAbs("/Volumes") { + require.Contains(t, p.PrivateRoots, "/Volumes") + } +} + +func TestBuildMakesTempDirsPrivate(t *testing.T) { + b, ws := builderFixture(t) + p, err := b.Build(ModeAuto, ws) + require.NoError(t, err) + for _, root := range []string{"/tmp", "/private/tmp", "/var", "/private/var"} { + if !filepath.IsAbs(root) { + continue + } + require.Contains(t, p.PrivateRoots, filepath.Clean(root), root) + } +} + +func TestBuildRefusesPrivateVarAsWorkspace(t *testing.T) { + if !filepath.IsAbs("/private/var") { + t.Skip("not a unix path layout") + } + b, _ := builderFixture(t) + _, err := b.Build(ModeAuto, Workspace{Kind: WorkspaceProject, Root: "/private/var"}) + require.ErrorIs(t, err, ErrWorkspaceTooBroad) +} + +func TestBuildRefusesVarFoldersAsWorkspace(t *testing.T) { + if !filepath.IsAbs("/var/folders") { + t.Skip("not a unix path layout") + } + b, _ := builderFixture(t) + _, err := b.Build(ModeAuto, Workspace{Kind: WorkspaceProject, Root: "/var/folders"}) + require.ErrorIs(t, err, ErrWorkspaceTooBroad) +} + +func TestBuildRefusesSystemVolumesDataAsWorkspace(t *testing.T) { + if !filepath.IsAbs("/System/Volumes/Data") { + t.Skip("not a unix path layout") + } + b, _ := builderFixture(t) + _, err := b.Build(ModeAuto, Workspace{Kind: WorkspaceProject, Root: "/System/Volumes/Data"}) + require.ErrorIs(t, err, ErrWorkspaceTooBroad) +} + +func TestBuildRefusesHomeLibraryDescendantAsWorkspace(t *testing.T) { + b, ws := builderFixture(t) + ws.Root = filepath.Join(b.homeDir, "Library", "Application Support") + _, err := b.Build(ModeAuto, ws) + require.ErrorIs(t, err, ErrWorkspaceTooBroad) +} + +func TestRelaxRefusesHomeWriteGrant(t *testing.T) { + b, ws := builderFixture(t) + base, err := b.Build(ModeAuto, ws) + require.NoError(t, err) + + _, err = b.Relax(base, Grant{WritePath: b.homeDir}) + require.ErrorIs(t, err, ErrWorkspaceTooBroad) +} + +func TestRelaxRefusesHomeLibraryDescendant(t *testing.T) { + b, ws := builderFixture(t) + base, err := b.Build(ModeAuto, ws) + require.NoError(t, err) + + _, err = b.Relax(base, Grant{WritePath: filepath.Join(b.homeDir, "Library", "Application Support")}) + require.ErrorIs(t, err, ErrWorkspaceTooBroad) +} + +func TestBuildRefusesWorkspaceInsideAppData(t *testing.T) { + b, _ := builderFixture(t) + ws := Workspace{ + Kind: WorkspaceSession, + Root: filepath.Join(b.appDataDir, "sessions", "s1"), + } + _, err := b.Build(ModeAuto, ws) + require.ErrorIs(t, err, ErrDenyReadCoversRoot) +} + +func TestRelaxRefusesToGrantAppData(t *testing.T) { + b, ws := builderFixture(t) + base, err := b.Build(ModeAuto, ws) + require.NoError(t, err) + + _, err = b.Relax(base, Grant{WritePath: b.appDataDir}) + require.Error(t, err) +} diff --git a/internal/localsandbox/core/policy_test.go b/internal/localsandbox/core/policy_test.go new file mode 100644 index 00000000..dfbd9db0 --- /dev/null +++ b/internal/localsandbox/core/policy_test.go @@ -0,0 +1,131 @@ +package core + +import ( + "path/filepath" + "testing" + + "github.com/stretchr/testify/require" +) + +func validPolicy() Policy { + return Policy{ + WritableRoots: []WritableRoot{{ + Path: "/Users/dev/My Project", + ReadOnlySubpaths: []string{"/Users/dev/My Project/.git"}, + }}, + ReadableRoots: []string{"/usr/lib"}, + DenyRead: []string{"/Users/dev/.ssh"}, + Network: NetworkDenied, + Cwd: "/Users/dev/My Project", + } +} + +func TestPolicyValidateAcceptsPathsWithSpaces(t *testing.T) { + require.NoError(t, validPolicy().Validate()) +} + +func TestPolicyValidateRejectsNoWritableRoot(t *testing.T) { + p := validPolicy() + p.WritableRoots = nil + require.ErrorIs(t, p.Validate(), ErrNoWritableRoot) +} + +func TestPolicyValidateAcceptsAskModeWithCwdUnderReadableRoot(t *testing.T) { + p := validPolicy() + p.WritableRoots = nil + p.ReadableRoots = append(p.ReadableRoots, p.Cwd) + require.NoError(t, p.Validate()) +} + +func TestPathUnderRejectsEmptyRoot(t *testing.T) { + require.False(t, PathUnder("/Users/dev/file", "")) + require.False(t, PathUnder("", "/Users/dev")) + require.False(t, PathUnder("", "")) +} + +func TestPolicyValidateRejectsFilesystemRoot(t *testing.T) { + p := validPolicy() + p.WritableRoots = []WritableRoot{{Path: "/"}} + p.Cwd = "/" + require.ErrorIs(t, p.Validate(), ErrFilesystemRoot) +} + +func TestPolicyValidateRejectsWellKnownWideWritableRoot(t *testing.T) { + for _, wide := range []string{"/var", "/private/var", "/tmp", "/System/Volumes/Data"} { + if !filepath.IsAbs(wide) { + continue + } + p := validPolicy() + p.WritableRoots = []WritableRoot{{Path: wide}} + p.Cwd = wide + require.ErrorIs(t, p.Validate(), ErrWorkspaceTooBroad, wide) + } +} + +func TestPolicyValidateRejectsDenyReadOfFilesystemRoot(t *testing.T) { + p := validPolicy() + p.DenyRead = []string{"/"} + require.ErrorIs(t, p.Validate(), ErrFilesystemRoot) +} + +// A private root that is "/" would deny reading the whole machine, including +// the paths exec itself needs. +func TestPolicyValidateRejectsFilesystemRootAsPrivateRoot(t *testing.T) { + p := validPolicy() + p.PrivateRoots = []string{"/"} + require.ErrorIs(t, p.Validate(), ErrFilesystemRoot) +} + +// A private root covering the workspace is the normal case (home contains the +// project); the compiler re-opens it afterwards. +func TestPolicyValidateAllowsPrivateRootCoveringWritableRoot(t *testing.T) { + p := validPolicy() + p.PrivateRoots = []string{"/Users/dev"} + require.NoError(t, p.Validate()) +} + +func TestPolicyFingerprintCoversPrivateRoots(t *testing.T) { + base := validPolicy() + withPrivate := validPolicy() + withPrivate.PrivateRoots = []string{"/Users/dev"} + require.NotEqual(t, base.Fingerprint(), withPrivate.Fingerprint()) +} + +func TestPolicyValidateRejectsRelativePath(t *testing.T) { + p := validPolicy() + p.ReadableRoots = []string{"usr/lib"} + require.ErrorIs(t, p.Validate(), ErrRelativePath) +} + +func TestPolicyValidateRejectsCwdOutsideRoots(t *testing.T) { + p := validPolicy() + p.Cwd = "/Users/dev/elsewhere" + require.ErrorIs(t, p.Validate(), ErrCwdOutsideRoots) +} + +// A deny-read entry that swallows a writable root is a contradiction the +// backends cannot express coherently; reject it at the door. +func TestPolicyValidateRejectsDenyReadCoveringWritableRoot(t *testing.T) { + p := validPolicy() + p.DenyRead = []string{"/Users/dev"} + require.ErrorIs(t, p.Validate(), ErrDenyReadCoversRoot) +} + +func TestPolicyFingerprintIsStableAndDiscriminating(t *testing.T) { + a := validPolicy() + b := validPolicy() + require.Equal(t, a.Fingerprint(), b.Fingerprint()) + + b.Network = NetworkUnrestricted + require.NotEqual(t, a.Fingerprint(), b.Fingerprint()) +} + +// Ordering must not change identity: the same permissions written in a +// different order describe the same sandbox. +func TestPolicyFingerprintIgnoresOrdering(t *testing.T) { + a := validPolicy() + a.ReadableRoots = []string{"/usr/lib", "/bin"} + b := validPolicy() + b.ReadableRoots = []string{"/bin", "/usr/lib"} + require.Equal(t, a.Fingerprint(), b.Fingerprint()) +} diff --git a/internal/localsandbox/core/workspace.go b/internal/localsandbox/core/workspace.go new file mode 100644 index 00000000..d85f3ed4 --- /dev/null +++ b/internal/localsandbox/core/workspace.go @@ -0,0 +1,163 @@ +package core + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "fmt" + "os" + "path/filepath" + "strings" + "time" + + "github.com/Tencent/WeKnora/internal/logger" +) + +// WorkspaceKind distinguishes a user-picked project from an auto-allocated session dir. +type WorkspaceKind int + +const ( + // WorkspaceProject is a directory the user picked. Sessions opened on the + // same project share it. + WorkspaceProject WorkspaceKind = iota + // WorkspaceSession is auto-allocated per session under the session root. + WorkspaceSession +) + +// Workspace is where one session's work happens. +type Workspace struct { + Kind WorkspaceKind + // Root is the only work directory and the child process's cwd. Agent + // edits land here; there is no separate input/ or output/ tree. + Root string + // ProtectGit is true only for project workspaces: a session workspace's + // .git was created by the agent itself, so protecting it only gets in + // the agent's way. + ProtectGit bool +} + +// ProjectLookup reports whether a session is bound to a user-selected project. +type ProjectLookup interface { + ProjectDirForSession(ctx context.Context, sessionID string) (string, bool) +} + +// DirLayout names the roots the resolver allocates under. +type DirLayout struct { + // SessionRoot is where session workspaces are created, by default + // ~/Documents/WeKnoraLite. It is user-visible on purpose. + SessionRoot string +} + +// WorkspaceResolver maps a session to the directory the agent may work in. +type WorkspaceResolver interface { + Resolve(ctx context.Context, sessionID string) (Workspace, error) +} + +type workspaceResolver struct { + layout DirLayout + projects ProjectLookup + now func() time.Time +} + +// NewWorkspaceResolver returns a resolver that prefers a bound project +// directory and otherwise allocates under layout.SessionRoot. +func NewWorkspaceResolver(layout DirLayout, projects ProjectLookup) WorkspaceResolver { + return &workspaceResolver{layout: layout, projects: projects, now: time.Now} +} + +func (r *workspaceResolver) Resolve(ctx context.Context, sessionID string) (Workspace, error) { + sessionID = strings.TrimSpace(sessionID) + if sessionID == "" { + logger.Warnf(ctx, "[LocalSandbox] resolve workspace: session id is required") + return Workspace{}, fmt.Errorf("localsandbox: session id is required") + } + + if r.projects != nil { + if dir, ok := r.projects.ProjectDirForSession(ctx, sessionID); ok && dir != "" { + root, err := filepath.EvalSymlinks(filepath.Clean(dir)) + if err != nil { + logger.Warnf(ctx, "[LocalSandbox] resolve project dir session=%s dir=%q: %v", + sessionID, dir, err) + return Workspace{}, fmt.Errorf("localsandbox: resolve project dir: %w", err) + } + logger.Infof(ctx, "[LocalSandbox] workspace session=%s kind=project root=%s", sessionID, root) + return Workspace{ + Kind: WorkspaceProject, + Root: root, + ProtectGit: true, + }, nil + } + } + + day := r.now().Format("2006-01-02") + seg := sanitizeSegment(sessionID) + if existing, ok := r.existingSessionDir(seg); ok { + logger.Infof(ctx, "[LocalSandbox] workspace session=%s kind=session root=%s", sessionID, existing) + return Workspace{ + Kind: WorkspaceSession, + Root: existing, + ProtectGit: false, + }, nil + } + root := filepath.Join(r.layout.SessionRoot, day, "session-"+seg) + if err := os.MkdirAll(root, 0o700); err != nil { + logger.Errorf(ctx, "[LocalSandbox] create session workspace session=%s root=%s: %v", + sessionID, root, err) + return Workspace{}, fmt.Errorf("localsandbox: create session workspace: %w", err) + } + if err := os.Chmod(root, 0o700); err != nil { + return Workspace{}, fmt.Errorf("localsandbox: restrict session workspace: %w", err) + } + resolvedRoot, err := filepath.EvalSymlinks(root) + if err != nil { + logger.Errorf(ctx, "[LocalSandbox] resolve session workspace session=%s root=%s: %v", + sessionID, root, err) + return Workspace{}, fmt.Errorf("localsandbox: resolve session workspace: %w", err) + } + logger.Infof(ctx, "[LocalSandbox] workspace session=%s kind=session root=%s", sessionID, resolvedRoot) + return Workspace{ + Kind: WorkspaceSession, + Root: resolvedRoot, + ProtectGit: false, + }, nil +} + +// sanitizeSegment reduces an identifier to a short, space-free, filesystem-safe +// directory segment. Spaces are excluded by construction: created paths cross +// shell, sbpl and Windows command-line escaping on every call. +func sanitizeSegment(id string) string { + var b strings.Builder + for _, r := range id { + switch { + case r >= 'a' && r <= 'z', r >= 'A' && r <= 'Z', r >= '0' && r <= '9', r == '-', r == '_': + b.WriteRune(r) + default: + b.WriteRune('-') + } + } + visible := b.String() + if visible == "" { + visible = "session" + } + sum := sha256.Sum256([]byte(id)) + return visible + "-" + hex.EncodeToString(sum[:4]) +} + +func (r *workspaceResolver) existingSessionDir(seg string) (string, bool) { + if r.layout.SessionRoot == "" || seg == "" { + return "", false + } + matches, err := filepath.Glob(filepath.Join(r.layout.SessionRoot, "*", "session-"+seg)) + if err != nil || len(matches) == 0 { + return "", false + } + info, err := os.Lstat(matches[0]) + if err != nil || !info.IsDir() || info.Mode()&os.ModeSymlink != 0 { + return "", false + } + resolved, err := filepath.EvalSymlinks(matches[0]) + if err != nil { + return "", false + } + return resolved, true +} diff --git a/internal/localsandbox/core/workspace_test.go b/internal/localsandbox/core/workspace_test.go new file mode 100644 index 00000000..93f6a1d7 --- /dev/null +++ b/internal/localsandbox/core/workspace_test.go @@ -0,0 +1,157 @@ +package core + +import ( + "context" + "os" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/stretchr/testify/require" +) + +func osMkdirAll(dir string) error { return os.MkdirAll(dir, 0o755) } + +type fakeProjects struct{ dir string } + +func (f fakeProjects) ProjectDirForSession(context.Context, string) (string, bool) { + if f.dir == "" { + return "", false + } + return f.dir, true +} + +func workspaceFixture(t *testing.T, projectDir string) WorkspaceResolver { + t.Helper() + base := t.TempDir() + return NewWorkspaceResolver(DirLayout{ + SessionRoot: filepath.Join(base, "Documents", "WeKnora"), + }, fakeProjects{dir: projectDir}) +} + +func TestResolveProjectWorkspaceUsesSelectedDirectory(t *testing.T) { + project := filepath.Join(t.TempDir(), "My Project") + require.NoError(t, osMkdirAll(project)) + ws, err := workspaceFixture(t, project).Resolve(context.Background(), "sess-1") + require.NoError(t, err) + + // macOS t.TempDir is /var/folders/...; Resolve EvalSymlinks it to /private/var. + resolved, err := filepath.EvalSymlinks(project) + require.NoError(t, err) + require.Equal(t, WorkspaceProject, ws.Kind) + require.Equal(t, resolved, ws.Root) + require.True(t, ws.ProtectGit) + require.NoDirExists(t, filepath.Join(resolved, "input")) + require.NoDirExists(t, filepath.Join(resolved, "output")) +} + +// The user's directory is the workspace. Creating input/ or output/ next to +// their files, or under app data, would be leftover remote-sandbox shape. +func TestResolveProjectWorkspaceDoesNotCreateInputOrOutput(t *testing.T) { + project := filepath.Join(t.TempDir(), "My Project") + require.NoError(t, osMkdirAll(project)) + ws, err := workspaceFixture(t, project).Resolve(context.Background(), "sess-1") + require.NoError(t, err) + + entries, err := os.ReadDir(ws.Root) + require.NoError(t, err) + require.Empty(t, entries) +} + +// Sessions opened on the same project share one directory, so their files +// accumulate the way a real project does. +func TestResolveProjectWorkspaceIsSharedAcrossSessions(t *testing.T) { + project := filepath.Join(t.TempDir(), "My Project") + require.NoError(t, osMkdirAll(project)) + r := workspaceFixture(t, project) + + a, err := r.Resolve(context.Background(), "sess-1") + require.NoError(t, err) + b, err := r.Resolve(context.Background(), "sess-2") + require.NoError(t, err) + require.Equal(t, a.Root, b.Root) +} + +func TestResolveSessionWorkspaceCreatesDatedDirectory(t *testing.T) { + ws, err := workspaceFixture(t, "").Resolve(context.Background(), "session-abcdef123456") + require.NoError(t, err) + + require.Equal(t, WorkspaceSession, ws.Kind) + require.DirExists(t, ws.Root) + require.Contains(t, ws.Root, "session-") + require.False(t, ws.ProtectGit) + require.NoDirExists(t, filepath.Join(ws.Root, "input")) + require.NoDirExists(t, filepath.Join(ws.Root, "output")) +} + +// Directory names we create must never contain spaces; they cross shell, +// sbpl and Windows command-line escaping every single call. +func TestResolveSessionWorkspaceHasNoSpacesInCreatedNames(t *testing.T) { + base := t.TempDir() + r := NewWorkspaceResolver(DirLayout{ + SessionRoot: filepath.Join(base, "Documents", "WeKnora"), + }, fakeProjects{}) + + ws, err := r.Resolve(context.Background(), "session-abcdef123456") + require.NoError(t, err) + + created := strings.TrimPrefix(ws.Root, filepath.Join(base, "Documents")) + require.NotContains(t, created, " ") +} + +func TestResolveSessionWorkspaceIsPerSession(t *testing.T) { + r := workspaceFixture(t, "") + a, err := r.Resolve(context.Background(), "sess-1") + require.NoError(t, err) + b, err := r.Resolve(context.Background(), "sess-2") + require.NoError(t, err) + require.NotEqual(t, a.Root, b.Root) +} + +func TestResolveRejectsEmptySessionID(t *testing.T) { + _, err := workspaceFixture(t, "").Resolve(context.Background(), "") + require.Error(t, err) +} + +func TestResolveSessionWorkspaceKeepsPathAfterMidnight(t *testing.T) { + base := t.TempDir() + r := NewWorkspaceResolver(DirLayout{ + SessionRoot: filepath.Join(base, "Documents", "WeKnora"), + }, fakeProjects{}).(*workspaceResolver) + + day1 := time.Date(2026, 9, 20, 23, 0, 0, 0, time.UTC) + r.now = func() time.Time { return day1 } + first, err := r.Resolve(context.Background(), "sess-keep") + require.NoError(t, err) + + r.now = func() time.Time { return day1.Add(2 * time.Hour) } + second, err := r.Resolve(context.Background(), "sess-keep") + require.NoError(t, err) + require.Equal(t, first.Root, second.Root) +} + +func TestResolveSessionWorkspaceUsesFullSessionID(t *testing.T) { + r := workspaceFixture(t, "") + a, err := r.Resolve(context.Background(), "session-abcdef123456") + require.NoError(t, err) + b, err := r.Resolve(context.Background(), "session-abcdef999999") + require.NoError(t, err) + require.NotEqual(t, a.Root, b.Root) + require.Contains(t, a.Root, "session-abcdef123456") + require.Contains(t, b.Root, "session-abcdef999999") +} + +func TestSanitizeSegmentDistinguishesCollidingIDs(t *testing.T) { + require.NotEqual(t, sanitizeSegment("foo/bar"), sanitizeSegment("foo-bar")) + require.NotEqual(t, sanitizeSegment("!!!"), sanitizeSegment("@@@")) + require.Equal(t, sanitizeSegment("sess-keep"), sanitizeSegment("sess-keep")) +} + +func TestResolveSessionWorkspaceIsOwnerPrivate(t *testing.T) { + ws, err := workspaceFixture(t, "").Resolve(context.Background(), "sess-mode") + require.NoError(t, err) + info, err := os.Stat(ws.Root) + require.NoError(t, err) + require.Equal(t, os.FileMode(0o700), info.Mode().Perm()) +} diff --git a/internal/localsandbox/rootlock.go b/internal/localsandbox/rootlock.go new file mode 100644 index 00000000..5a519280 --- /dev/null +++ b/internal/localsandbox/rootlock.go @@ -0,0 +1,62 @@ +package localsandbox + +import ( + "path/filepath" + "runtime" + "strings" + "sync" +) + +type rootLocks struct { + mu sync.Mutex + locks map[string]*rootLease +} + +type rootLease struct { + mu sync.Mutex + refs int +} + +func newRootLocks() *rootLocks { + return &rootLocks{locks: make(map[string]*rootLease)} +} + +func rootLockKey(root string) string { + key := filepath.Clean(root) + if runtime.GOOS == "darwin" || runtime.GOOS == "windows" { + key = strings.ToLower(key) + } + return key +} + +// LockRoot serializes mutating work against one workspace directory. +// Sessions that share a project share the lock; different directories do not +// block each other. The returned function always unlocks; call it with defer. +func (s *Service) LockRoot(root string) func() { + if s == nil || s.roots == nil || strings.TrimSpace(root) == "" { + return func() {} + } + return s.roots.lock(root) +} + +func (r *rootLocks) lock(root string) func() { + key := rootLockKey(root) + r.mu.Lock() + lease := r.locks[key] + if lease == nil { + lease = &rootLease{} + r.locks[key] = lease + } + lease.refs++ + r.mu.Unlock() + lease.mu.Lock() + return func() { + lease.mu.Unlock() + r.mu.Lock() + lease.refs-- + if lease.refs == 0 { + delete(r.locks, key) + } + r.mu.Unlock() + } +} diff --git a/internal/localsandbox/seatbelt/backend.go b/internal/localsandbox/seatbelt/backend.go new file mode 100644 index 00000000..9f964606 --- /dev/null +++ b/internal/localsandbox/seatbelt/backend.go @@ -0,0 +1,323 @@ +//go:build darwin + +// Package seatbelt implements the sandbox backend for macOS on top of +// /usr/bin/sandbox-exec. The policy compiler in this package carries no build +// tag so it stays testable on every platform. +package seatbelt + +import ( + "bytes" + "context" + "errors" + "fmt" + "io" + "os" + "os/exec" + "path/filepath" + "strings" + "sync" + "syscall" + "time" + + "github.com/Tencent/WeKnora/internal/localsandbox/core" + "github.com/Tencent/WeKnora/internal/logger" +) + +// seatbeltExecPath is hard-coded rather than resolved through PATH: a PATH +// lookup would let anything earlier in PATH impersonate the sandbox. If this +// binary itself is tampered with, the attacker already has root. +const seatbeltExecPath = "/usr/bin/sandbox-exec" + +type seatbeltBackend struct{} + +// New returns the macOS Seatbelt backend. +func New() (core.Backend, error) { + return &seatbeltBackend{}, nil +} + +func (b *seatbeltBackend) Name() string { return "seatbelt" } + +func (b *seatbeltBackend) Available() error { + info, err := os.Stat(seatbeltExecPath) + if err != nil { + logger.Errorf(context.Background(), "[LocalSandbox] seatbelt missing: %v", err) + return fmt.Errorf("%w: %s is missing", core.ErrUnsupportedPlatform, seatbeltExecPath) + } + if info.Mode()&0o111 == 0 { + logger.Errorf(context.Background(), "[LocalSandbox] seatbelt not executable: %s", seatbeltExecPath) + return fmt.Errorf("%w: %s is not executable", core.ErrUnsupportedPlatform, seatbeltExecPath) + } + return nil +} + +// EnsureReady is a no-op: Seatbelt needs no installation and no elevation. +// That is what makes it suitable for a double-click desktop app. +func (b *seatbeltBackend) EnsureReady(context.Context) error { return nil } + +// TearDown is a no-op for the same reason: nothing persistent was created. +func (b *seatbeltBackend) TearDown(context.Context) error { return nil } + +type seatbeltPrepared struct { + fingerprint string + program seatbeltProgram +} + +func (p *seatbeltPrepared) Fingerprint() string { return p.fingerprint } +func (p *seatbeltPrepared) Close() error { return nil } + +func (b *seatbeltBackend) Prepare(ctx context.Context, p core.Policy) (core.Prepared, error) { + if err := b.Available(); err != nil { + return nil, err + } + resolved, err := resolvePolicyPaths(p) + if err != nil { + logger.Errorf(ctx, "[LocalSandbox] seatbelt resolve policy paths: %v", err) + return nil, err + } + program, err := compileSeatbelt(resolved) + if err != nil { + logger.Errorf(ctx, "[LocalSandbox] seatbelt compile: %v", err) + return nil, err + } + logger.Debugf(ctx, "[LocalSandbox] seatbelt prepared fingerprint=%s params=%d", + p.Fingerprint(), len(program.Params)) + return &seatbeltPrepared{fingerprint: p.Fingerprint(), program: program}, nil +} + +func (b *seatbeltBackend) Spawn( + ctx context.Context, prep core.Prepared, cmd core.Command, +) (core.Process, error) { + if err := cmd.Validate(); err != nil { + return nil, err + } + prepared, ok := prep.(*seatbeltPrepared) + if !ok { + return nil, fmt.Errorf("localsandbox: prepared handle is not a seatbelt program") + } + + argv := []string{"-p", prepared.program.Profile} + argv = append(argv, prepared.program.Params...) + argv = append(argv, "--") + argv = append(argv, cmd.Argv...) + + // Not CommandContext: cancellation must kill the whole process group, and + // CommandContext only signals the root process. + execCmd := exec.Command(seatbeltExecPath, argv...) + execCmd.Dir = cmd.Cwd + execCmd.Env = withSandboxTemp(mergedEnv(cmd.Env), cmd.Cwd, cmd.Env) + if len(cmd.Stdin) > 0 { + execCmd.Stdin = bytes.NewReader(cmd.Stdin) + } + // Setpgid puts the child in its own process group so descendants can be + // terminated together. + execCmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true} + + stdout, err := execCmd.StdoutPipe() + if err != nil { + return nil, fmt.Errorf("localsandbox: stdout pipe: %w", err) + } + stderr, err := execCmd.StderrPipe() + if err != nil { + return nil, fmt.Errorf("localsandbox: stderr pipe: %w", err) + } + started := time.Now() + if err := execCmd.Start(); err != nil { + logger.Errorf(ctx, "[LocalSandbox] seatbelt start cwd=%s: %v", cmd.Cwd, err) + return nil, fmt.Errorf("localsandbox: start sandboxed command: %w", err) + } + pid := 0 + if execCmd.Process != nil { + pid = execCmd.Process.Pid + } + logger.Infof(ctx, "[LocalSandbox] seatbelt spawn pid=%d cwd=%s argv0=%s", pid, cmd.Cwd, cmd.Argv[0]) + + proc := &seatbeltProcess{ + cmd: execCmd, + stdout: stdout, + stderr: stderr, + started: started, + waitDone: make(chan struct{}), + } + go proc.watchContext(ctx) + return proc, nil +} + +func resolvePolicyPaths(p core.Policy) (core.Policy, error) { + out := p + out.WritableRoots = make([]core.WritableRoot, len(p.WritableRoots)) + for i, root := range p.WritableRoots { + path, err := resolveExisting(root.Path) + if err != nil { + return core.Policy{}, err + } + subs := make([]string, len(root.ReadOnlySubpaths)) + for j, sub := range root.ReadOnlySubpaths { + subs[j], err = resolveExisting(sub) + if err != nil { + return core.Policy{}, err + } + } + out.WritableRoots[i] = core.WritableRoot{Path: path, ReadOnlySubpaths: subs} + } + out.ReadableRoots = make([]string, len(p.ReadableRoots)) + for i, root := range p.ReadableRoots { + var err error + out.ReadableRoots[i], err = resolveExisting(root) + if err != nil { + return core.Policy{}, err + } + } + // The kernel matches the resolved path, so an unresolved private root + // silently protects nothing: /tmp/... never matches /private/tmp/... + out.PrivateRoots = make([]string, len(p.PrivateRoots)) + for i, private := range p.PrivateRoots { + var err error + out.PrivateRoots[i], err = resolveExisting(private) + if err != nil { + return core.Policy{}, err + } + } + out.DenyRead = make([]string, len(p.DenyRead)) + for i, deny := range p.DenyRead { + var err error + out.DenyRead[i], err = resolveExisting(deny) + if err != nil { + return core.Policy{}, err + } + } + cwd, err := resolveExisting(p.Cwd) + if err != nil { + return core.Policy{}, err + } + out.Cwd = cwd + return out, nil +} + +// resolveExisting EvalSymlinks the longest existing prefix. /tmp/foo becomes +// /private/tmp/foo; a missing ~/.ssh keeps the realpath of the parent. +func resolveExisting(path string) (string, error) { + cleaned := filepath.Clean(path) + if resolved, err := filepath.EvalSymlinks(cleaned); err == nil { + return resolved, nil + } + parent := filepath.Dir(cleaned) + if parent == cleaned { + return cleaned, nil + } + resolvedParent, err := resolveExisting(parent) + if err != nil { + return "", err + } + return filepath.Join(resolvedParent, filepath.Base(cleaned)), nil +} + +func mergedEnv(env map[string]string) []string { + // Nil is a direct-Spawn fallback: filtered inherit. Service always + // passes a map already run through BuildCommandEnv. + if env == nil { + return core.FilterInheritedEnv(os.Environ()) + } + return core.EnvSlice(env) +} + +func withSandboxTemp(env []string, cwd string, explicit map[string]string) []string { + // Command.Env is the only way a caller opts into a custom temp dir. An + // inherited host TMPDIR (Go tests set one under /var/folders) would + // otherwise skip injection and leave python/git writing outside the + // writable root. + if _, ok := explicit["TMPDIR"]; ok { + return env + } + out := make([]string, 0, len(env)+3) + for _, kv := range env { + if strings.HasPrefix(kv, "TMPDIR=") || + strings.HasPrefix(kv, "TMP=") || + strings.HasPrefix(kv, "TEMP=") { + continue + } + out = append(out, kv) + } + return append(out, + "TMPDIR="+cwd, + "TMP="+cwd, + "TEMP="+cwd, + ) +} + +type seatbeltProcess struct { + cmd *exec.Cmd + stdout io.ReadCloser + stderr io.ReadCloser + started time.Time + waitDone chan struct{} + + mu sync.Mutex + killed bool + reaped bool +} + +func (p *seatbeltProcess) Stdout() io.Reader { return p.stdout } +func (p *seatbeltProcess) Stderr() io.Reader { return p.stderr } +func (p *seatbeltProcess) PID() int { return p.cmd.Process.Pid } + +func (p *seatbeltProcess) watchContext(ctx context.Context) { + select { + case <-p.waitDone: + return + case <-ctx.Done(): + } + // ctx fired. If Wait already reaped the process, skip Kill: SIGKILL to + // -pid after wait has a PID-reuse window. waitDone is closed first. + select { + case <-p.waitDone: + return + default: + _ = p.Kill() + } +} + +// Kill terminates the entire process group. Killing only the root would leave +// descendants running after a timeout. +func (p *seatbeltProcess) Kill() error { + p.mu.Lock() + // ProcessState is written before cmd.Wait returns, so this closes the + // window between Wait returning and reaped being set. + if p.reaped || p.cmd.ProcessState != nil { + p.mu.Unlock() + return nil + } + p.killed = true + pid := 0 + if p.cmd.Process != nil { + pid = p.cmd.Process.Pid + } + p.mu.Unlock() + + if pid == 0 { + return nil + } + if err := syscall.Kill(-pid, syscall.SIGKILL); err != nil && + err != syscall.ESRCH { + return fmt.Errorf("localsandbox: kill process group: %w", err) + } + return nil +} + +func (p *seatbeltProcess) Wait(context.Context) (core.ExitStatus, error) { + err := p.cmd.Wait() + p.mu.Lock() + p.reaped = true + killed := p.killed + p.mu.Unlock() + close(p.waitDone) + duration := time.Since(p.started) + + status := core.ExitStatus{Code: p.cmd.ProcessState.ExitCode(), Killed: killed, Duration: duration} + // A non-zero exit is a normal result, not a transport failure: only errors + // other than *exec.ExitError mean the execution itself went wrong. + var exitErr *exec.ExitError + if err == nil || errors.As(err, &exitErr) { + return status, nil + } + return status, fmt.Errorf("localsandbox: wait: %w", err) +} diff --git a/internal/localsandbox/seatbelt/backend_test.go b/internal/localsandbox/seatbelt/backend_test.go new file mode 100644 index 00000000..6108d769 --- /dev/null +++ b/internal/localsandbox/seatbelt/backend_test.go @@ -0,0 +1,473 @@ +//go:build darwin + +package seatbelt + +import ( + "context" + "io" + "os" + "path/filepath" + "testing" + "time" + + "github.com/stretchr/testify/require" + + "github.com/Tencent/WeKnora/internal/localsandbox/core" +) + +func darwinFixture(t *testing.T) (core.Backend, core.Policy, string) { + t.Helper() + backend, err := New() + require.NoError(t, err) + require.NoError(t, backend.Available()) + + base, err := filepath.EvalSymlinks(t.TempDir()) + require.NoError(t, err) + // The space is deliberate: it is the shape of a real user directory. + root := filepath.Join(base, "My Project") + require.NoError(t, os.MkdirAll(filepath.Join(root, ".git"), 0o755)) + + secrets := filepath.Join(base, "secrets") + require.NoError(t, os.MkdirAll(secrets, 0o755)) + require.NoError(t, os.WriteFile(filepath.Join(secrets, "note.txt"), []byte("KEY"), 0o600)) + + // base stands in for the user's home: another project beside the + // workspace, and a per-user toolchain that has to keep working. + other := filepath.Join(base, "Other Project") + require.NoError(t, os.MkdirAll(other, 0o755)) + require.NoError(t, os.WriteFile(filepath.Join(other, "private.txt"), []byte("OTHER"), 0o600)) + toolchain := filepath.Join(base, ".nvm") + require.NoError(t, os.MkdirAll(toolchain, 0o755)) + require.NoError(t, os.WriteFile(filepath.Join(toolchain, "node"), []byte("NODE"), 0o644)) + + p := core.Policy{ + WritableRoots: []core.WritableRoot{{ + Path: root, + ReadOnlySubpaths: []string{filepath.Join(root, ".git")}, + }}, + ReadableRoots: []string{toolchain}, + PrivateRoots: []string{base}, + DenyRead: []string{secrets}, + Network: core.NetworkDenied, + Cwd: root, + } + return backend, p, base +} + +func runSandboxed(t *testing.T, backend core.Backend, p core.Policy, script string) (core.ExitStatus, string) { + t.Helper() + return runSandboxedArgv(t, backend, p, []string{"/bin/bash", "-c", script}, nil) +} + +func runSandboxedArgv( + t *testing.T, backend core.Backend, p core.Policy, argv []string, env map[string]string, +) (core.ExitStatus, string) { + t.Helper() + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + + prep, err := backend.Prepare(ctx, p) + require.NoError(t, err) + defer func() { _ = prep.Close() }() + + proc, err := backend.Spawn(ctx, prep, core.Command{ + Argv: argv, + Env: env, + Cwd: p.Cwd, + }) + require.NoError(t, err) + + outCh := make(chan []byte, 1) + errCh := make(chan []byte, 1) + go func() { + b, _ := io.ReadAll(proc.Stdout()) + outCh <- b + }() + go func() { + b, _ := io.ReadAll(proc.Stderr()) + errCh <- b + }() + status, err := proc.Wait(ctx) + require.NoError(t, err) + return status, string(<-outCh) + string(<-errCh) +} + +func TestSeatbeltAllowsWriteInsideWorkspace(t *testing.T) { + backend, p, _ := darwinFixture(t) + status, out := runSandboxed(t, backend, p, `echo hi > ./a.txt && cat ./a.txt`) + require.Equal(t, 0, status.Code, out) + require.Contains(t, out, "hi") +} + +func TestSeatbeltDeniesWriteOutsideWorkspace(t *testing.T) { + backend, p, base := darwinFixture(t) + status, out := runSandboxed(t, backend, p, `echo pwned > `+filepath.Join(base, "escape.txt")) + require.NotEqual(t, 0, status.Code, out) + require.True(t, core.ClassifyDenial(status, "", out).IsDenied(), out) + require.NoFileExists(t, filepath.Join(base, "escape.txt")) +} + +func TestSeatbeltDeniesWriteToGit(t *testing.T) { + backend, p, _ := darwinFixture(t) + status, out := runSandboxed(t, backend, p, `echo x > ./.git/config`) + require.NotEqual(t, 0, status.Code, out) +} + +// subpath alone would let this succeed; the literal exclusion is what stops it. +func TestSeatbeltDeniesRecreatingProtectedDirectory(t *testing.T) { + backend, p, _ := darwinFixture(t) + status, out := runSandboxed(t, backend, p, `rm -rf ./.git && mkdir ./.git`) + require.NotEqual(t, 0, status.Code, out) +} + +func TestSeatbeltDeniesSymlinkEscapeToSecrets(t *testing.T) { + backend, p, base := darwinFixture(t) + status, out := runSandboxed(t, backend, p, + `ln -s `+filepath.Join(base, "secrets", "note.txt")+` ./stolen && cat ./stolen`) + require.NotEqual(t, 0, status.Code, out) + require.NotContains(t, out, "KEY") +} + +func TestSeatbeltDeniesReadingSecrets(t *testing.T) { + backend, p, base := darwinFixture(t) + status, out := runSandboxed(t, backend, p, `cat `+filepath.Join(base, "secrets", "note.txt")) + require.NotEqual(t, 0, status.Code, out) + require.NotContains(t, out, "KEY") +} + +// The point of the private root: everything else in the user's home is +// invisible, not just the handful of named credential directories. +func TestSeatbeltDeniesReadingOtherDirectoriesInHome(t *testing.T) { + backend, p, base := darwinFixture(t) + status, out := runSandboxed(t, backend, p, + `cat `+filepath.Join(base, "Other Project", "private.txt")) + require.NotEqual(t, 0, status.Code, out) + require.NotContains(t, out, "OTHER") +} + +// Denying home wholesale must not take the user's toolchain with it. +func TestSeatbeltAllowsReadingReopenedToolchain(t *testing.T) { + backend, p, base := darwinFixture(t) + status, out := runSandboxed(t, backend, p, `cat `+filepath.Join(base, ".nvm", "node")) + require.Equal(t, 0, status.Code, out) + require.Contains(t, out, "NODE") +} + +// The workspace sits inside the private root and must stay readable. +func TestSeatbeltAllowsReadingWorkspaceInsidePrivateRoot(t *testing.T) { + backend, p, _ := darwinFixture(t) + status, out := runSandboxed(t, backend, p, `echo body > ./f.txt && cat ./f.txt`) + require.Equal(t, 0, status.Code, out) + require.Contains(t, out, "body") +} + +// End-to-end through the real PolicyBuilder rather than a hand-written +// policy: this is what actually ships, and `bash -lc` reading its startup +// files under a denied home is the part most likely to regress. +func TestSeatbeltPolicyFromBuilderRunsLoginShell(t *testing.T) { + backend, err := New() + require.NoError(t, err) + require.NoError(t, backend.Available()) + + home, err := filepath.EvalSymlinks(t.TempDir()) + require.NoError(t, err) + workspace := filepath.Join(home, "Documents", "WeKnora", "s1") + require.NoError(t, os.MkdirAll(workspace, 0o755)) + secretProfile := []byte("export AWS_SECRET_ACCESS_KEY=super-secret\n") + require.NoError(t, os.WriteFile(filepath.Join(home, ".profile"), secretProfile, 0o644)) + require.NoError(t, os.WriteFile(filepath.Join(home, ".bashrc"), []byte("export GITHUB_TOKEN=gho_secret\n"), 0o644)) + require.NoError(t, os.WriteFile(filepath.Join(home, ".zshrc"), []byte("export OPENAI_API_KEY=sk-secret\n"), 0o644)) + require.NoError(t, os.MkdirAll(filepath.Join(home, ".ssh"), 0o700)) + require.NoError(t, os.WriteFile(filepath.Join(home, ".ssh", "id_rsa"), []byte("PRIVATEKEY"), 0o600)) + + builder := core.NewPolicyBuilder(home, filepath.Join(home, "Library", "App")) + p, err := builder.Build(core.ModeAuto, core.Workspace{Kind: core.WorkspaceSession, Root: workspace}) + require.NoError(t, err) + + env := map[string]string{ + "HOME": home, + "PATH": os.Getenv("PATH"), + } + noProfile := []string{"/bin/bash", "--noprofile", "--norc", "-c"} + writeCmd := `echo alive && echo w > ./f.txt && cat ./f.txt` + status, out := runSandboxedArgv(t, backend, p, append(noProfile, writeCmd), env) + require.Equal(t, 0, status.Code, out) + require.Contains(t, out, "alive") + require.Contains(t, out, "w") + + status, out = runSandboxedArgv(t, backend, p, append(noProfile, `cat `+filepath.Join(home, ".ssh", "id_rsa")), env) + require.NotEqual(t, 0, status.Code, out) + require.NotContains(t, out, "PRIVATEKEY") + + status, out = runSandboxedArgv(t, backend, p, append(noProfile, `cat `+filepath.Join(home, ".zshrc")), env) + require.NotEqual(t, 0, status.Code, out) + require.NotContains(t, out, "sk-secret") + + status, out = runSandboxedArgv(t, backend, p, append(noProfile, "printenv"), env) + require.Equal(t, 0, status.Code, out) + require.NotContains(t, out, "super-secret") + require.NotContains(t, out, "gho_secret") + require.NotContains(t, out, "sk-secret") +} + +// Cancelling the spawn context after Wait must not SIGKILL the process group: +// the pid may already have been reused. Service.Run's defer cancel() hits +// this on every successful command. +func TestSeatbeltDoesNotKillAfterSuccessfulWait(t *testing.T) { + backend, p, _ := darwinFixture(t) + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + + prep, err := backend.Prepare(ctx, p) + require.NoError(t, err) + defer func() { _ = prep.Close() }() + + proc, err := backend.Spawn(ctx, prep, core.Command{ + Argv: []string{"/bin/bash", "-c", "echo hi"}, + Cwd: p.Cwd, + }) + require.NoError(t, err) + + outCh := make(chan []byte, 1) + errCh := make(chan []byte, 1) + go func() { + b, _ := io.ReadAll(proc.Stdout()) + outCh <- b + }() + go func() { + b, _ := io.ReadAll(proc.Stderr()) + errCh <- b + }() + status, err := proc.Wait(ctx) + require.NoError(t, err) + require.Equal(t, 0, status.Code, string(<-outCh)+string(<-errCh)) + require.False(t, status.Killed) + + cancel() + time.Sleep(50 * time.Millisecond) + sp := proc.(*seatbeltProcess) + sp.mu.Lock() + killed := sp.killed + sp.mu.Unlock() + require.False(t, killed, "spawn-context cancel after Wait must not Kill(-pid)") +} + +func TestSeatbeltKillAfterWaitDoesNotSignal(t *testing.T) { + backend, p, _ := darwinFixture(t) + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + + prep, err := backend.Prepare(ctx, p) + require.NoError(t, err) + defer func() { _ = prep.Close() }() + + proc, err := backend.Spawn(ctx, prep, core.Command{ + Argv: []string{"/bin/bash", "-c", "echo hi"}, + Cwd: p.Cwd, + }) + require.NoError(t, err) + + go func() { _, _ = io.ReadAll(proc.Stdout()) }() + go func() { _, _ = io.ReadAll(proc.Stderr()) }() + status, err := proc.Wait(ctx) + require.NoError(t, err) + require.Equal(t, 0, status.Code) + + require.NoError(t, proc.Kill()) + sp := proc.(*seatbeltProcess) + sp.mu.Lock() + killed := sp.killed + sp.mu.Unlock() + require.False(t, killed, "Kill after Wait must be a no-op") +} + +// When the workspace is the home directory, credential files sit inside the +// writable root. subpath deny does not match a file, so without a literal +// write deny `echo pwned > ~/.cargo/credentials.toml` succeeds. +func TestSeatbeltDeniesWritingCredentialFileInsideWritableHome(t *testing.T) { + backend, err := New() + require.NoError(t, err) + require.NoError(t, backend.Available()) + + home, err := filepath.EvalSymlinks(t.TempDir()) + require.NoError(t, err) + cargo := filepath.Join(home, ".cargo") + require.NoError(t, os.MkdirAll(cargo, 0o755)) + creds := filepath.Join(cargo, "credentials.toml") + require.NoError(t, os.WriteFile(creds, []byte("SECRET"), 0o600)) + require.NoError(t, os.WriteFile(filepath.Join(cargo, "config.toml"), []byte("ok\n"), 0o644)) + + p := core.Policy{ + WritableRoots: []core.WritableRoot{{ + Path: home, + ReadOnlySubpaths: []string{filepath.Join(home, ".git")}, + }}, + ReadableRoots: []string{home, cargo}, + PrivateRoots: []string{home}, + DenyRead: []string{creds}, + Network: core.NetworkDenied, + Cwd: home, + } + require.NoError(t, p.Validate()) + + status, out := runSandboxed(t, backend, p, `echo pwned > `+creds) + require.NotEqual(t, 0, status.Code, out) + got, err := os.ReadFile(creds) + require.NoError(t, err) + require.Equal(t, "SECRET", string(got)) + + status, out = runSandboxed(t, backend, p, `echo x > `+filepath.Join(cargo, "config.toml")) + require.Equal(t, 0, status.Code, out) +} + +func TestSeatbeltDeniesWritingAppDataInsideWritableHome(t *testing.T) { + backend, err := New() + require.NoError(t, err) + require.NoError(t, backend.Available()) + + home, err := filepath.EvalSymlinks(t.TempDir()) + require.NoError(t, err) + appData := filepath.Join(home, "Library", "App") + require.NoError(t, os.MkdirAll(appData, 0o755)) + prefs := filepath.Join(appData, "prefs.json") + require.NoError(t, os.WriteFile(prefs, []byte("keep"), 0o600)) + + p := core.Policy{ + WritableRoots: []core.WritableRoot{{ + Path: home, + ReadOnlySubpaths: []string{filepath.Join(home, ".git")}, + }}, + ReadableRoots: []string{home}, + PrivateRoots: []string{home}, + DenyRead: []string{appData}, + Network: core.NetworkDenied, + Cwd: home, + } + require.NoError(t, p.Validate()) + + status, out := runSandboxed(t, backend, p, `echo pwned > `+prefs) + require.NotEqual(t, 0, status.Code, out) + got, err := os.ReadFile(prefs) + require.NoError(t, err) + require.Equal(t, "keep", string(got)) +} + +// file-read* is blanket; /tmp and /var/folders must stay behind PrivateRoots +// or the agent can read other apps' temp tokens. Workspace under a temp +// fixture must still be writable after those denials. +func TestSeatbeltDeniesReadingTmpAndVarFolders(t *testing.T) { + backend, err := New() + require.NoError(t, err) + require.NoError(t, backend.Available()) + + home, err := filepath.EvalSymlinks(t.TempDir()) + require.NoError(t, err) + workspace := filepath.Join(home, "Documents", "WeKnora", "s1") + require.NoError(t, os.MkdirAll(workspace, 0o755)) + + tmpSecret := filepath.Join("/tmp", "weknora-seatbelt-"+t.Name()) + require.NoError(t, os.WriteFile(tmpSecret, []byte("TMPSECRET"), 0o600)) + t.Cleanup(func() { _ = os.Remove(tmpSecret) }) + + vfSecret := filepath.Join(os.TempDir(), "weknora-seatbelt-"+t.Name()) + require.NoError(t, os.WriteFile(vfSecret, []byte("VFSECRET"), 0o600)) + t.Cleanup(func() { _ = os.Remove(vfSecret) }) + + builder := core.NewPolicyBuilder(home, filepath.Join(home, "Library", "App")) + p, err := builder.Build(core.ModeAuto, core.Workspace{Kind: core.WorkspaceSession, Root: workspace}) + require.NoError(t, err) + + env := map[string]string{ + "HOME": home, + "PATH": os.Getenv("PATH"), + } + noProfile := []string{"/bin/bash", "--noprofile", "--norc", "-c"} + + status, out := runSandboxedArgv(t, backend, p, append(noProfile, `echo ok > ./f.txt && cat ./f.txt`), env) + require.Equal(t, 0, status.Code, out) + require.Contains(t, out, "ok") + + status, out = runSandboxedArgv(t, backend, p, append(noProfile, `cat `+tmpSecret), env) + require.NotEqual(t, 0, status.Code, out) + require.NotContains(t, out, "TMPSECRET") + + status, out = runSandboxedArgv(t, backend, p, append(noProfile, `cat `+vfSecret), env) + require.NotEqual(t, 0, status.Code, out) + require.NotContains(t, out, "VFSECRET") +} + +func TestSeatbeltDeniesNetwork(t *testing.T) { + backend, p, _ := darwinFixture(t) + status, out := runSandboxed(t, backend, p, + `curl --max-time 5 -sS https://example.com`) + require.NotEqual(t, 0, status.Code) + // Seatbelt does not surface EPERM for DNS; curl exits 6. + require.True(t, core.LooksLikeNetworkDenial(status, "", out), out) + require.False(t, core.ClassifyDenial(status, "", out).IsDenied(), out) +} + +func TestSeatbeltPrepareResolvesTmpAlias(t *testing.T) { + backend, err := New() + require.NoError(t, err) + + logical, err := os.MkdirTemp("/tmp", "weknora-seatbelt-") + require.NoError(t, err) + t.Cleanup(func() { _ = os.RemoveAll(logical) }) + + p := core.Policy{ + WritableRoots: []core.WritableRoot{{Path: logical}}, + Network: core.NetworkDenied, + Cwd: logical, + } + status, out := runSandboxed(t, backend, p, `echo hi > ./from-tmp.txt && cat ./from-tmp.txt`) + require.Equal(t, 0, status.Code, out) + require.Contains(t, out, "hi") +} + +func TestSeatbeltInjectsTMPDIR(t *testing.T) { + backend, p, _ := darwinFixture(t) + status, out := runSandboxed(t, backend, p, `printf '%s\n' "$TMPDIR"`) + require.Equal(t, 0, status.Code, out) + require.Contains(t, out, p.Cwd) +} + +func TestSeatbeltDoesNotInheritSecretEnv(t *testing.T) { + t.Setenv("AWS_SECRET_ACCESS_KEY", "super-secret") + t.Setenv("GITHUB_TOKEN", "gho_secret") + + backend, p, _ := darwinFixture(t) + status, out := runSandboxed(t, backend, p, `printenv`) + require.Equal(t, 0, status.Code, out) + require.NotContains(t, out, "super-secret") + require.NotContains(t, out, "gho_secret") + require.NotContains(t, out, "AWS_SECRET_ACCESS_KEY") + require.NotContains(t, out, "GITHUB_TOKEN") +} + +func TestSeatbeltKillsProcessTreeOnContextCancel(t *testing.T) { + backend, p, _ := darwinFixture(t) + ctx, cancel := context.WithCancel(context.Background()) + + prep, err := backend.Prepare(ctx, p) + require.NoError(t, err) + defer func() { _ = prep.Close() }() + + proc, err := backend.Spawn(ctx, prep, core.Command{ + Argv: []string{"/bin/bash", "-c", `sleep 60 & sleep 60`}, + Cwd: p.Cwd, + }) + require.NoError(t, err) + + time.AfterFunc(200*time.Millisecond, cancel) + status, err := proc.Wait(ctx) + require.NoError(t, err) + require.True(t, status.Killed) + require.Less(t, status.Duration, 30*time.Second) +} + +func TestSeatbeltPreparedFingerprintMatchesPolicy(t *testing.T) { + backend, p, _ := darwinFixture(t) + prep, err := backend.Prepare(context.Background(), p) + require.NoError(t, err) + defer func() { _ = prep.Close() }() + require.Equal(t, p.Fingerprint(), prep.Fingerprint()) +} diff --git a/internal/localsandbox/seatbelt/base.sbpl b/internal/localsandbox/seatbelt/base.sbpl new file mode 100644 index 00000000..73165797 --- /dev/null +++ b/internal/localsandbox/seatbelt/base.sbpl @@ -0,0 +1,39 @@ +;; Base policy for WeKnora Lite's local sandbox. +;; Deny-by-default; everything else is granted explicitly by the compiler. + +(version 1) +(deny default) + +(allow process-exec) +(allow process-fork) +(allow signal (target same-sandbox)) +(allow process-info* (target same-sandbox)) + +(allow sysctl-read) + +;; darwin 25: a platform subpath allowlist is not enough to exec /bin/echo +;; (sandbox-exec SIGABRT). Unfiltered file-read* is required; DenyRead +;; (emitted last by the compiler) is what actually restricts reads. +;; This also matches Windows WRITE_RESTRICTED and lets ~/.nvm etc. work. +(allow file-read*) + +(allow file-read-metadata) + +;; Character devices and the controlling terminal. git status needs /dev/null. +(allow file-read* (literal "/dev/null") (literal "/dev/zero") + (literal "/dev/random") (literal "/dev/urandom")) +(allow file-write-data + (require-all (path "/dev/null") (vnode-type CHARACTER-DEVICE))) +(allow file-read* file-write* file-ioctl (literal "/dev/ptmx") (literal "/dev/tty")) +(allow file-read* file-write* file-ioctl (regex #"^/dev/ttys[0-9]+$")) +(allow file-read* (subpath "/dev/fd")) + +;; Python multiprocessing (sem) and OpenMP (named shm). +(allow ipc-posix-sem) +(allow ipc-posix-shm-read-data + ipc-posix-shm-write-create + ipc-posix-shm-write-unlink + (ipc-posix-name-regex #"^/__KMP_REGISTERED_LIB_[0-9]+$")) +(allow pseudo-tty) + +(allow mach-lookup (global-name "com.apple.system.opendirectoryd.libinfo")) diff --git a/internal/localsandbox/seatbelt/compiler.go b/internal/localsandbox/seatbelt/compiler.go new file mode 100644 index 00000000..f35d6b31 --- /dev/null +++ b/internal/localsandbox/seatbelt/compiler.go @@ -0,0 +1,171 @@ +// Package seatbelt implements the sandbox backend for macOS on top of +// /usr/bin/sandbox-exec. The policy compiler in this package carries no build +// tag so it stays testable on every platform. +package seatbelt + +import ( + _ "embed" + "fmt" + "strings" + + "github.com/Tencent/WeKnora/internal/localsandbox/core" +) + +//go:embed base.sbpl +var seatbeltBasePolicy string + +// seatbeltProgram is a compiled policy ready to hand to sandbox-exec. +type seatbeltProgram struct { + // Profile is the sbpl text. It never contains a caller-supplied path. + Profile string + // Params are the -DNAME=VALUE arguments carrying those paths. + Params []string +} + +// compileSeatbelt turns a core.Policy into sbpl text plus -D parameters. +// +// Every path travels as a parameter and is referenced from the profile as +// (param "NAME"). Inlining paths would require escaping them into both string +// and regex contexts, which is exactly the class of bug this avoids. +func compileSeatbelt(p core.Policy) (seatbeltProgram, error) { + if err := p.Validate(); err != nil { + return seatbeltProgram{}, err + } + + var params []string + // Four ordered tiers. sbpl gives precedence to the rule written later, so + // the order below *is* the policy: + // + // writeAllows workspace writes, network + // privateDenies the user's home, denied for reading as a whole + // readAllows workspace + toolchains, re-opened inside that deny + // denies credentials and root anchors, final say + // + // Reads cannot simply sit in the first tier: the base profile grants + // blanket file-read*, so the private deny has to come after every broad + // allow, and the paths it must not cover have to come after it in turn. + var writeAllows []string + var privateDenies []string + var readAllows []string + var denies []string + + for i, root := range p.WritableRoots { + rootParam := fmt.Sprintf("WRITABLE_ROOT_%d", i) + params = append(params, fmt.Sprintf("-D%s=%s", rootParam, root.Path)) + + clauses := []string{fmt.Sprintf(`(subpath (param %q))`, rootParam)} + for j, sub := range root.ReadOnlySubpaths { + subParam := fmt.Sprintf("%s_EXCLUDED_%d", rootParam, j) + params = append(params, fmt.Sprintf("-D%s=%s", subParam, sub)) + // Both forms are required: subpath alone still permits creating + // the protected directory itself. + clauses = append(clauses, + fmt.Sprintf(`(require-not (literal (param %q)))`, subParam), + fmt.Sprintf(`(require-not (subpath (param %q)))`, subParam), + ) + } + writeAllows = append(writeAllows, + fmt.Sprintf("(allow file-write* (require-all %s))", strings.Join(clauses, " ")), + ) + readAllows = append(readAllows, + fmt.Sprintf("(allow file-read* (subpath (param %q)))", rootParam), + ) + // The writable root is the authority boundary the next policy build + // reuses; it must not be replaceable by a symlink. + denies = append(denies, fmt.Sprintf( + `(deny file-write-unlink (require-all (literal (param %q)) (vnode-type DIRECTORY)))`, + rootParam)) + + for j := range root.ReadOnlySubpaths { + subParam := fmt.Sprintf("%s_EXCLUDED_%d", rootParam, j) + // Renaming the parent of a protected subtree would move it out of + // its carve-out, so deny unlinking the carve-out itself too. + denies = append(denies, fmt.Sprintf( + `(deny file-write-unlink (require-all (literal (param %q)) (vnode-type DIRECTORY)))`, + subParam)) + } + } + + for i, private := range p.PrivateRoots { + param := fmt.Sprintf("PRIVATE_ROOT_%d", i) + params = append(params, fmt.Sprintf("-D%s=%s", param, private)) + // Read only. Writing is already confined to the writable roots, and + // denying writes here would revoke the workspace along with them. + privateDenies = append(privateDenies, + fmt.Sprintf("(deny file-read* (subpath (param %q)))", param)) + } + + for i, root := range p.ReadableRoots { + param := fmt.Sprintf("READABLE_ROOT_%d", i) + params = append(params, fmt.Sprintf("-D%s=%s", param, root)) + // A readable root may be a single file — a shell startup script — + // which subpath does not match on its own. + readAllows = append(readAllows, + fmt.Sprintf("(allow file-read* (subpath (param %q)))", param), + fmt.Sprintf("(allow file-read* (literal (param %q)))", param), + ) + } + + networkRules, err := seatbeltNetworkRules(p) + if err != nil { + return seatbeltProgram{}, err + } + writeAllows = append(writeAllows, networkRules...) + + for i, deny := range p.DenyRead { + param := fmt.Sprintf("DENY_READ_%d", i) + params = append(params, fmt.Sprintf("-D%s=%s", param, deny)) + denies = append(denies, + fmt.Sprintf("(deny file-read* (subpath (param %q)))", param), + fmt.Sprintf("(deny file-read* (literal (param %q)))", param), + fmt.Sprintf("(deny file-write* (subpath (param %q)))", param), + fmt.Sprintf("(deny file-write* (literal (param %q)))", param), + ) + } + + sections := []string{seatbeltBasePolicy} + sections = append(sections, writeAllows...) + sections = append(sections, privateDenies...) + sections = append(sections, readAllows...) + // Credential denies and root anchors come last so nothing above can + // reopen them. + sections = append(sections, denies...) + + return seatbeltProgram{ + Profile: strings.Join(sections, "\n") + "\n", + Params: params, + }, nil +} + +func seatbeltNetworkRules(p core.Policy) ([]string, error) { + switch p.Network { + case core.NetworkDenied: + // No allow rule at all; (deny default) in the base policy covers it. + return nil, nil + case core.NetworkUnrestricted: + return []string{ + "(allow network-outbound)", + "(allow network-inbound)", + "(allow network-bind)", + `(allow system-socket)`, + }, nil + case core.NetworkLoopback: + if len(p.LoopbackPorts) == 0 { + // Fail closed rather than silently widening to every port. + return nil, fmt.Errorf( + "localsandbox: loopback network mode requires at least one port") + } + rules := []string{`(allow system-socket)`} + for _, port := range p.LoopbackPorts { + if port < 1 || port > 65535 { + return nil, fmt.Errorf("localsandbox: invalid loopback port %d", port) + } + // sandbox-exec rejects 127.0.0.1 here: "host must be * or localhost". + rules = append(rules, + fmt.Sprintf(`(allow network-outbound (remote ip "localhost:%d"))`, port)) + } + return rules, nil + default: + return nil, fmt.Errorf("localsandbox: unknown network mode %d", p.Network) + } +} diff --git a/internal/localsandbox/seatbelt/compiler_test.go b/internal/localsandbox/seatbelt/compiler_test.go new file mode 100644 index 00000000..d297f08d --- /dev/null +++ b/internal/localsandbox/seatbelt/compiler_test.go @@ -0,0 +1,165 @@ +package seatbelt + +import ( + "strings" + "testing" + + "github.com/stretchr/testify/require" + + "github.com/Tencent/WeKnora/internal/localsandbox/core" +) + +func seatbeltPolicy() core.Policy { + return core.Policy{ + WritableRoots: []core.WritableRoot{{ + Path: "/Users/dev/My Project", + ReadOnlySubpaths: []string{"/Users/dev/My Project/.git"}, + }}, + ReadableRoots: []string{"/opt/tools"}, + PrivateRoots: []string{"/Users/dev"}, + DenyRead: []string{"/Users/dev/.ssh"}, + Network: core.NetworkDenied, + Cwd: "/Users/dev/My Project", + } +} + +// The base profile has to grant blanket file-read* (see base.sbpl), so the +// only way to protect the user's data is to deny their home afterwards and +// re-open the workspace after that. Order is the whole mechanism. +func TestCompileSeatbeltDeniesPrivateRootThenReopensWorkspace(t *testing.T) { + prog, err := compileSeatbelt(seatbeltPolicy()) + require.NoError(t, err) + + require.Contains(t, prog.Params, "-DPRIVATE_ROOT_0=/Users/dev") + privateDeny := strings.Index(prog.Profile, `(deny file-read* (subpath (param "PRIVATE_ROOT_0")))`) + require.GreaterOrEqual(t, privateDeny, 0) + + workspaceRead := strings.Index(prog.Profile, `(allow file-read* (subpath (param "WRITABLE_ROOT_0")))`) + require.Greater(t, workspaceRead, privateDeny, + "the workspace read must be re-opened after the private deny") + + credentialDeny := strings.Index(prog.Profile, `(deny file-read* (subpath (param "DENY_READ_0")))`) + require.Greater(t, credentialDeny, workspaceRead, + "credential denies must still win over every re-opened read") +} + +// A readable root may be a single file (a shell rc file), which subpath does +// not match on its own. +func TestCompileSeatbeltEmitsReadableRootAsSubpathAndLiteral(t *testing.T) { + prog, err := compileSeatbelt(seatbeltPolicy()) + require.NoError(t, err) + + require.Contains(t, prog.Profile, `(allow file-read* (subpath (param "READABLE_ROOT_0")))`) + require.Contains(t, prog.Profile, `(allow file-read* (literal (param "READABLE_ROOT_0")))`) +} + +// Writing must survive the private deny: that deny is read-only by design. +func TestCompileSeatbeltPrivateRootDoesNotRevokeWorkspaceWrite(t *testing.T) { + prog, err := compileSeatbelt(seatbeltPolicy()) + require.NoError(t, err) + + privateDeny := strings.Index(prog.Profile, `(deny file-read* (subpath (param "PRIVATE_ROOT_0")))`) + require.NotContains(t, prog.Profile[privateDeny:], `(deny file-write* (subpath (param "PRIVATE_ROOT_0")))`) +} + +// Paths must travel as -D parameters, never inlined, so quoting and regex +// metacharacters in user paths can never reach the policy text. +func TestCompileSeatbeltPassesPathsAsParams(t *testing.T) { + prog, err := compileSeatbelt(seatbeltPolicy()) + require.NoError(t, err) + + require.Contains(t, prog.Params, "-DWRITABLE_ROOT_0=/Users/dev/My Project") + require.Contains(t, prog.Params, "-DWRITABLE_ROOT_0_EXCLUDED_0=/Users/dev/My Project/.git") + require.Contains(t, prog.Params, "-DREADABLE_ROOT_0=/opt/tools") + require.Contains(t, prog.Params, "-DDENY_READ_0=/Users/dev/.ssh") + require.NotContains(t, prog.Profile, "/Users/dev") +} + +// literal and subpath must both be excluded, otherwise creating the protected +// directory itself (mkdir .git) succeeds. +func TestCompileSeatbeltExcludesReadOnlySubpathTwice(t *testing.T) { + prog, err := compileSeatbelt(seatbeltPolicy()) + require.NoError(t, err) + + require.Contains(t, prog.Profile, + `(require-not (literal (param "WRITABLE_ROOT_0_EXCLUDED_0")))`) + require.Contains(t, prog.Profile, + `(require-not (subpath (param "WRITABLE_ROOT_0_EXCLUDED_0")))`) +} + +// A credential path may be a file (~/.npmrc, ~/.cargo/credentials.toml). +// subpath does not match a file, which is why reads already emit literal; +// the write deny has to do the same or a writable home still clobbers it. +func TestCompileSeatbeltDeniesCredentialWriteAsSubpathAndLiteral(t *testing.T) { + prog, err := compileSeatbelt(seatbeltPolicy()) + require.NoError(t, err) + + require.Contains(t, prog.Profile, `(deny file-write* (subpath (param "DENY_READ_0")))`) + require.Contains(t, prog.Profile, `(deny file-write* (literal (param "DENY_READ_0")))`) +} + +// sbpl gives precedence to later rules, so every deny must follow every allow. +func TestCompileSeatbeltPutsDeniesLast(t *testing.T) { + prog, err := compileSeatbelt(seatbeltPolicy()) + require.NoError(t, err) + + lastAllow := strings.LastIndex(prog.Profile, "(allow ") + firstDenyRead := strings.Index(prog.Profile, `(deny file-read* (subpath (param "DENY_READ_0")))`) + require.Greater(t, firstDenyRead, lastAllow) +} + +// Replacing the writable root with a symlink would invalidate the next +// policy build, so unlinking the root directory itself is denied. +func TestCompileSeatbeltAnchorsWritableRoot(t *testing.T) { + prog, err := compileSeatbelt(seatbeltPolicy()) + require.NoError(t, err) + + require.Contains(t, prog.Profile, + `(deny file-write-unlink (require-all (literal (param "WRITABLE_ROOT_0")) (vnode-type DIRECTORY)))`) +} + +func TestCompileSeatbeltDeniesNetworkByDefault(t *testing.T) { + prog, err := compileSeatbelt(seatbeltPolicy()) + require.NoError(t, err) + require.NotContains(t, prog.Profile, "network-outbound") +} + +func TestCompileSeatbeltBasePolicyAllowsUnfilteredFileRead(t *testing.T) { + prog, err := compileSeatbelt(seatbeltPolicy()) + require.NoError(t, err) + require.Contains(t, prog.Profile, "(allow file-read*)") + require.NotRegexp(t, `(?m)^\(allow file-write\*\)$`, prog.Profile) +} + +func TestCompileSeatbeltAllowsConfiguredLoopbackPorts(t *testing.T) { + p := seatbeltPolicy() + p.Network = core.NetworkLoopback + p.LoopbackPorts = []int{11434} + + prog, err := compileSeatbelt(p) + require.NoError(t, err) + require.Contains(t, prog.Profile, `(allow network-outbound (remote ip "localhost:11434"))`) +} + +// Loopback mode without any port is a configuration error, not "allow all". +func TestCompileSeatbeltFailsClosedOnLoopbackWithoutPorts(t *testing.T) { + p := seatbeltPolicy() + p.Network = core.NetworkLoopback + + _, err := compileSeatbelt(p) + require.Error(t, err) +} + +func TestCompileSeatbeltRejectsInvalidPolicy(t *testing.T) { + _, err := compileSeatbelt(core.Policy{Cwd: "/tmp/work"}) + require.ErrorIs(t, err, core.ErrNoWritableRoot) +} + +func TestCompileSeatbeltAllowsAskModeWithNoWritableRoot(t *testing.T) { + p := seatbeltPolicy() + p.WritableRoots = nil + p.ReadableRoots = append(p.ReadableRoots, p.Cwd) + prog, err := compileSeatbelt(p) + require.NoError(t, err) + require.NotContains(t, prog.Profile, "WRITABLE_ROOT") +} diff --git a/internal/localsandbox/service.go b/internal/localsandbox/service.go new file mode 100644 index 00000000..cb7999a1 --- /dev/null +++ b/internal/localsandbox/service.go @@ -0,0 +1,291 @@ +package localsandbox + +import ( + "context" + "fmt" + "io" + "strings" + "sync" + "time" + + "github.com/Tencent/WeKnora/internal/logger" + "github.com/Tencent/WeKnora/internal/utils" +) + +// defaultRunTimeout matches the shell_exec tool default so behaviour does not +// change when a session moves between a remote sandbox and this one. +const defaultRunTimeout = 120 * time.Second + +// maxRunTimeout hard-caps whatever the caller asks for. +const maxRunTimeout = 10 * time.Minute + +// maxCapturedStreamBytes bounds what one stream of one command can pull into +// this process. shell_exec caps the model-visible slice far lower (64 KiB +// hard), but that truncation runs on the string the executor already +// returned. On a remote backend the bytes pile up on the other machine; here +// the producer is a local process and the consumer is the desktop app, so +// `cat /dev/urandom` would grow the heap until the run timeout fires. +const maxCapturedStreamBytes = 1 << 20 + +// ModeLookup reports the approval mode in force for a session. +type ModeLookup interface { + ModeForSession(ctx context.Context, sessionID string) ApprovalMode +} + +// Service is the facade the application layer uses. It hides policy +// derivation, preparation, spawning and denial classification behind one call. +type Service struct { + backend Backend + resolver WorkspaceResolver + builder *PolicyBuilder + modes ModeLookup + shell []string + roots *rootLocks +} + +// NewService constructs the application-facing sandbox facade. +func NewService( + backend Backend, resolver WorkspaceResolver, builder *PolicyBuilder, modes ModeLookup, +) *Service { + return &Service{ + backend: backend, + resolver: resolver, + builder: builder, + modes: modes, + shell: []string{"/bin/bash", "--noprofile", "--norc", "-c"}, + roots: newRootLocks(), + } +} + +// RunRequest is one shell command to execute inside a session workspace. +type RunRequest struct { + SessionID string + Command string + // WorkDir is optional and must stay inside the workspace. + WorkDir string + Timeout time.Duration + // Env overlays the filtered host inherit. It is not itself allowlisted: + // pass only the keys this command needs (skill credentials, PATH tweaks). + // Do not copy os.Environ() into it. + Env map[string]string +} + +// RunResult is the captured outcome of one Run. +type RunResult struct { + Stdout string + Stderr string + Exit ExitStatus + Denial Denial +} + +// workspaceFor resolves the session workspace and its policy. +func (s *Service) workspaceFor( + ctx context.Context, sessionID string, +) (Workspace, Policy, error) { + ws, err := s.resolver.Resolve(ctx, sessionID) + if err != nil { + logger.Warnf(ctx, "[LocalSandbox] resolve workspace session=%s: %v", sessionID, err) + return Workspace{}, Policy{}, err + } + mode := ModeAuto + if s.modes != nil { + mode = s.modes.ModeForSession(ctx, sessionID) + } + // Strict enforcement boundary. Normalizing user input is the caller's job + // (see ParseApprovalMode); by the time a mode reaches here, honouring it + // or refusing are the only honest options — substituting a different + // permission stance for the one that was asked for is not. + if !mode.Shipped() { + logger.Warnf(ctx, "[LocalSandbox] refusing session=%s: approval mode %q is not available", + sessionID, mode) + return Workspace{}, Policy{}, fmt.Errorf("%w: %q", ErrApprovalModeNotShipped, mode) + } + policy, err := s.builder.Build(mode, ws) + if err != nil { + logger.Warnf(ctx, "[LocalSandbox] build policy session=%s mode=%s root=%s: %v", + sessionID, mode, ws.Root, err) + return Workspace{}, Policy{}, err + } + logger.Debugf(ctx, "[LocalSandbox] workspace session=%s kind=%d root=%s mode=%s writable=%d", + sessionID, ws.Kind, ws.Root, mode, len(policy.WritableRoots)) + return ws, policy, nil +} + +// GuardForSession returns the path guard the trusted file tools must use. +// It derives from the same Policy the backend compiles, which is what keeps +// the two enforcement paths in agreement. +func (s *Service) GuardForSession( + ctx context.Context, sessionID string, +) (*PathGuard, Workspace, error) { + ws, policy, err := s.workspaceFor(ctx, sessionID) + if err != nil { + return nil, Workspace{}, err + } + logger.Debugf(ctx, "[LocalSandbox] guard session=%s root=%s", sessionID, ws.Root) + return NewPathGuard(policy), ws, nil +} + +// Run executes one shell command inside the session's workspace. +func (s *Service) Run(ctx context.Context, req RunRequest) (*RunResult, error) { + if err := s.backend.Available(); err != nil { + logger.Errorf(ctx, "[LocalSandbox] backend unavailable: %v", err) + return nil, err + } + if err := s.backend.EnsureReady(ctx); err != nil { + logger.Errorf(ctx, "[LocalSandbox] backend not ready: %v", err) + return nil, fmt.Errorf("ensure sandbox ready: %w", err) + } + ws, policy, err := s.workspaceFor(ctx, req.SessionID) + if err != nil { + return nil, err + } + unlock := s.LockRoot(ws.Root) + defer unlock() + + cwd := ws.Root + if req.WorkDir != "" { + // work_dir is a convenience for the model, not a privilege boundary; + // it is checked against the same guard the file tools use. + resolved, err := NewPathGuard(policy).CheckDir(req.WorkDir) + if err != nil { + logger.Warnf(ctx, "[LocalSandbox] work_dir denied session=%s work_dir=%q: %v", + req.SessionID, req.WorkDir, err) + return nil, err + } + cwd = resolved + } + + timeout := req.Timeout + if timeout <= 0 { + timeout = defaultRunTimeout + } + if timeout > maxRunTimeout { + timeout = maxRunTimeout + } + logger.Infof(ctx, "[LocalSandbox] run session=%s cwd=%s timeout=%s command=%q", + req.SessionID, cwd, timeout, previewCommand(req.Command)) + runCtx, cancel := context.WithTimeout(ctx, timeout) + defer cancel() + + prep, err := s.backend.Prepare(runCtx, policy) + if err != nil { + logger.Errorf(ctx, "[LocalSandbox] prepare session=%s: %v", req.SessionID, err) + return nil, fmt.Errorf("prepare sandbox: %w", err) + } + defer func() { _ = prep.Close() }() + + argv := append(append([]string(nil), s.shell...), req.Command) + var extraPATH []string + if s.builder != nil { + extraPATH = s.builder.ToolchainBins() + } + proc, err := s.backend.Spawn(runCtx, prep, Command{ + Argv: argv, + Env: BuildCommandEnv(req.Env, extraPATH), + Cwd: cwd, + }) + if err != nil { + logger.Errorf(ctx, "[LocalSandbox] spawn session=%s cwd=%s: %v", req.SessionID, cwd, err) + return nil, fmt.Errorf("spawn sandboxed command: %w", err) + } + + // Kill the process group on timeout or caller cancel. Stop the watcher + // as soon as Wait returns so a finished process is never signalled — + // process-group Kill(-pid) after wait has a PID-reuse window. + // Drain both pipes concurrently before Wait: sequential reads deadlock + // when the unread pipe fills. + done := make(chan struct{}) + watchDone := make(chan struct{}) + go func() { + defer close(watchDone) + watchKill(runCtx, done, proc) + }() + + stdout, stderr := drain(proc) + status, err := proc.Wait(runCtx) + close(done) + <-watchDone + if err != nil { + logger.Errorf(ctx, "[LocalSandbox] wait session=%s: %v", req.SessionID, err) + return nil, err + } + + denial := ClassifyRunDenial(policy, status, stdout, stderr) + if denial.IsDenied() { + logger.Warnf(ctx, "[LocalSandbox] denied session=%s reason=%d path=%q exit=%d killed=%t duration=%s", + req.SessionID, denial.Reason, denial.Path, status.Code, status.Killed, status.Duration) + } else { + logger.Infof(ctx, "[LocalSandbox] done session=%s exit=%d killed=%t duration=%s stdout=%d stderr=%d", + req.SessionID, status.Code, status.Killed, status.Duration, len(stdout), len(stderr)) + } + + return &RunResult{ + Stdout: stdout, + Stderr: stderr, + Exit: status, + Denial: denial, + }, nil +} + +func watchKill(ctx context.Context, done <-chan struct{}, proc Process) { + select { + case <-done: + return + case <-ctx.Done(): + } + select { + case <-done: + return + default: + _ = proc.Kill() + } +} + +const commandLogLimit = 240 + +func previewCommand(command string) string { + command = strings.Join(strings.Fields(command), " ") + command = utils.MaskCommandAssignments(command) + if len(command) <= commandLogLimit { + return command + } + return command[:commandLogLimit] + "…" +} + +func drain(proc Process) (string, string) { + var ( + stdout string + stderr string + wg sync.WaitGroup + ) + wg.Add(2) + go func() { + defer wg.Done() + stdout = captureStream(proc.Stdout()) + }() + go func() { + defer wg.Done() + stderr = captureStream(proc.Stderr()) + }() + wg.Wait() + return stdout, stderr +} + +// captureStream keeps at most maxCapturedStreamBytes and discards the rest. +// +// Discarding rather than closing matters: a child blocked writing into a full +// pipe never exits, and Wait would block behind it until the run timeout. +func captureStream(r io.Reader) string { + if r == nil { + return "" + } + kept, err := io.ReadAll(io.LimitReader(r, maxCapturedStreamBytes)) + if err != nil || len(kept) < maxCapturedStreamBytes { + return string(kept) + } + dropped, _ := io.Copy(io.Discard, r) + if dropped == 0 { + return string(kept) + } + return fmt.Sprintf("%s\n...[truncated %d more bytes]...", kept, dropped) +} diff --git a/internal/localsandbox/service_test.go b/internal/localsandbox/service_test.go new file mode 100644 index 00000000..62a30375 --- /dev/null +++ b/internal/localsandbox/service_test.go @@ -0,0 +1,516 @@ +package localsandbox + +import ( + "bytes" + "context" + "io" + "os" + "path/filepath" + "strings" + "sync" + "testing" + "time" + + "github.com/stretchr/testify/require" +) + +type fakeBackend struct { + mu sync.Mutex + prepared []string + spawnCmd Command + stdout string + stderr string + exit ExitStatus + spawnErr error + available error + ensureReady error + calls []string + proc Process + onSpawn func() +} + +func (f *fakeBackend) Name() string { return "fake" } +func (f *fakeBackend) Available() error { + f.mu.Lock() + f.calls = append(f.calls, "available") + err := f.available + f.mu.Unlock() + return err +} + +func (f *fakeBackend) EnsureReady(context.Context) error { + f.mu.Lock() + f.calls = append(f.calls, "ready") + err := f.ensureReady + f.mu.Unlock() + return err +} +func (f *fakeBackend) TearDown(context.Context) error { return nil } + +type fakePrepared struct{ fp string } + +func (p fakePrepared) Fingerprint() string { return p.fp } +func (p fakePrepared) Close() error { return nil } + +func (f *fakeBackend) Prepare(_ context.Context, p Policy) (Prepared, error) { + f.mu.Lock() + f.calls = append(f.calls, "prepare") + f.prepared = append(f.prepared, p.Fingerprint()) + f.mu.Unlock() + return fakePrepared{fp: p.Fingerprint()}, nil +} + +func (f *fakeBackend) Spawn(_ context.Context, _ Prepared, cmd Command) (Process, error) { + if f.onSpawn != nil { + f.onSpawn() + } + f.mu.Lock() + defer f.mu.Unlock() + if f.spawnErr != nil { + return nil, f.spawnErr + } + f.spawnCmd = cmd + if f.proc != nil { + return f.proc, nil + } + return &fakeProcess{ + stdout: io.NopCloser(bytes.NewBufferString(f.stdout)), + stderr: io.NopCloser(bytes.NewBufferString(f.stderr)), + exit: f.exit, + }, nil +} + +type fakeProcess struct { + stdout io.ReadCloser + stderr io.ReadCloser + exit ExitStatus +} + +func (p *fakeProcess) Stdout() io.Reader { return p.stdout } +func (p *fakeProcess) Stderr() io.Reader { return p.stderr } +func (p *fakeProcess) Kill() error { return nil } +func (p *fakeProcess) PID() int { return 1 } +func (p *fakeProcess) Wait(context.Context) (ExitStatus, error) { return p.exit, nil } + +type fakeProjects struct{} + +func (fakeProjects) ProjectDirForSession(context.Context, string) (string, bool) { + return "", false +} + +type fixedProject string + +func (p fixedProject) ProjectDirForSession(context.Context, string) (string, bool) { + return string(p), true +} + +type fixedMode ApprovalMode + +func (m fixedMode) ModeForSession(context.Context, string) ApprovalMode { + return ApprovalMode(m) +} + +func serviceFixture(t *testing.T, backend *fakeBackend, mode ApprovalMode) *Service { + t.Helper() + return serviceFixtureWithProjects(t, backend, mode, fakeProjects{}) +} + +func serviceFixtureWithProjects( + t *testing.T, backend *fakeBackend, mode ApprovalMode, projects ProjectLookup, +) *Service { + t.Helper() + base := t.TempDir() + home := filepath.Join(base, "home") + appData := filepath.Join(home, "App Support", "WeKnora Lite") + resolver := NewWorkspaceResolver(DirLayout{ + SessionRoot: filepath.Join(home, "Documents", "WeKnora"), + }, projects) + return NewService(backend, resolver, NewPolicyBuilder(home, appData), fixedMode(mode)) +} + +func TestServiceRunReturnsOutput(t *testing.T) { + backend := &fakeBackend{stdout: "hello\n", exit: ExitStatus{Code: 0}} + svc := serviceFixture(t, backend, ModeAuto) + + res, err := svc.Run(context.Background(), RunRequest{SessionID: "s1", Command: "echo hello"}) + require.NoError(t, err) + require.Equal(t, "hello\n", res.Stdout) + require.Equal(t, 0, res.Exit.Code) + require.False(t, res.Denial.IsDenied()) +} + +// shell_exec caps the model-visible slice, but only after the executor has +// already returned the whole string. On host the producer is a local process +// and the consumer is the desktop app itself, so the cap has to be here. +func TestServiceRunCapsHugeStdout(t *testing.T) { + huge := strings.Repeat("a", maxCapturedStreamBytes*3) + backend := &fakeBackend{stdout: huge, exit: ExitStatus{Code: 0}} + svc := serviceFixture(t, backend, ModeAuto) + + res, err := svc.Run(context.Background(), RunRequest{SessionID: "s1", Command: "cat big"}) + require.NoError(t, err) + require.Less(t, len(res.Stdout), len(huge)) + require.LessOrEqual(t, len(res.Stdout), maxCapturedStreamBytes+128) + require.Contains(t, res.Stdout, "truncated") +} + +func TestServiceRunCapsHugeStderr(t *testing.T) { + huge := strings.Repeat("e", maxCapturedStreamBytes*2) + backend := &fakeBackend{stderr: huge, exit: ExitStatus{Code: 1}} + svc := serviceFixture(t, backend, ModeAuto) + + res, err := svc.Run(context.Background(), RunRequest{SessionID: "s1", Command: "noisy"}) + require.NoError(t, err) + require.LessOrEqual(t, len(res.Stderr), maxCapturedStreamBytes+128) +} + +// Truncating must not stop reading: a child blocked writing into a full pipe +// never exits, and Wait would hang behind it. +func TestServiceRunDrainsPipeAfterCap(t *testing.T) { + huge := strings.Repeat("a", maxCapturedStreamBytes*2) + counter := &countingReader{inner: strings.NewReader(huge)} + backend := &fakeBackend{proc: &fakeProcess{ + stdout: io.NopCloser(counter), + stderr: io.NopCloser(strings.NewReader("")), + }} + svc := serviceFixture(t, backend, ModeAuto) + + _, err := svc.Run(context.Background(), RunRequest{SessionID: "s1", Command: "cat big"}) + require.NoError(t, err) + require.Equal(t, len(huge), counter.read, "the pipe must be drained to EOF") +} + +type countingReader struct { + inner io.Reader + read int +} + +func (c *countingReader) Read(p []byte) (int, error) { + n, err := c.inner.Read(p) + c.read += n + return n, err +} + +func TestServiceRunClassifiesDenial(t *testing.T) { + backend := &fakeBackend{ + stderr: "touch: /etc/x: Operation not permitted", + exit: ExitStatus{Code: 1}, + } + svc := serviceFixture(t, backend, ModeAuto) + + res, err := svc.Run(context.Background(), RunRequest{SessionID: "s1", Command: "touch /etc/x"}) + require.NoError(t, err) + require.True(t, res.Denial.IsDenied()) + require.Equal(t, DenialOperationNotPermitted, res.Denial.Reason) +} + +// Full access is the one mode that must never reach Prepare. +func TestServiceRunRejectsFullAccessUntilImplemented(t *testing.T) { + backend := &fakeBackend{} + svc := serviceFixture(t, backend, ModeFull) + + _, err := svc.Run(context.Background(), RunRequest{SessionID: "s1", Command: "echo hi"}) + require.ErrorIs(t, err, ErrApprovalModeNotShipped) + require.Empty(t, backend.prepared) +} + +// Ask compiles to a perfectly valid policy with nothing writable, so without +// the approval loop above it every write fails with a bare path-denied error +// and no explanation. Refuse the turn instead of running it half-disabled. +func TestServiceRunRefusesModeItCannotEnforce(t *testing.T) { + backend := &fakeBackend{} + svc := serviceFixture(t, backend, ModeAsk) + + _, err := svc.Run(context.Background(), RunRequest{SessionID: "s1", Command: "echo hi"}) + require.ErrorIs(t, err, ErrApprovalModeNotShipped) + require.Empty(t, backend.prepared) +} + +// Substituting a mode the caller did not ask for is the failure this guards: +// ask is stricter than auto, so quietly running auto would widen access. +func TestServiceRunDoesNotSubstituteAutoForAsk(t *testing.T) { + backend := &fakeBackend{exit: ExitStatus{Code: 0}} + svc := serviceFixture(t, backend, ModeAsk) + + res, err := svc.Run(context.Background(), RunRequest{SessionID: "s1", Command: "echo hi"}) + require.Error(t, err) + require.Nil(t, res) +} + +func TestServiceRunRunsInWorkspace(t *testing.T) { + backend := &fakeBackend{exit: ExitStatus{Code: 0}} + svc := serviceFixture(t, backend, ModeAuto) + + _, err := svc.Run(context.Background(), RunRequest{SessionID: "s1", Command: "pwd"}) + require.NoError(t, err) + + ws, _, err := svc.workspaceFor(context.Background(), "s1") + require.NoError(t, err) + require.Equal(t, ws.Root, backend.spawnCmd.Cwd) +} + +// work_dir is a convenience, not a privilege boundary: it must stay inside +// the workspace or the call fails before anything is spawned. +func TestServiceRunRejectsWorkDirOutsideWorkspace(t *testing.T) { + backend := &fakeBackend{} + svc := serviceFixture(t, backend, ModeAuto) + + _, err := svc.Run(context.Background(), RunRequest{ + SessionID: "s1", Command: "ls", WorkDir: "/etc", + }) + require.ErrorIs(t, err, ErrPathDenied) +} + +func TestServiceRunAppliesDefaultTimeout(t *testing.T) { + backend := &fakeBackend{exit: ExitStatus{Code: 0}} + svc := serviceFixture(t, backend, ModeAuto) + + res, err := svc.Run(context.Background(), RunRequest{ + SessionID: "s1", Command: "sleep 0", Timeout: 0, + }) + require.NoError(t, err) + require.NotNil(t, res) +} + +func TestServiceGuardMatchesPolicy(t *testing.T) { + backend := &fakeBackend{} + svc := serviceFixture(t, backend, ModeAuto) + + guard, ws, err := svc.GuardForSession(context.Background(), "s1") + require.NoError(t, err) + + _, err = guard.CheckWrite(filepath.Join(ws.Root, "file.txt")) + require.NoError(t, err) + _, err = guard.CheckWrite(filepath.Join(filepath.Dir(ws.Root), "outside.txt")) + require.ErrorIs(t, err, ErrPathDenied) +} + +type recordingProcess struct { + stdout io.ReadCloser + stderr io.ReadCloser + exit ExitStatus + blockUntilKill bool + + mu sync.Mutex + kills int + killed chan struct{} + closeOnce sync.Once +} + +func newRecordingProcess(exit ExitStatus) *recordingProcess { + return &recordingProcess{ + stdout: io.NopCloser(bytes.NewBuffer(nil)), + stderr: io.NopCloser(bytes.NewBuffer(nil)), + exit: exit, + killed: make(chan struct{}), + } +} + +func (p *recordingProcess) Stdout() io.Reader { return p.stdout } +func (p *recordingProcess) Stderr() io.Reader { return p.stderr } +func (p *recordingProcess) PID() int { return 1 } + +func (p *recordingProcess) Kill() error { + p.mu.Lock() + p.kills++ + p.mu.Unlock() + p.closeOnce.Do(func() { close(p.killed) }) + return nil +} + +func (p *recordingProcess) killCount() int { + p.mu.Lock() + defer p.mu.Unlock() + return p.kills +} + +func (p *recordingProcess) Wait(context.Context) (ExitStatus, error) { + if !p.blockUntilKill { + return p.exit, nil + } + <-p.killed + return ExitStatus{Code: -1, Killed: true}, nil +} + +func TestServiceRunDoesNotKillAfterSuccess(t *testing.T) { + proc := newRecordingProcess(ExitStatus{Code: 0}) + backend := &fakeBackend{proc: proc} + svc := serviceFixture(t, backend, ModeAuto) + + res, err := svc.Run(context.Background(), RunRequest{SessionID: "s1", Command: "echo hi"}) + require.NoError(t, err) + require.Equal(t, 0, res.Exit.Code) + + // The deferred timeout cancel must not race a leftover watcher into Kill. + time.Sleep(20 * time.Millisecond) + require.Equal(t, 0, proc.killCount()) +} + +func TestWatchKillSkipsWhenDoneAlreadyClosed(t *testing.T) { + proc := newRecordingProcess(ExitStatus{Code: 0}) + done := make(chan struct{}) + close(done) + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + watchKill(ctx, done, proc) + require.Equal(t, 0, proc.killCount()) +} + +func TestServiceRunCallsEnsureReadyBeforePrepare(t *testing.T) { + backend := &fakeBackend{exit: ExitStatus{Code: 0}} + svc := serviceFixture(t, backend, ModeAuto) + + _, err := svc.Run(context.Background(), RunRequest{SessionID: "s1", Command: "echo hi"}) + require.NoError(t, err) + require.Equal(t, []string{"available", "ready", "prepare"}, backend.calls) +} + +func TestServiceRunKillsOnParentCancel(t *testing.T) { + proc := newRecordingProcess(ExitStatus{Code: 0}) + proc.blockUntilKill = true + backend := &fakeBackend{proc: proc} + svc := serviceFixture(t, backend, ModeAuto) + + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + go func() { + time.Sleep(10 * time.Millisecond) + cancel() + }() + + res, err := svc.Run(ctx, RunRequest{SessionID: "s1", Command: "sleep 60"}) + require.NoError(t, err) + require.True(t, res.Exit.Killed) + require.Greater(t, proc.killCount(), 0) +} + +func TestServiceRunFailsWhenBackendUnavailable(t *testing.T) { + backend := &fakeBackend{available: ErrUnsupportedPlatform} + svc := serviceFixture(t, backend, ModeAuto) + + _, err := svc.Run(context.Background(), RunRequest{SessionID: "s1", Command: "echo hi"}) + require.ErrorIs(t, err, ErrUnsupportedPlatform) +} + +func TestServiceRunUsesNonLoginShell(t *testing.T) { + backend := &fakeBackend{exit: ExitStatus{Code: 0}} + svc := serviceFixture(t, backend, ModeAuto) + _, err := svc.Run(context.Background(), RunRequest{SessionID: "s1", Command: "echo hi"}) + require.NoError(t, err) + require.Equal(t, []string{"/bin/bash", "--noprofile", "--norc", "-c", "echo hi"}, backend.spawnCmd.Argv) +} + +func TestServiceRunDoesNotPassHostSecrets(t *testing.T) { + t.Setenv("AWS_SECRET_ACCESS_KEY", "super-secret") + t.Setenv("GITHUB_TOKEN", "gho_secret") + backend := &fakeBackend{exit: ExitStatus{Code: 0}} + svc := serviceFixture(t, backend, ModeAuto) + + _, err := svc.Run(context.Background(), RunRequest{ + SessionID: "s1", + Command: "printenv", + Env: map[string]string{"FOO": "bar"}, + }) + require.NoError(t, err) + joined := strings.Join(envMapToSlice(backend.spawnCmd.Env), "\n") + require.Contains(t, joined, "FOO=bar") + require.NotContains(t, joined, "super-secret") + require.NotContains(t, joined, "GITHUB_TOKEN") +} + +func envMapToSlice(env map[string]string) []string { + out := make([]string, 0, len(env)) + for k, v := range env { + out = append(out, k+"="+v) + } + return out +} + +func TestPreviewCommandMasksInlineAssignments(t *testing.T) { + got := previewCommand(`export TOKEN="sk-secret"; FOO=bare ./run --model cogview-4`) + require.NotContains(t, got, "sk-secret") + require.NotContains(t, got, "bare") + require.Contains(t, got, "TOKEN=***") + require.Contains(t, got, "FOO=***") + require.Contains(t, got, "--model cogview-4") +} + +// Two sessions on the same project share one directory. Overlapping Run +// would let them stomp each other's files and git state. +func TestServiceRunSerializesSharedProjectRoot(t *testing.T) { + project := t.TempDir() + require.NoError(t, os.MkdirAll(project, 0o755)) + + entered := make(chan struct{}, 2) + release := make(chan struct{}) + backend := &fakeBackend{ + exit: ExitStatus{Code: 0}, + onSpawn: func() { + entered <- struct{}{} + <-release + }, + } + svc := serviceFixtureWithProjects(t, backend, ModeAuto, fixedProject(project)) + + errCh := make(chan error, 2) + for _, id := range []string{"s1", "s2"} { + go func(sessionID string) { + _, err := svc.Run(context.Background(), RunRequest{SessionID: sessionID, Command: "pwd"}) + errCh <- err + }(id) + } + + select { + case <-entered: + case <-time.After(2 * time.Second): + t.Fatal("first command never reached Spawn") + } + select { + case <-entered: + t.Fatal("second command entered Spawn while the first still held the workspace") + case <-time.After(80 * time.Millisecond): + } + close(release) + + select { + case <-entered: + case <-time.After(2 * time.Second): + t.Fatal("second command never reached Spawn after the first released") + } + require.NoError(t, <-errCh) + require.NoError(t, <-errCh) +} + +// Distinct session workspaces must not wait on each other. +func TestServiceRunAllowsConcurrentDistinctRoots(t *testing.T) { + entered := make(chan struct{}, 2) + release := make(chan struct{}) + backend := &fakeBackend{ + exit: ExitStatus{Code: 0}, + onSpawn: func() { + entered <- struct{}{} + <-release + }, + } + svc := serviceFixture(t, backend, ModeAuto) + + errCh := make(chan error, 2) + for _, id := range []string{"s1", "s2"} { + go func(sessionID string) { + _, err := svc.Run(context.Background(), RunRequest{SessionID: sessionID, Command: "pwd"}) + errCh <- err + }(id) + } + + for i := 0; i < 2; i++ { + select { + case <-entered: + case <-time.After(2 * time.Second): + t.Fatalf("command %d never reached Spawn concurrently", i+1) + } + } + close(release) + require.NoError(t, <-errCh) + require.NoError(t, <-errCh) +} diff --git a/internal/localsandbox/winhost/backend.go b/internal/localsandbox/winhost/backend.go new file mode 100644 index 00000000..7d2e175a --- /dev/null +++ b/internal/localsandbox/winhost/backend.go @@ -0,0 +1,24 @@ +//go:build windows + +// Package winhost will implement the sandbox backend for Windows using the +// Route B design: a dedicated hidden account, a restricted token, per-root +// capability SIDs, firewall rules and a job object for the process tree. +// See spec section 6.2. Phase 3 splits this package into account.go, token.go, +// acl.go, firewall.go, install.go, spawn.go and teardown.go plus an elevated +// helper executable. +package winhost + +import ( + "context" + "fmt" + + "github.com/Tencent/WeKnora/internal/localsandbox/core" + "github.com/Tencent/WeKnora/internal/logger" +) + +// New reports Windows as unavailable rather than running unsandboxed. +func New() (core.Backend, error) { + err := fmt.Errorf("%w: windows backend is not implemented yet", core.ErrUnsupportedPlatform) + logger.Errorf(context.Background(), "[LocalSandbox] %v", err) + return nil, err +} diff --git a/internal/utils/shell_assignment.go b/internal/utils/shell_assignment.go new file mode 100644 index 00000000..14b0dbb2 --- /dev/null +++ b/internal/utils/shell_assignment.go @@ -0,0 +1,41 @@ +package utils + +import ( + "regexp" + "strings" +) + +// shellAssignmentPattern finds NAME=value in a model-built shell command. +// The name must be UPPER_SNAKE_CASE so flags like --model and URLs are not +// treated as environment variables. +var shellAssignmentPattern = regexp.MustCompile( + `(?:^|[;|&\s])(?:export\s+)?([A-Z_][A-Z0-9_]{0,127})=(?:"([^"]*)"|'([^']*)'|([^\s;|&]+))`, +) + +// MaskCommandAssignments replaces the value of every NAME=value assignment +// with a placeholder. A command is logged at Info, and passing a credential +// inline is a documented way to hand a skill its key, so the raw string must +// never reach the log. +func MaskCommandAssignments(command string) string { + return shellAssignmentPattern.ReplaceAllStringFunc(command, func(match string) string { + eq := strings.Index(match, "=") + if eq < 0 { + return match + } + return match[:eq+1] + "***" + }) +} + +// ExtractShellAssignments returns NAME=value pairs from a model-built command. +func ExtractShellAssignments(command string) map[string]string { + out := map[string]string{} + for _, match := range shellAssignmentPattern.FindAllStringSubmatch(command, -1) { + name := match[1] + value := match[2] + match[3] + match[4] + if name == "" || value == "" { + continue + } + out[name] = value + } + return out +} diff --git a/internal/utils/shell_assignment_test.go b/internal/utils/shell_assignment_test.go new file mode 100644 index 00000000..65e1fdc3 --- /dev/null +++ b/internal/utils/shell_assignment_test.go @@ -0,0 +1,29 @@ +package utils + +import ( + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestMaskCommandAssignmentsHidesValues(t *testing.T) { + command := `export BIGMODEL_API_KEY="sk-abc.def"; TOKEN=plain ./run --model cogview-4` + + got := MaskCommandAssignments(command) + + assert.NotContains(t, got, "sk-abc.def") + assert.NotContains(t, got, "plain") + assert.Contains(t, got, "BIGMODEL_API_KEY=***") + assert.Contains(t, got, "TOKEN=***") + assert.Contains(t, got, "--model cogview-4") +} + +func TestExtractShellAssignmentsFromExportAndPrefix(t *testing.T) { + command := `unset HTTP_PROXY; export BIGMODEL_API_KEY="sk-abc.def"; cd /workspace && ./run` + + got := ExtractShellAssignments(command) + + require.Equal(t, "sk-abc.def", got["BIGMODEL_API_KEY"]) + assert.NotContains(t, got, "HTTP_PROXY") +}