Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
96 commits
Select commit Hold shift + click to select a range
6322126
feat(sandbox): add Windows sandbox principals
Vasanthdev2004 Jul 26, 2026
f3eeb0b
feat(sandbox): use a sandbox principal for Windows command execution
Vasanthdev2004 Jul 26, 2026
41a1526
test(sandbox): name the per-shell env syntax in the provisioning skip
Vasanthdev2004 Jul 26, 2026
34a6e21
test(sandbox): cover the logon-rights and token-minting half
Vasanthdev2004 Jul 26, 2026
30944ff
feat(sandbox): provision a sandbox principal during elevated setup
Vasanthdev2004 Jul 26, 2026
6053126
fix(sandbox): keep the restricted token when the network is denied
Vasanthdev2004 Jul 26, 2026
2ab568d
feat(sandbox): encrypt the stored principal password to the invoking …
Vasanthdev2004 Jul 26, 2026
521e9f5
fix(sandbox): surface a squatted principal name instead of falling back
Vasanthdev2004 Jul 27, 2026
5c624e0
fix(sandbox): reset the password when the account already exists
Vasanthdev2004 Jul 27, 2026
c2ceb0d
fix(sandbox): revoke logon rights before deleting a principal
Vasanthdev2004 Jul 27, 2026
d40dce0
fix(sandbox): refuse a squatted account name and clean up partial pro…
Vasanthdev2004 Jul 27, 2026
a54a001
fix(sandbox): drop the stored secret whenever provisioning fails
Vasanthdev2004 Jul 27, 2026
a5c2ab6
test(sandbox): check the ACE type before decoding its trustee
Vasanthdev2004 Jul 28, 2026
d5d2b09
fix(sandbox): grant delete to the principal and keep rollback able to…
Vasanthdev2004 Jul 28, 2026
60257df
fix(sandbox): stop setup destroying a principal it did not create
Vasanthdev2004 Jul 29, 2026
194e687
fix(sandbox): keep an adopted principal's logon rights on rollback
Vasanthdev2004 Jul 29, 2026
7003367
fix(sandbox): grant the principal the runtime tree commands write to
Vasanthdev2004 Jul 30, 2026
1462592
fix(sandbox): refuse to adopt a principal in a privileged group
Vasanthdev2004 Jul 30, 2026
aa1a187
fix(sandbox): materialize .git/config as a file, not a directory
Vasanthdev2004 Jul 30, 2026
bdb5bc5
fix(sandbox): re-check principal privilege when minting a command token
Vasanthdev2004 Jul 30, 2026
87180ab
fix(sandbox): revoke stale principal ACEs before re-applying the plan
Vasanthdev2004 Jul 30, 2026
c12738a
fix(sandbox): revoke ACEs on teardown and key setup off the resolved …
Vasanthdev2004 Jul 30, 2026
6d82e7a
fix(sandbox): canonicalize the workspace root on both sides, not just…
Vasanthdev2004 Jul 30, 2026
97ff106
fix(sandbox): normalize the cache root too, not just the workspace root
Vasanthdev2004 Jul 30, 2026
d44ac17
fix(sandbox): resolve through path segments that do not exist yet
Vasanthdev2004 Jul 30, 2026
5a7f630
test(sandbox): assert the ancestor walk, not the old all-or-nothing c…
Vasanthdev2004 Jul 30, 2026
dc8b7bb
fix(sandbox): close the delete-through-parent, junction-ancestor and …
Vasanthdev2004 Jul 31, 2026
e42cace
fix(sandbox): stop teardown creating a directory while naming one
Vasanthdev2004 Jul 31, 2026
27849df
fix(sandbox): surface a failed stale-secret cleanup after rotation
Vasanthdev2004 Jul 31, 2026
f2a8e71
fix(sandbox): reject reparse ancestors before creating an ACL target
Vasanthdev2004 Aug 1, 2026
374f28d
fix(sandbox): keep the principal inside the Windows write jail
Vasanthdev2004 Aug 1, 2026
0aac1fa
fix(sandbox): carry the principal opt-in through the setup protocol
Vasanthdev2004 Aug 3, 2026
9dc1880
fix(sandbox): revoke principal ACEs on roots that left the policy
Vasanthdev2004 Aug 3, 2026
f3e6bc0
test(sandbox): compare ACL record paths the way the plans do
Vasanthdev2004 Aug 3, 2026
62976aa
fix(sandbox): stop a principal replacing .git to shed its carveouts
Vasanthdev2004 Aug 7, 2026
7ea9405
feat(sandbox): handle-relative directory create and delete on Windows
Vasanthdev2004 Aug 7, 2026
fd6e1d8
fix(sandbox): keep the git rename guard tests portable
Vasanthdev2004 Aug 8, 2026
0ac2e72
fix(sandbox): bind windows ACL materialization and rollback to handles
Vasanthdev2004 Aug 8, 2026
f4fd1c9
fix(sandbox): reject protected metadata names that escape the write root
Vasanthdev2004 Aug 8, 2026
c834f88
fix(sandbox): apply the .git rename guard on a workspace that had no …
Vasanthdev2004 Aug 8, 2026
9552175
fix(sandbox): stop granting a principal read at the volume root, and …
Vasanthdev2004 Aug 8, 2026
60da04e
docs(sandbox): attribute the Users-group premise the volume-root fix …
Vasanthdev2004 Aug 8, 2026
366b9c3
fix(sandbox): name the root that blocks unelevated ACL setup
Vasanthdev2004 Aug 8, 2026
9b3376d
feat(sandbox): add `zero sandbox exec` to run one command through the…
Vasanthdev2004 Aug 8, 2026
bbda356
fix(sandbox): fingerprint principal grants in the setup marker
Vasanthdev2004 Aug 8, 2026
e2b8b70
fix(sandbox): report an inactive principal in doctor, and finish the …
Vasanthdev2004 Aug 9, 2026
7b0ed7e
fix(sandbox): retire the principal on opt-out, and finish teardown pa…
Vasanthdev2004 Aug 9, 2026
54af05e
fix(sandbox): serialize elevated setup with a per-workspace lock
Vasanthdev2004 Aug 9, 2026
ad2d03b
fix(sandbox): address jatmn's review on the principal backend and san…
Vasanthdev2004 Aug 10, 2026
1ef6604
fix(sandbox): keep elevated Windows setup tied to the caller's identity
Vasanthdev2004 Aug 10, 2026
63bda96
fix(sandbox): fail opt-out only when the principal actually survived
Vasanthdev2004 Aug 10, 2026
2170635
fix(sandbox): refuse to adopt a ZeroSandboxUsers group Zero did not c…
Vasanthdev2004 Aug 10, 2026
97251dd
fix(sandbox): stop the principal's own SID from defeating its write jail
Vasanthdev2004 Aug 11, 2026
af97b88
fix(sandbox): derive the fallback runtime root instead of minting one…
Vasanthdev2004 Aug 11, 2026
0496196
chore: drop a stray probe artifact from the branch
Vasanthdev2004 Aug 11, 2026
3a1d7ff
fix(sandbox): cover both runtime roots in the setup contract
Vasanthdev2004 Aug 11, 2026
0f6469f
test(sandbox): make the jail aliasing assertion able to fail
Vasanthdev2004 Aug 11, 2026
207e218
fix(sandbox): create the runtime roots setup grants
Vasanthdev2004 Aug 11, 2026
bd64ab7
fix(sandbox): say what changed when the setup marker is rejected
Vasanthdev2004 Aug 11, 2026
1ef250f
fix(sandbox): derive the runtime roots where TEMP is the operator's
Vasanthdev2004 Aug 11, 2026
80ac2cd
fix(sandbox): give the principal's read roots a restricting SID
Vasanthdev2004 Aug 11, 2026
ed84ed3
test(sandbox): fix the workspace-root literal in the setup-args tests
Vasanthdev2004 Aug 11, 2026
7a062a6
fix(sandbox): protect the gitdir pointer in a linked worktree
Vasanthdev2004 Aug 11, 2026
99f340c
fix(sandbox): write the principal secret through one pinned handle
Vasanthdev2004 Aug 12, 2026
a70f36f
fix(sandbox): report the privileges a principal launch actually needs
Vasanthdev2004 Aug 12, 2026
ffe71ed
fix(sandbox): stop the principal's environment naming the caller
Vasanthdev2004 Aug 12, 2026
83750ae
fix(sandbox): drop the unfollowable sandbox override from ACL failures
Vasanthdev2004 Aug 12, 2026
ba5219c
fix(sandbox): stop the redirect check resolving what it checks for
Vasanthdev2004 Aug 12, 2026
3b34c83
test(sandbox): compare normalized paths, not the raw input
Vasanthdev2004 Aug 12, 2026
5ac436c
feat(sandbox): give each workspace an offline and an online principal…
Vasanthdev2004 Aug 21, 2026
79716d9
fix(sandbox): bind the ACL restore to the object it snapshotted
Vasanthdev2004 Aug 21, 2026
909c741
fix(sandbox): name the two role inventories, and fingerprint the whol…
Vasanthdev2004 Aug 21, 2026
ab3265c
fix(sandbox): refuse to provision a principal this caller could never…
Vasanthdev2004 Aug 24, 2026
f369e33
test(sandbox): assert nothing was created, not that a count held still
Vasanthdev2004 Aug 27, 2026
fe0c697
fix(sandbox): keep principal provisioning closed until a launch path …
Vasanthdev2004 Aug 31, 2026
b40d72d
test(sandbox): keep the runtime-root candidates inside test-owned sto…
Vasanthdev2004 Aug 31, 2026
f882848
test(sandbox): stop the launch preflight test asserting a machine's t…
Vasanthdev2004 Aug 31, 2026
7f95315
fix(sandbox): root the fallback runtime tree beneath a validated priv…
Vasanthdev2004 Sep 2, 2026
41d2ab9
fix(sandbox): resolve the temp dir physically before proving the fall…
Vasanthdev2004 Sep 2, 2026
0d331a4
fix(sandbox,cli): plan the grant and its guard together, and state th…
Vasanthdev2004 Sep 3, 2026
0daeca9
fix(sandbox): validate runtime candidates before the elevated create,…
Vasanthdev2004 Sep 3, 2026
0585da8
fix(sandbox): check the runtime root still carries its grant, not jus…
Vasanthdev2004 Sep 3, 2026
c934449
fix(sandbox): recheck the runtime object on the unelevated tier too
Vasanthdev2004 Sep 4, 2026
b958def
fix(sandbox): make the capability git guard reach a workspace that ge…
Vasanthdev2004 Sep 4, 2026
e096206
fix(sandbox): refuse a denyRead profile instead of ACLing the volume …
Vasanthdev2004 Sep 4, 2026
654bf83
fix(sandbox): key the read-grant refusal on the grant, not on the vol…
Vasanthdev2004 Sep 4, 2026
f8c752d
fix(sandbox): do not synthesize a .git inside an ancestor repository
Vasanthdev2004 Sep 4, 2026
4981ccf
fix(cli): keep a specified-empty sandbox environment from inheriting
Vasanthdev2004 Sep 4, 2026
8f47de5
test(sandbox): stop probing for privilege by mutating System32
Vasanthdev2004 Sep 4, 2026
0154b91
fix(sandbox): keep a linked worktree's .git typed as a file through p…
Vasanthdev2004 Sep 4, 2026
214127b
fix(sandbox): stop following sandbox-controlled runtime descendants
Vasanthdev2004 Sep 4, 2026
be9fcb4
test(sandbox): drive the runtime-tree descent through its entry point
Vasanthdev2004 Sep 4, 2026
12d082e
fix(sandbox): restore a raced leaf whose parent this run created
Vasanthdev2004 Sep 4, 2026
802f726
test(sandbox): reproduce the raced leaf at the instant it can actuall…
Vasanthdev2004 Sep 4, 2026
659140f
fix(cli): terminate the sandboxed command when the wrapper is cancelled
Vasanthdev2004 Sep 4, 2026
7e9a524
fix(sandbox): decide the runtime base on a canonical spelling
Vasanthdev2004 Sep 4, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 11 additions & 1 deletion internal/cli/sandbox.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ const permissionProfileScopeNote = "permissionProfile is derived from this proce

func runSandbox(args []string, stdout io.Writer, stderr io.Writer, deps appDeps) int {
if len(args) == 0 {
return writeExecUsageError(stderr, "sandbox subcommand required. Use `zero sandbox policy` or `zero sandbox grants list`.")
return writeExecUsageError(stderr, "sandbox subcommand required. Use `zero sandbox policy`, `zero sandbox exec`, or `zero sandbox grants list`.")
}
switch args[0] {
case "-h", "--help", "help":
Expand All @@ -36,6 +36,8 @@ func runSandbox(args []string, stdout io.Writer, stderr io.Writer, deps appDeps)
return runSandboxSetup(args[1:], stdout, stderr, deps)
case "check":
return runSandboxCheck(args[1:], stdout, stderr, deps)
case "exec":
return runSandboxExec(args[1:], stdout, stderr, deps)
case "grants":
return runSandboxGrants(args[1:], stdout, stderr, deps)
default:
Expand Down Expand Up @@ -174,10 +176,17 @@ func runSandboxSetup(args []string, stdout io.Writer, stderr io.Writer, deps app
if !setupHelper.Available() {
return writeAppError(stderr, "Windows sandbox setup helper is not available", exitProvider)
}
// Resolved here, in the shell the user typed `zero sandbox setup` into, and
// carried in the args. The helper may be launched elevated, and an elevated
// process does not inherit this shell's environment. Stated explicitly rather
// than left nil (which resolves the same way) because this is the call site
// the opt-in is about.
principalOptIn := zeroSandbox.WindowsSandboxPrincipalOptIn(nil)
setupArgs, err := zeroSandbox.BuildWindowsSandboxSetupArgs(zeroSandbox.WindowsSandboxSetupArgsOptions{
CommandCWD: workspaceRoot,
WorkspaceRoots: []string{workspaceRoot},
PermissionProfile: profile,
PrincipalOptIn: &principalOptIn,
})
if err != nil {
return writeAppError(stderr, err.Error(), exitCrash)
Expand Down Expand Up @@ -646,6 +655,7 @@ Commands:
policy Inspect active sandbox policy and platform backend
setup Run native platform sandbox setup
check Evaluate the sandbox decision for a hypothetical tool action
exec Run one command through the real sandbox
grants Manage persistent sandbox grants

`)
Expand Down
253 changes: 253 additions & 0 deletions internal/cli/sandbox_exec.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,253 @@
package cli

import (
"context"
"errors"
"fmt"
"io"
"os"
"os/exec"
"strings"
"time"

"github.com/Gitlawb/zero/internal/config"
"github.com/Gitlawb/zero/internal/execution"
zeroSandbox "github.com/Gitlawb/zero/internal/sandbox"
)

// runSandboxExec runs ONE command through the real sandbox and exits with its
// status.
//
// This exists because until now the sandbox could only be exercised through a
// full agent turn with a model in the loop. `zero sandbox policy` reports what
// the posture would be and `zero sandbox check` evaluates a hypothetical
// decision, but nothing actually ran a command and let you look at what
// happened on disk afterwards. The practical result is that enforcement is
// covered almost entirely by tests asserting the shape of an ACL plan, and
// almost not at all by tests asserting a write was refused.
//
// A plan can be perfectly correct and never reach the filesystem. That is not
// hypothetical here: the .git rename guard was emitted correctly by the planner
// and silently skipped by the applier, and four tests covering the plan all
// passed while the ACE was absent from disk. Something that runs the real
// binary and then stats the file is the only thing that catches that class.
//
// Deliberately NOT a debug curiosity: it takes the same path a shell tool
// takes, through SandboxManager.BuildCommandPlan, so what it proves is what
// users get. It prints the resolved backend and enforcement level to stderr
// before running, so a harness can assert the sandbox was actually engaged
// rather than quietly downgraded.
func runSandboxExec(args []string, stdout io.Writer, stderr io.Writer, deps appDeps) int {
command, err := parseSandboxExecArgs(args)
if err != nil {
if errors.Is(err, errSandboxExecHelp) {
if writeErr := writeSandboxExecHelp(stdout); writeErr != nil {
return exitCrash
}
return exitSuccess
}
return writeExecUsageError(stderr, err.Error())
}

workspaceRoot, err := resolveWorkspaceRoot("", deps)
if err != nil {
return writeExecUsageError(stderr, err.Error())
}
resolved, err := deps.resolveConfig(workspaceRoot, config.Overrides{})
if err != nil {
return writeAppError(stderr, err.Error(), exitProvider)
}
policy := applyConfiguredSandboxPolicy(zeroSandbox.DefaultPolicy(), resolved.Sandbox)

scope, err := zeroSandbox.NewScope(workspaceRoot, resolved.Sandbox.AdditionalWriteRoots)
if err != nil {
return writeAppError(stderr, fmt.Sprintf("resolve sandbox write roots: %v", err), exitCrash)
}

// Through the ENGINE, not a SandboxManager built here.
//
// The engine is what a real tool call goes through, and it does more than
// hand the manager a request: it resolves the permission profile, calls
// prepareSandboxRuntime, and folds the runtime state into that profile
// before planning. Building a manager directly skipped all of it, so the
// command ran without the runtime write root, and cache or temp writes could
// pass or fail differently from the sandboxed command this exists to imitate.
// A harness that exercises the wrong path is worse than no harness, because
// its result still reads as evidence.
engine := zeroSandbox.NewEngine(zeroSandbox.EngineOptions{
WorkspaceRoot: workspaceRoot,
Policy: policy,
Scope: scope,
Backend: deps.selectSandboxBackend(zeroSandbox.BackendOptions{}),
// The same scrub list a real tool call gets. Without it the engine keeps an
// empty set, and only the hardcoded names plus the provider catalog's own
// AuthEnvVars are removed from the child's environment: a key named by
// `apiKeyEnv` in the user's config would be scrubbed for every sandboxed
// tool call and handed to this one. Reproducing the production environment
// is the entire point of the command, and a credential is the last part of
// it that may differ.
SensitiveEnvKeys: providerSensitiveEnvKeys(resolved),
})
plan, err := engine.BuildCommandPlan(zeroSandbox.CommandSpec{
Name: command[0],
Args: command[1:],
Dir: workspaceRoot,
Env: os.Environ(),
})
if err != nil {
return writeAppError(stderr, fmt.Sprintf("build sandbox command plan: %v", err), exitCrash)
}
// The plan owns resources beyond its construction: on Linux it allocates a
// policy-report file and registers the removal here, so without this every
// invocation leaves a /tmp/zero-sandbox-report-* behind.
defer plan.Cleanup()

// Printed before the command runs and on stderr, so it survives a command
// that writes to stdout and stays greppable by a test harness. A downgrade
// is reported loudly for the same reason: a smoke test that passes because
// the sandbox quietly stood down is worse than no smoke test.
fmt.Fprintf(stderr, "sandbox: backend=%s enforcement=%s wrapped=%t workspace=%s\n",
plan.Backend.Name, plan.EnforcementLevel, plan.Wrapped, plan.WorkspaceRoot)
if strings.TrimSpace(plan.DowngradeReason) != "" {
fmt.Fprintf(stderr, "sandbox: DOWNGRADED: %s\n", plan.DowngradeReason)
}

// The CLI's shared shutdown context, so Ctrl+C and a directed SIGTERM both
// arrive here rather than only at whatever the terminal happens to signal.
runCtx, stopSignals := signalContext()
defer stopSignals()
return runSandboxPlannedCommand(runCtx, plan, stdout, stderr)
}

// sandboxExecShutdownGrace bounds how long a cancelled child may take to exit
// before it is killed outright, so cleanup still runs.
const sandboxExecShutdownGrace = 5 * time.Second

func runSandboxPlannedCommand(ctx context.Context, plan zeroSandbox.CommandPlan, stdout io.Writer, stderr io.Writer) int {
// CANCELLING THE WRAPPER HAS TO REACH THE COMMAND.
//
// This started the backend wrapper with a bare exec.Command().Run(): no
// context, no forwarding, no shutdown path. A terminal masks it, because
// terminals signal the whole foreground process group, but a supervisor or
// task runner that sends SIGTERM to the zero sandbox exec PID killed only
// Zero. The wrapper and everything under it kept running, doing filesystem
// and network work after the caller considered the task cancelled, and the
// deferred plan cleanup never ran because the process was gone.
//
// DELIBERATELY NOT execution.ConfigureProcessGroup. Putting the child in its
// own process group closes this hole and opens a worse one: it severs every
// kernel-delivered group signal, so a supervisor escalating to a group kill,
// and a terminal delivering Ctrl+C to its foreground group, would stop
// reaching the child. That trades a path that works today for one that does
// not. Keeping the child in Zero's group leaves group delivery unchanged,
// while the directed-signal case, which reached nothing at all before, now
// reaches the child.
process := exec.CommandContext(ctx, plan.Name, plan.Args...)
// Kill the tree rather than the root: on Windows that is taskkill /T, and on
// Unix the child plus its group when it leads one.
process.Cancel = func() error { return execution.KillProcessTree(process.Process.Pid) }
// Bounded, so a child ignoring the first signal cannot hold the wrapper open
// forever and skip cleanup anyway.
process.WaitDelay = sandboxExecShutdownGrace
process.Dir = plan.Dir
if process.Dir == "" {
process.Dir = plan.WorkspaceRoot
}
// SPECIFIED-EMPTY IS NOT UNSPECIFIED.
//
// exec.Cmd treats a nil Env as "inherit this process's entire environment",
// which is a different statement from "run with no variables". The plan owns
// its environment: directCommandEnv and scrubSensitiveEnv return a slice they
// built, and that slice is non-nil with length zero when every entry was
// sensitive. Testing length collapsed those two states and turned the strictest
// possible answer into the loosest one.
//
// Not reachable through `zero sandbox exec` today, because the child
// environment is os.Environ() and an environment holding only sensitive keys
// has no %AppData%, so config resolution fails before the planner runs. Fixed
// anyway: the guard is one assignment, and the next caller that hands the plan
// a deliberately narrow environment would inherit everything instead, silently.
if plan.Env != nil {
process.Env = plan.Env
}
process.Stdin = os.Stdin
process.Stdout = stdout
process.Stderr = stderr

if err := process.Run(); err != nil {
var exitErr *exec.ExitError
if errors.As(err, &exitErr) {
// The command's own status, not ours. A harness asserting "the write
// was refused" needs the refusal's exit code, not a wrapper's.
// A SIGNALED CHILD HAS NO EXIT CODE TO REPORT. ExitCode() answers -1
// there, and os.Exit truncates that to 255, so a child that took SIGTERM
// became indistinguishable from one that chose to exit 255. Fold the
// signal into the conventional 128+n a shell would report, which needs
// the ProcessState rather than the integer.
if status, signaled := signaledExitStatus(exitErr.ProcessState); signaled {
return status
}
return exitErr.ExitCode()
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
fmt.Fprintf(stderr, "sandbox exec: %v\n", err)
return exitCrash
}
return exitSuccess
}

var errSandboxExecHelp = errors.New("help requested")

// parseSandboxExecArgs takes everything after `--` as the command, so the
// command's own flags are never mistaken for ours.
func parseSandboxExecArgs(args []string) ([]string, error) {
if len(args) == 0 {
return nil, errors.New("usage: zero sandbox exec -- <command> [args...]")
}
// Only the FIRST token is ours to interpret. Everything from the second
// onwards belongs to the child, help flags included.
//
// Written as a straight-line decision on args[0] rather than a loop, because
// a loop here is a lie. An earlier version scanned for `--` "up front" and
// said so in its comment, but every branch of its body returned, so it only
// ever examined index 0 and the promised scan did not exist. The rule below
// is what that code actually implemented, and it is the rule we want: it is
// the wrapper's own prefix that can ask for the wrapper's help, and the
// prefix is at most one token long.
switch args[0] {
case "--":
// Everything after the separator is the command, verbatim, including
// `--help`. That is the documented contract: `zero sandbox exec -- cmd
// --help` must run cmd's help, not ours.
command := args[1:]
if len(command) == 0 {
return nil, errors.New("usage: zero sandbox exec -- <command> [args...]")
}
return command, nil
case "-h", "--help", "help":
return nil, errSandboxExecHelp
}
// The separator-less form, tolerated for interactive use: the first token is
// the command, so nothing after it is ours to read. Without this,
// `zero sandbox exec mycmd --help` printed OUR help and never ran mycmd,
// which is the same contract break as reading past `--`. The help text still
// shows the separator, because anything with a leading dash needs it.
return args, nil
}

func writeSandboxExecHelp(w io.Writer) error {
_, err := fmt.Fprint(w, `Usage:
zero sandbox exec -- <command> [args...]

Runs one command through the real sandbox and exits with its status.

Everything after the -- separator is the command, so its own flags are not
parsed as Zero's. The resolved backend and enforcement level are written to
stderr before the command runs, and a downgrade is reported there explicitly.

Examples:
zero sandbox exec -- cmd /c echo hello
zero sandbox exec -- powershell -Command "Set-Content out.txt x"

`)
return err
}
78 changes: 78 additions & 0 deletions internal/cli/sandbox_exec_cancel_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
package cli

import (
"context"
"io"
"os"
"runtime"
"testing"
"time"

zeroSandbox "github.com/Gitlawb/zero/internal/sandbox"
)

// longLivedPlan returns a plan whose child outlives the test unless something
// terminates it.
func longLivedPlan(t *testing.T) zeroSandbox.CommandPlan {
t.Helper()
plan := zeroSandbox.CommandPlan{Dir: t.TempDir()}
if runtime.GOOS == "windows" {
plan.Name = "cmd.exe"
plan.Args = []string{"/c", "ping -n 120 127.0.0.1 >NUL"}
return plan
}
plan.Name = "/bin/sh"
plan.Args = []string{"-c", "sleep 120"}
return plan
}

// CANCELLING THE WRAPPER HAS TO REACH THE COMMAND.
//
// The sandboxed command was started with a bare exec.Command().Run(): no
// context, no forwarding, no shutdown path. A terminal masks that, because it
// signals the whole foreground process group, but a supervisor or task runner
// that sends SIGTERM to the wrapper's PID killed only Zero. The command kept
// running, doing filesystem and network work after the caller considered the
// task cancelled, and the deferred plan cleanup never ran.
//
// Driven with a real long-lived child and a real cancellation, asserting that
// the call actually returns rather than that a field is set.
func TestCancellingTheWrapperTerminatesTheSandboxedCommand(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())

done := make(chan int, 1)
go func() {
done <- runSandboxPlannedCommand(ctx, longLivedPlan(t), io.Discard, io.Discard)
}()

// Let the child actually start, or cancelling proves nothing.
time.Sleep(300 * time.Millisecond)
select {
case <-done:
t.Fatal("SETUP INVALID: the child exited on its own, so cancellation was not exercised")
default:
}

cancel()
select {
case <-done:
case <-time.After(sandboxExecShutdownGrace + 10*time.Second):
t.Fatal("cancelling the wrapper did not terminate the sandboxed command; it would keep running after the caller gave up")
}
}

// And an uncancelled command still runs to completion and reports its own
// status, or the fix above would be "kill everything immediately".
func TestAnUncancelledSandboxedCommandStillReportsItsStatus(t *testing.T) {
plan := zeroSandbox.CommandPlan{Dir: t.TempDir()}
if runtime.GOOS == "windows" {
plan.Name = "cmd.exe"
plan.Args = []string{"/c", "exit 3"}
} else {
plan.Name = "/bin/sh"
plan.Args = []string{"-c", "exit 3"}
}
if code := runSandboxPlannedCommand(context.Background(), plan, io.Discard, os.Stderr); code != 3 {
t.Fatalf("exit code = %d, want the child's own 3", code)
}
}
Loading
Loading