Skip to content

Open source CapCut alternative.

TypeScript

fix(app): run workspace-confined interpreters unprompted under the jail

David Le56347c17209b
diff --git a/apps/Donkey/Sources/DonkeyRuntime/DonkeyCommandBackends.swift b/apps/Donkey/Sources/DonkeyRuntime/DonkeyCommandBackends.swift
index 13ad522d..d5bd2cce 100644
--- a/apps/Donkey/Sources/DonkeyRuntime/DonkeyCommandBackends.swift
+++ b/apps/Donkey/Sources/DonkeyRuntime/DonkeyCommandBackends.swift
@@ -313,11 +313,12 @@ public enum DonkeyCommandBackends {
}
/// The seatbelt policy confining a shell spawn. Reads are open (the consent classifier already treats
- /// reads as free); writes are confined by the consent outcome. An UNPROMPTED command (a read, or a
- /// bounded mutator whose operands all sit in an owned folder) is held to the owned folders. A command
- /// the user APPROVED at a prompt also gets their home directory writable, so the approved write lands —
- /// the kernel still blocks `/System`, `/usr`, and other users. `nil` when no folder is owned yet, so the
- /// spawn runs unconfined exactly as before the jail existed; the consent prompt is the gate there.
+ /// reads as free) and the network is open (API calls and downloads are common); writes are confined by
+ /// the consent outcome. An UNPROMPTED command (a read, a bounded mutator whose operands all sit in an
+ /// owned folder, or a jailed interpreter) is held to the owned folders. A command the user APPROVED at a
+ /// prompt also gets their home directory writable, so the approved write lands — the kernel still blocks
+ /// `/System`, `/usr`, and other users. `nil` when no folder is owned yet, so the spawn runs unconfined
+ /// exactly as before the jail existed; the consent prompt is the gate there.
private static func shellPolicy(owned: [String], consented: Bool) -> SandboxPolicy? {
guard !owned.isEmpty else { return nil }
let writable = consented ? owned + [FileManager.default.homeDirectoryForCurrentUser.path] : owned
@@ -771,16 +772,23 @@ public enum DonkeyCommandBackends {
let workingDirectory = workspaceBaseDir(context)
let owned = ownedRoots(context)
- // Decide consent. A command runs UNPROMPTED when it is a read, or a bounded file mutator whose every
- // operand sits inside a folder Donkey created — managing its own folder is not the user's to approve.
- // Anything else (a mutation reaching a user file, an interpreter, a network tool) prompts first;
- // nothing is silently refused.
+ // Decide consent. A command runs UNPROMPTED when it is a read; a bounded file mutator whose every
+ // operand sits inside a folder Donkey created; or a scripting interpreter the kernel jail can
+ // contain — managing its own folder is not the user's to approve. Anything else (a mutation
+ // reaching a user file, a network tool, a side-effecting app driver) prompts first; nothing is
+ // silently refused.
let classification = ShellCommandClassifier.classify(command)
+ let resolvedWorkdir = workingDirectory ?? FileManager.default.homeDirectoryForCurrentUser.path
+ // An interpreter (python3/ruby/…) reshaping files in Donkey's own folder runs unprompted, the same
+ // as a bounded mutator — because the kernel jail keeps its WRITES in those folders. Reads and the
+ // network stay open like every spawn, so a script that inspects a file or calls an API still works;
+ // a write aimed at a user file is stopped by the kernel rather than a prompt.
let unprompted = classification.tier == .read
+ || ShellCommandClassifier.isWorkspaceConfinedInterpreterRun(
+ command, ownedRoots: owned, workingDirectory: resolvedWorkdir
+ )
|| ShellCommandClassifier.everySegmentMutatesOnlyOwnedRoots(
- command,
- ownedRoots: owned,
- workingDirectory: workingDirectory ?? FileManager.default.homeDirectoryForCurrentUser.path
+ command, ownedRoots: owned, workingDirectory: resolvedWorkdir
)
if !unprompted {
if let gate = await consentGate(context, command: command, classification: classification) {
@@ -790,8 +798,9 @@ public enum DonkeyCommandBackends {
let timeout = context.call.input["timeoutSeconds"].flatMap(Double.init)
.map { min(max($0, 1), shellTimeoutMax) } ?? shellTimeout
- // Confine the spawn (kernel-enforced): reads open, writes held to the owned folders — plus the user's
- // home when they approved this command at a prompt, so the approved write lands. nil → no folder yet.
+ // Confine the spawn (kernel-enforced): reads open, network open, writes held to the owned folders —
+ // plus the user's home when they approved this command at a prompt, so the approved write lands.
+ // nil → no folder yet.
let policy = shellPolicy(owned: owned, consented: !unprompted)
let result = await Task.detached(priority: .userInitiated) {
runShellSync(command, timeout: timeout, workingDirectory: workingDirectory, policy: policy)
diff --git a/apps/Donkey/Sources/DonkeyRuntime/ShellCommandClassifier.swift b/apps/Donkey/Sources/DonkeyRuntime/ShellCommandClassifier.swift
index 55e5eca9..ac1dfd7f 100644
--- a/apps/Donkey/Sources/DonkeyRuntime/ShellCommandClassifier.swift
+++ b/apps/Donkey/Sources/DonkeyRuntime/ShellCommandClassifier.swift
@@ -61,13 +61,13 @@ public enum ShellCommandClassifier {
/// `everySegmentMutatesOnlyOwnedRoots`): the agent managing its own folder is the work the user said it
/// shouldn't have to approve. A mutation that reaches a file the user owns prompts like any other.
///
- /// Scripting interpreters (`python3`, `ruby`, `perl`, `node`) are deliberately ABSENT. Their effect is
- /// the code they run, not the paths in argv — `python3 script.py` can delete a user folder no static
- /// look at the command line can see — so "a workspace exists" is no containment at all for them. They
- /// stay on the normal consent path, surfacing a clear "runs a … script" prompt the user can
- /// always-allow. `sed -i` is absent for a related reason: its file operand can't be told apart from its
- /// script argument statically, so it too prompts. Tools with side effects beyond the filesystem
- /// (osascript, open, killall, …) are absent for the same reason.
+ /// Scripting interpreters (`python3`, `ruby`, `perl`, `node`) are ABSENT here because their effect is
+ /// the opaque code they run, not the paths in argv — no static look at `python3 script.py` can clear
+ /// its operands. They are contained a different way: `isWorkspaceConfinedInterpreterRun` lets one run
+ /// unprompted when the spawn is jailed to the owned folders, so the KERNEL — not an operand check —
+ /// keeps its WRITES in the workspace. `sed -i` is absent for a related reason: its file operand can't be
+ /// told apart from its script argument statically, so it prompts. Tools with side effects the jail does
+ /// not contain (osascript, open, killall, …) are absent for the same reason.
public static let workspaceFileToolSignatures: Set<String> = [
"mkdir", "touch", "cp", "mv", "ln", "tee", "rm", "rmdir", "chmod"
]
@@ -78,6 +78,65 @@ public enum ShellCommandClassifier {
workspaceFileToolSignatures.contains(signature)
}
+ /// The scripting interpreters whose effect is the opaque code they run, not their argv — so operand
+ /// analysis can't clear them the way it clears a bounded mutator. The kernel jail can: confined to the
+ /// owned folders, an interpreter can only WRITE inside the workspace (reads and the network stay open,
+ /// as for every spawn). This is what lets a workspace data step run without a prompt.
+ public static let workspaceInterpreterSignatures: Set<String> = ["python3", "python", "ruby", "perl", "node"]
+
+ /// Whether the line may run UNPROMPTED because the kernel jail confines its writes to the owned folders.
+ /// It qualifies when nothing escalates the line to high-risk (no sudo/rm/curl/`-exec`/pipe-to-shell/
+ /// device-redirect) AND every segment is one of: a read (a plain read, a bundled tool, a read
+ /// subcommand); a bounded file mutator whose operands all sit in an owned root; or a bare scripting
+ /// interpreter (`python3`/`ruby`/…). At least one interpreter must be present — a line without one is
+ /// already covered by the read or bounded-mutator paths.
+ ///
+ /// An interpreter is opaque, so its safety rests on the KERNEL, not a look at its arguments: the caller
+ /// jails the spawn to the owned folders, so a script can only WRITE inside the workspace — a write
+ /// aimed at a user file is stopped by the kernel instead of a prompt. Reads and the network stay open,
+ /// exactly as they are for every other spawn, so a script that inspects a file or calls an API still
+ /// works. The unprompted pass therefore depends on a folder existing to confine writes into: with no
+ /// owned roots there is no jail, so this returns false and the interpreter prompts as before. Anything
+ /// the jail can't contain — a side-effecting tool (`open`/`osascript`), a mutation reaching outside the
+ /// folder — also disqualifies the line. Argv tokens only; any resolution ambiguity errs toward prompting.
+ public static func isWorkspaceConfinedInterpreterRun(
+ _ command: String,
+ ownedRoots: [String],
+ workingDirectory: String
+ ) -> Bool {
+ // A high-risk construct anywhere (sudo, rm, an -exec flag, pipe-to-shell, a device redirect) is not
+ // contained by the filesystem jail, so it never rides this unprompted path.
+ guard classify(command).tier != .highRisk else { return false }
+ let owned = ownedRoots.compactMap(canonicalDirectory)
+ guard !owned.isEmpty else { return false }
+ let workdir = canonicalDirectory(workingDirectory) ?? (workingDirectory as NSString).expandingTildeInPath
+ let segments = splitSegments(command).map(tokenize).filter { !$0.isEmpty }
+ guard !segments.isEmpty else { return false }
+ var sawInterpreter = false
+ for tokens in segments {
+ let exe = executableName(tokens[0])
+ if workspaceInterpreterSignatures.contains(exe) {
+ sawInterpreter = true
+ continue
+ }
+ // Any read — a plain read, a bundled capability tool, a read subcommand — rides along; reads
+ // change nothing and the jail confines the line's writes regardless.
+ if classifySegment(tokens).tier == .read { continue }
+ // A bounded file mutator is fine only when every operand resolves inside an owned root.
+ if workspaceFileToolSignatures.contains(exe),
+ pathOperands(of: tokens).allSatisfy({ operand in
+ guard let resolved = resolveOperandPath(operand, workingDirectory: workdir) else { return false }
+ return owned.contains { isWithin(resolved, root: $0) }
+ }) {
+ continue
+ }
+ // Anything else (open, osascript, an out-of-folder mutation) is not contained by the jail —
+ // disqualify and let the line prompt.
+ return false
+ }
+ return sawInterpreter
+ }
+
/// Whether EVERY command in the line is a bare bounded file mutator (`mv`, `rm`, `mkdir`, `chmod`, …)
/// AND every path operand it names resolves inside one of `ownedRoots` — the folders Donkey created.
/// Such a line runs WITHOUT a consent prompt: it only creates, moves, or deletes files, and only inside
diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/ShellCommandClassifierTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/ShellCommandClassifierTests.swift
index bc8c9ed2..1626326a 100644
--- a/apps/Donkey/Tests/DonkeyRuntimeTests/ShellCommandClassifierTests.swift
+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/ShellCommandClassifierTests.swift
@@ -248,16 +248,75 @@ struct ShellCommandClassifierTests {
}
@Test
- func interpretersAreNotWorkspaceTools() {
- // A scripting interpreter's effect is the opaque code it runs, not the paths in argv, so "a
- // workspace exists" is no containment — it must prompt (once, always-allowable), never auto-run.
+ func interpretersAreNotBoundedFileTools() {
+ // A scripting interpreter's effect is the opaque code it runs, not the paths in argv, so operand
+ // analysis can't clear it: it is not a bounded FILE tool. (It is instead contained by the kernel
+ // jail — see `workspaceConfinedInterpretersRunUnprompted`.) Its tier stays reversibleWrite so that,
+ // with no workspace to jail it into, it still surfaces a clear "runs a … script" prompt.
for command in ["python3 map.py", "python3 -c 'print(1)'", "ruby s.rb", "node x.js", "perl y.pl"] {
let c = ShellCommandClassifier.classify(command)
#expect(c.tier == .reversibleWrite)
- #expect(!ShellCommandClassifier.isWorkspaceFileTool(c.signature), "interpreter must prompt: \(command)")
+ #expect(!ShellCommandClassifier.isWorkspaceFileTool(c.signature), "not a bounded file tool: \(command)")
}
}
+ @Test
+ func workspaceConfinedInterpretersRunUnprompted() throws {
+ // The motivating annoyance: Donkey parsing a JSON file it created in its own folder with
+ // `python3 -c "json.load(open('fields.json'))"` prompted on every call. An interpreter is opaque,
+ // so it can't be cleared by operand analysis — but jailed to the owned folder (writes confined
+ // there, reads and network open), it can only reshape workspace files, so it runs without a prompt.
+ let ws = try makeOwnedRoot()
+ defer { try? FileManager.default.removeItem(atPath: ws) }
+ func confined(_ c: String) -> Bool {
+ ShellCommandClassifier.isWorkspaceConfinedInterpreterRun(c, ownedRoots: [ws], workingDirectory: ws)
+ }
+ for command in [
+ "python3 -c \"import json; print(len(json.load(open('fields.json'))))\"",
+ "python3 map.py",
+ "ruby s.rb",
+ "node x.js",
+ "perl y.pl",
+ "cat fields.json | python3 -c 'import sys,json; json.load(sys.stdin)'", // read piped to interpreter
+ "ls && python3 process.py", // read then interpreter
+ "mkdir \"\(ws)/out\" && python3 build.py", // owned mutator + interpreter
+ "yt-dlp 'https://x' && python3 process.py", // bundled tool keeps its open network
+ "python3 -c \"import urllib.request; urllib.request.urlopen('https://x')\"", // a network call inside the script just works
+ ] {
+ #expect(confined(command), "should run unprompted (jailed writes, network open): \(command)")
+ }
+ }
+
+ @Test
+ func interpretersThatEscapeTheJailStillPrompt() throws {
+ // The free pass is only for what the jail contains. A network tool, a destructive neighbor, an
+ // -exec escape, a pipe-to-shell, or a side-effecting app driver (open/osascript) all disqualify the
+ // line — it prompts as before. (A bare `curl`/`open` is gated on its own; the interpreter's own
+ // network access is fine, since the jail's job is bounding writes, not egress.)
+ let ws = try makeOwnedRoot()
+ defer { try? FileManager.default.removeItem(atPath: ws) }
+ func confined(_ c: String) -> Bool {
+ ShellCommandClassifier.isWorkspaceConfinedInterpreterRun(c, ownedRoots: [ws], workingDirectory: ws)
+ }
+ for command in [
+ "python3 fetch.py && curl http://x", // explicit network tool is gated on its own
+ "python3 -c 'print(1)' | sh", // pipe to shell
+ "python3 clean.py; rm -rf ~/Downloads", // destructive neighbor
+ "python3 -c 'print(1)' && open -a Mail", // app driving — jail doesn't contain it
+ "python3 -c 'print(1)' && osascript -e 'tell app \"Mail\" to quit'",
+ "sudo python3 x.py", // privileged
+ "python3 -c \"open('\(ws)/../escape.txt','w')\" && mv \"\(ws)/../escape.txt\" \"\(ws)/a\"", // mutator climbs out
+ ] {
+ #expect(!confined(command), "should still prompt: \(command)")
+ }
+ // No owned roots → no jail to contain the interpreter → it prompts.
+ #expect(!ShellCommandClassifier.isWorkspaceConfinedInterpreterRun(
+ "python3 -c 'print(1)'", ownedRoots: [], workingDirectory: ws))
+ // No interpreter present → this path doesn't apply (the read/mutator paths cover it).
+ #expect(!ShellCommandClassifier.isWorkspaceConfinedInterpreterRun(
+ "ls -la", ownedRoots: [ws], workingDirectory: ws))
+ }
+
@Test
func boundedMutatorsInsideTheOwnedFolderRunUnprompted() throws {
// Every segment is a pure file mutator AND every operand resolves inside a folder Donkey created, so