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

+322
View File
@@ -0,0 +1,322 @@
//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,
pid: pid,
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
pid int
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.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()
// reaped is set under this lock as soon as Wait returns. Cmd.ProcessState
// is written by Wait itself, so another goroutine must not read it.
if p.reaped {
p.mu.Unlock()
return nil
}
p.killed = true
pid := p.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)
}
@@ -0,0 +1,479 @@
//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))
}
// /tmp is open in the base profile for chat and install. /var/folders stays
// behind PrivateRoots so per-user temp tokens there remain unreadable.
// The workspace itself must still be writable.
func TestSeatbeltAllowsTmpAndDeniesVarFolders(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.Equal(t, 0, status.Code, out)
require.Contains(t, out, "TMPSECRET")
tmpOut := filepath.Join("/tmp", "weknora-seatbelt-out-"+t.Name())
t.Cleanup(func() { _ = os.Remove(tmpOut) })
status, out = runSandboxedArgv(t, backend, p, append(noProfile, `echo from-sandbox > `+tmpOut+` && cat `+tmpOut), env)
require.Equal(t, 0, status.Code, out)
require.Contains(t, out, "from-sandbox")
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())
}
+39
View File
@@ -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"))
+180
View File
@@ -0,0 +1,180 @@
// 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),
)
}
if len(p.WritableRoots) > 0 {
// Host temp opens with the first writable root, for chat and install
// alike. A policy with none (Ask mode before approval) must not write
// anywhere. /tmp is a symlink of /private/tmp and Seatbelt matches the
// resolved vnode, so both names are required. /var/folders stays closed.
writeAllows = append(writeAllows,
`(allow file-write* (subpath "/tmp") (subpath "/private/tmp"))`)
}
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)
}
}
@@ -0,0 +1,179 @@
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 TestCompileSeatbeltOpensTmpOnlyWithAWritableRoot(t *testing.T) {
const tmpRule = `(allow file-write* (subpath "/tmp") (subpath "/private/tmp"))`
prog, err := compileSeatbelt(seatbeltPolicy())
require.NoError(t, err)
require.Contains(t, prog.Profile, tmpRule)
readOnly := seatbeltPolicy()
readOnly.WritableRoots = nil
readOnly.ReadableRoots = append(readOnly.ReadableRoots, readOnly.Cwd)
prog, err = compileSeatbelt(readOnly)
require.NoError(t, err)
require.NotContains(t, prog.Profile, tmpRule)
}
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")
}