chore: 项目基线(基于 WeKnora 定制版,整理文件忽略规则)

This commit is contained in:
runny committed 2026-11-13 17:54:56 +08:00
commit 9097ee699d
5769 files changed
+1446466

No files matched your search

+68
View File
@@ -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
}
@@ -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())
}
+148
View File
@@ -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:]
}
+102
View File
@@ -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)
}
+108
View File
@@ -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))
}
+61
View File
@@ -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)
}
+128
View File
@@ -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
}
}
@@ -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)
}
@@ -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
}
@@ -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
}
@@ -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)
}
@@ -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,
}
}
@@ -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)
}
@@ -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)
}
+255
View File
@@ -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
}
@@ -0,0 +1,365 @@
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.
// ModeAsk compiles to a valid policy with nothing writable and relies on an
// approval round-trip to widen it per command; ModeFull is the absence of a
// policy. Neither path is wired yet, so only ModeAuto is served.
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. /var (and
// /private/var) covers /var/folders, where per-user temp tokens live.
// /tmp is not in this list: the base Seatbelt profile opens it for read
// and write. A private deny here is emitted after that allow and would
// close reads again.
var extraPrivateRoots = []string{
"/Users", "/Volumes",
"/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*. 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",
}
// ErrInstallDirOutsideSkillsRoot refuses an install policy for any directory
// that is not inside the configured skills root.
var ErrInstallDirOutsideSkillsRoot = errors.New("localsandbox: install directory is outside the skills root")
// PolicyBuilder derives a Policy from an approval mode and a workspace.
type PolicyBuilder struct {
homeDir string
appDataDir string
skillsRoot string
jobsRoot 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),
jobsRoot: filepath.Join(filepath.Clean(homeDir), ".weknora", "jobs"),
}
}
// 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{
// Auto-mode chat commands need outbound access for package installs,
// APIs, and skill tests. Ask mode keeps it denied below: a network
// denial is what routes a command to the approval prompt.
Network: NetworkUnrestricted,
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 and nothing leaves the machine up front;
// approved commands are re-prepared through Relax. Cwd stays the
// workspace so the process has a home.
p.WritableRoots = nil
p.Network = NetworkDenied
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)))
}
if b.skillsRoot != "" {
roots = append(roots, b.skillsRoot)
}
return roots
}
// WithSkillsRoot makes installed skills readable to every chat command.
func (b *PolicyBuilder) WithSkillsRoot(root string) *PolicyBuilder {
if root = strings.TrimSpace(root); root != "" {
b.skillsRoot = filepath.Clean(root)
}
return b
}
// BuildInstall is the policy one skill install runs under: only dir is
// writable, the network is open for package downloads, and deny-read is the
// same set auto mode enforces.
func (b *PolicyBuilder) BuildInstall(dir string) (Policy, error) {
dir = filepath.Clean(strings.TrimSpace(dir))
if b.skillsRoot == "" || !filepath.IsAbs(dir) ||
!PathUnder(dir, b.skillsRoot) || samePath(dir, b.skillsRoot) {
return Policy{}, fmt.Errorf("%w: %q", ErrInstallDirOutsideSkillsRoot, dir)
}
if err := b.rejectBroadWorkspace(dir); err != nil {
return Policy{}, err
}
p := Policy{
Network: NetworkUnrestricted,
Cwd: dir,
WritableRoots: []WritableRoot{{Path: dir}},
ReadableRoots: b.readableRoots(Workspace{Root: dir}),
PrivateRoots: b.privateRoots(),
DenyRead: b.denyRead(),
}
if err := p.Validate(); err != nil {
return Policy{}, err
}
return p, nil
}
// 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)
}
}
// Background jobs live under ~/.weknora/jobs. A workspace that covers that
// directory, or sits inside it, can read or replace another session's output.
if b.jobsRoot != "" && (PathUnder(b.jobsRoot, root) || PathUnder(root, b.jobsRoot)) {
return fmt.Errorf("%w: %q overlaps the background jobs directory", 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)+2)
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)
}
if b.jobsRoot != "" && !isFilesystemRoot(b.jobsRoot) {
deny = append(deny, b.jobsRoot)
}
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
}
@@ -0,0 +1,408 @@
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, NetworkUnrestricted, 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)
require.Equal(t, NetworkDenied, p.Network)
}
// 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 TestBuildKeepsVarPrivateAndLeavesTmpOpen(t *testing.T) {
b, ws := builderFixture(t)
p, err := b.Build(ModeAuto, ws)
require.NoError(t, err)
for _, root := range []string{"/var", "/private/var"} {
if !filepath.IsAbs(root) {
continue
}
require.Contains(t, p.PrivateRoots, filepath.Clean(root), root)
}
for _, root := range []string{"/tmp", "/private/tmp"} {
if !filepath.IsAbs(root) {
continue
}
require.NotContains(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)
}
func skillsBuilder(t *testing.T) (*PolicyBuilder, string) {
t.Helper()
b, _ := builderFixture(t)
root := filepath.Join(b.homeDir, ".weknora", "skills")
return b.WithSkillsRoot(root), root
}
func TestBuildAutoModeReadsButDoesNotWriteSkillsRoot(t *testing.T) {
b, root := skillsBuilder(t)
_, ws := builderFixture(t)
ws.Root = filepath.Join(b.homeDir, "My Project")
p, err := b.Build(ModeAuto, ws)
require.NoError(t, err)
require.Contains(t, p.ReadableRoots, root)
for _, w := range p.WritableRoots {
require.False(t, PathUnder(w.Path, root) || PathUnder(root, w.Path), w.Path)
}
require.Equal(t, NetworkUnrestricted, p.Network)
}
func TestBuildInstallConfinesWritesToVersionDir(t *testing.T) {
b, root := skillsBuilder(t)
dir := filepath.Join(root, ".versions", "pdf-1")
p, err := b.BuildInstall(dir)
require.NoError(t, err)
require.Equal(t, dir, p.Cwd)
require.Equal(t, NetworkUnrestricted, p.Network)
require.Equal(t, []WritableRoot{{Path: dir}}, p.WritableRoots)
require.Equal(t, b.denyRead(), p.DenyRead)
require.Contains(t, p.DenyRead, filepath.Join(b.homeDir, ".ssh"))
require.Contains(t, p.DenyRead, b.appDataDir)
for _, root := range []string{"/tmp", "/private/tmp"} {
if filepath.IsAbs(root) {
require.NotContains(t, p.PrivateRoots, filepath.Clean(root), root)
}
}
}
func TestBuildInstallRejectsDirOutsideSkillsRoot(t *testing.T) {
b, root := skillsBuilder(t)
for _, dir := range []string{root, filepath.Join(b.homeDir, "My Project"), "/tmp/pdf-1", "relative"} {
_, err := b.BuildInstall(dir)
require.ErrorIs(t, err, ErrInstallDirOutsideSkillsRoot, dir)
}
}
func TestBuildInstallRequiresASkillsRoot(t *testing.T) {
b, _ := builderFixture(t)
_, err := b.BuildInstall(filepath.Join(b.homeDir, ".weknora", "skills", ".versions", "pdf-1"))
require.ErrorIs(t, err, ErrInstallDirOutsideSkillsRoot)
}
func TestJobsDirectoryCannotBecomeAWorkspace(t *testing.T) {
home := "/Users/local-test"
jobs := filepath.Join(home, ".weknora", "jobs")
b := NewPolicyBuilder(home, filepath.Join(home, "Library", "Application Support", "WeKnora Lite"))
for _, root := range []string{filepath.Dir(jobs), jobs, filepath.Join(jobs, "sj_0123")} {
_, err := b.Build(ModeAuto, Workspace{Root: root})
require.Error(t, err, root)
}
p, err := b.Build(ModeAuto, Workspace{Root: filepath.Join(home, "project")})
require.NoError(t, err)
require.Contains(t, p.DenyRead, jobs)
}
+131
View File
@@ -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())
}
+180
View File
@@ -0,0 +1,180 @@
package core
import (
"context"
"crypto/sha256"
"encoding/hex"
"errors"
"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.
//
// Three outcomes:
// - ("", false, nil) — unbound; Resolve allocates a session workspace
// - (dir, true, nil) — bound and still approved
// - ("", false, err) — bound but no longer approved, or lookup failed;
// Resolve must not allocate a replacement directory
type ProjectLookup interface {
ProjectDirForSession(ctx context.Context, sessionID string) (string, bool, error)
}
// ErrProjectDirRevoked is returned when a session still names a host project
// that is no longer on the approved list. Fail closed: do not silently
// switch the agent to an auto-allocated directory.
var ErrProjectDirRevoked = errors.New("localsandbox: session project directory is no longer approved")
// 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 {
dir, ok, err := r.projects.ProjectDirForSession(ctx, sessionID)
if err != nil {
logger.Warnf(ctx, "[LocalSandbox] resolve project dir session=%s: %v", sessionID, err)
return Workspace{}, err
}
if 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
}
@@ -0,0 +1,178 @@
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, error) {
if f.dir == "" {
return "", false, nil
}
return f.dir, true, nil
}
type revokedProjects struct{}
func (revokedProjects) ProjectDirForSession(context.Context, string) (string, bool, error) {
return "", false, ErrProjectDirRevoked
}
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 TestResolveFailsClosedWhenBoundProjectIsRevoked(t *testing.T) {
base := t.TempDir()
sessionRoot := filepath.Join(base, "Documents", "WeKnora")
r := NewWorkspaceResolver(DirLayout{SessionRoot: sessionRoot}, revokedProjects{})
_, err := r.Resolve(context.Background(), "sess-revoked")
require.ErrorIs(t, err, ErrProjectDirRevoked)
if _, statErr := os.Stat(sessionRoot); !os.IsNotExist(statErr) {
entries, readErr := os.ReadDir(sessionRoot)
require.NoError(t, readErr)
require.Empty(t, entries, "revoking a project must not allocate a replacement workspace")
}
}
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())
}