Skip to content

Latest commit

 

History

History
234 lines (176 loc) · 16.2 KB

6.3-command-execution.md

File metadata and controls

234 lines (176 loc) · 16.2 KB

Command Execution — Two Tiers

Status: design (draft, 2026-08-19). Specifies the form a command takes when devlore runs one: an argv vector always, with shell and PowerShell workflows delivered as script files that the same argv engine executes. No implementation. Companion: 6.3-command-execution.status.md.

Relationship to the neighbors. 6-execution-topology.md owns the elevation policy, 6.1-authorization.md the provider that fulfills it, and 6.2-process-pool.md the command runners — how they stand for an account, are reached and are reclaimed. This document owns what is handed to a host. 6.2 answers who runs it; 6.3 answers what shape the thing being run has.

Thesis

A command is an argv vector. A script is a file that an argv vector runs. There is no third thing, and in particular there is no command string assembled by concatenation and handed to an interpreter's -c.

That single rule removes an entire defect class rather than defending against it. Today devlore builds command strings by concatenation in three places, and every one of them is either exploitable, broken, or both.

1. What the current shape costs

pkg/platform concatenates and runs under sudo. Seventy call sites across four files build strings like "apt-get install -y "+strings.Join(names, " ") and hand them to sudo -n bash -c. ParsePURL (pkg/platform/purl.go:86) applies no charset validation to a package name, and passes the version through url.PathUnescape, so %3B arrives as ;. A name reaching that concatenation with shell metacharacters executes as root.

shell.exec and powershell.exec take an opaque string. Both are Exec(command string), running sh -c and pwsh -Command respectively. Anything an author interpolates — a path, a package name, a URL — is subject to that interpreter's escaping rules.

The escaping rules differ per interpreter, so a single quoting helper cannot serve both:

sh:          'it'\''s'      close, escape, reopen
PowerShell:  'it''s'        doubled quote; the escape character is a backtick

And the failure is not theoretical. Two test fixtures interpolated an OS-native path into an sh -c string. On Windows sh consumed the backslashes as escapes — C:\Users\RUNNER~1\… became C:UsersRUNNER~1… — and the redirect wrote to a path nobody intended. It was found only because the Windows leg runs.

Go offers no help here deliberately: the standard library ships no shell quoter, because exec.Command(name, args...) never invokes a shell. Ruby needs Shellwords.escape because system("…") is string-shaped. Go's answer is to not be string-shaped, and this design adopts it.

2. Tier 1 — the argv engine

Every execution path terminates here:

exec.CommandContext(ctx, name, args...)

No interpreter, no metacharacters, no quoting, no length limits on a single -c argument. Arguments containing spaces, quotes, semicolons or newlines are data, because the kernel receives them as a vector rather than a sentence to be parsed.

Nearly everything is expressible here. All seventy pkg/platform commands are, once two habits are unlearned:

Pattern Looks like it needs a shell Argv form
dpkg-query -W -f='${Version}' <name> ${…} ["dpkg-query","-W","-f=${Version}",name] — the quotes existed only to hide it from sh; dpkg parses ${Version} itself
rpm -q --queryformat '%{VERSION}' <name> %{…} ["rpm","-q","--queryformat","%{VERSION}",name]
launchctl list | grep -q <name> a pipe run launchctl list, then strings.Contains on the captured output
port installed <name> | grep -q <name> a pipe same

The last two illustrate the general case: a pipe whose right-hand side is a text utility is usually a Go expression. | grep is strings.Contains, | wc -l is a line count, | sort is sort.Strings. Reaching for a shell to run grep is reaching for a process to avoid a function call.

3. Tier 2 — the script fallback

A pipe whose right-hand side is a real program, a loop, a conditional, a heredoc, or simply a legible multi-line workflow is not argv-shaped, and pretending otherwise produces worse designs than admitting it.

So a script arrives as a string, is written to a file, and is executed by tier 1:

exec.CommandContext(ctx, "sh", scriptPath, arg1, arg2)

The interpreter is named explicitly and the script is a file argument, not a -c payload. Everything shell syntax offers is available, because it is script content rather than argv.

3.1 The body is static; values arrive as arguments

This is the half that makes tier 2 safe rather than merely tidier. A value interpolated into script text is still shell source, and still needs quoting — tier 2 would have relocated the bug rather than removed it.

# body: static, written once, never assembled
set -eu
mkdir -p "$(dirname "$2")"
printf '%s' "$1" > "$2"
exec.CommandContext(ctx, "sh", scriptPath, content, destination)   // $1, $2

The script text never varies with input, so there is nothing to escape at either tier. It also disposes of the Windows case for free: a native path passed as $2 never passes through sh's escape processing at all.

Interpolating into the body is the one thing this design forbids. Where a caller genuinely must — a generated script rather than a parameterized one — that is a distinct and reviewable act, not the default path.

3.2 Where the file lives

The temporary file is created through the scratch root, not os.CreateTemp directly.

fsroot.OpenScratch already confines its tree, already removes it on Close, and already routes writes through the code that applies a restrictive mode. That last property matters: a script body can carry a secret, and os.CreateTemp yields 0600 on Unix but a 0666-reported file with an inherited DACL on Windows. Creating it in a confined scratch tree also closes the window in which another process could swap the path between write and execute.

The executable bit is never set. The interpreter is invoked explicitly — sh script, pwsh -File script.ps1 — which avoids the exec-permission question entirely and keeps interpreter selection an explicit decision rather than a shebang's.

3.3 PowerShell has its own tier 2

pwsh -File requires a .ps1 extension, and parameters arrive through param() / $args rather than $1. The dialect difference is real and permanent — which is a third argument for the static-body rule, since it is the only approach that needs no quoter for either dialect.

3.4 The record is the script, not the path

Result.Command must carry the script source for tier 2, and the argv vector for tier 1. Never the temp path, and never a joined string.

A trace saying ran /scratch/abc123/script is unauditable the moment scratch is reclaimed. A joined argv is worse than useless when debugging, because it is not what the kernel received and it re-introduces the ambiguity the vector existed to remove.

Ruled 2026-10-23 and 2026-10-24: the command provider

On 2026-10-23 and 2026-10-24 the owner ruled on what the command provider returns, what it offers, and where the account belongs. This section states those rulings; §§ 4 and 6 are read against them.

The result

Everything a program writes to standard output is its result, accumulated and returned. Everything it writes to standard error is narration, streamed as it is written into the caller's narration sink, and never part of the result. A non-zero exit is an error. A command has no compensating action, so the command provider's actions are fallible, not compensable, and return (string, error): Go's own exec.Cmd.Output shape. The string is the whole of stdout. The error, on a non-zero exit, is an ExitError carrying the argv, the exit code and any signal, and no stderr, which the user has already seen as narration. There is no parameter for accepted exit codes until a use appears, such as grep and diff exiting 1 as an answer; when one does, it is a parameter, not a richer return type (#1153, which supersedes #824).

The interface

Every command devlore runs is, in the end, an exec.Cmd from Go's os/exec. The interface offers what Go supports:

type Provider interface {
    Run(argv []string, opts Options) (string, error)                            // to completion; stdout the result
    Script(dialect, body string, args []string, opts Options) (string, error)  // tier 2, § 3
    Exec(argv []string, opts Options) error                                     // replace this process; returns only on failure
    Which(name string) (string, error)                                          // where a program resolves
    Options(kwargs map[string]any) (Options, error)                             // built from Starlark, both surfaces
}

type Options struct {
    Env     map[string]string // joins the child's environment
    Dir     string            // working directory
    Stdin   *op.Stdin         // bytes, or auto-confirm; nil closes stdin
    Timeout Duration          // the deadline, "10m"
    Grace   Duration          // SIGTERM to SIGKILL
    Limits  *Limits           // memory, CPU, process count
}
  • Run and Script are synchronous, and the program is governed while it runs: exec.CommandContext with Cmd.Cancel sending SIGTERM and Cmd.WaitDelay as the grace before SIGKILL and the pipes' close; Setpgid and a signal to the group on Unix, a Job Object killed on close on Windows, so a cancel ends the whole process tree; resource limits through SysProcAttr.CgroupFD on Linux and the Job Object on Windows, and none on macOS, said so; Pdeathsig on Linux; pidfd signalling on Linux, Go's own since 1.23 (#1165).
  • Exec replaces the current process with the program, keeping its pid, descriptors and terminal, after a graceful shutdown that flushes narration, writes the trace and releases locks, since nothing runs after it. It is the direct path only, never through a broker, which cannot replace its caller; on Windows syscall.Exec returns EWINDOWS. Start-Claude, ported to star, ends in an Exec into tmux attach-session (#802).
  • Which reports where a program resolves, so a script can probe before it runs (#1166).
  • Options is the constructor Starlark calls, command.options(...) and plan.command.options(...); it validates keys, durations and limits on the author's line, and a dict hydrates into the same type wherever an Options is expected (#1164). In the planned surface the value is a slot in the graph document: durations and sizes are text, a field may be a promise, and the graph's checksum and signature cover it.
  • The account is not an option. It belongs to the logon the command runs inside, and every command in a logon runs as the logon's account; a call that names an account runs as a logon of that one command (2.3 § plan.logon). The broker elevates to it (6.2).
  • Every child's environment carries the OpenTelemetry variables: the Collector's endpoint, the service name and resource attributes, and TRACEPARENT, the exec's span, so a program instrumented with OpenTelemetry joins the event bus with no setup of its own; an option turns them off (#1171). Shell scripts join through otel-cli, installed with devlore (#1172).
  • Asynchronous execution is ruled out for now. The graph executor provides concurrency with gather, and an action must finish before its receipt is pushed. A Start returning a handle is added only when a script needs a background child, and the handle dies with the run.

Fork and exec, for a reader who knows Windows

On Unix a program starts another in two calls. fork() copies the running process, memory, open files and directory, and returns twice, once in each copy. exec() replaces the program inside a process, keeping its pid, its descriptors and its terminal; a successful exec never returns. The child configures itself between the two, redirecting descriptors, joining a process group, dropping privileges, and then becomes the new program. Windows does both at once with CreateProcess, passing that configuration as parameters, and has neither call alone. Go offers the combination, syscall.ForkExec, behind exec.Cmd.Start, and exec alone, syscall.Exec; it does not offer fork alone, because a Go program is always multithreaded and fork() copies only the calling thread, leaving the child with no working runtime. So the interface has Run (fork, exec and wait), and Exec (become the program), and no fork.

4. The Starlark surface

Two shapes, matching the two tiers:

plan.command.run(argv=["systemctl", "restart", name])

plan.command.script(
    body = """
        set -eu
        journalctl -u "$1" --since "$2" | tail -20
    """,
    args = [name, since],
)

Whether today's shell.exec(command=…) survives as a third form was open (§6); the provider is command (§6, 6), and the string form has no place in the interface ruled 2026-10-24. It is the only shape that requires escaping, and keeping it keeps the defect class alive; retiring it is a breaking change to an authoring surface.

5. What this settles

  • #561 — pkg/platform's rewrite is tier 1, and can proceed as the first delivery without waiting for tiers to be built.
  • Quoting helpers — not needed at either tier, in either dialect, so the question of where a Quote function lives dissolves rather than being answered.
  • Pipes — expressible, in tier 2, where they belong.
  • The Windows escaping failure — impossible once values arrive as arguments.

6. Open questions

  1. Does command= survive? — answered 2026-10-24: no. The interface takes an argv or a script; there is no legacy to keep.
  2. Environment and working directory — answered 2026-10-24. Options carries both. Before that, neither shell.Exec nor powershell.Exec accepts either today, and cmd.Dir is never set, so commands inherit the devlore process's directory. Tier 2 makes a working directory more obviously necessary, since a script is more likely to use relative paths.
  3. Stdin — closed 2026-10-21 (6.2 § 4.1, 2.7 § The wire, in detail): stdin is an attribute of the request, a byte string or auto_confirm, which is what pkg/platform's endless y\n stream becomes. A tier 2 script that wants live stdin has no REST channel, since SSE is half-duplex; live stdin exists only on a full-duplex surface, if at all, and an interactive command is otherwise refused with a named failure.
  4. Elevation. Since 2026-10-24 the account is the logon's and the broker elevates (6.2). A tier 2 script under sudo must be readable by the elevated identity. Root bypasses Unix permissions, and an elevated Windows process is in Administrators, which applyMode's DACL grants — so both work, but the interaction should be stated rather than discovered.
  5. Interpreter availability. sh on Windows means Git-for-Windows; pwsh is not present by default on Linux or macOS. Tier 2 fails differently depending on which is missing, and 6.2's host identity is where that belongs. On Windows the runner runs tier 2 as pwsh -File, with Windows PowerShell 5.1 when pwsh is absent (6.2 § 4.3).
  6. The provider's name — ruled 2026-10-22: command. "Command is a better name for the shell provider." Feature #799 calls it "one command-execution surface for every platform"; tier 1 runs no shell, and PowerShell is a dialect of tier 2, which made shell a misnomer and a second powershell provider a dialect beside it. plan.command.run(argv=[...]) and plan.command.script(body=..., args=[...]), the dialect a parameter. No alias: there is no legacy. The change is lane 8 of #1127, #1136.