Open source CapCut alternative.
TypeScript
feat(app): risk-tier shell_exec descriptor and consent classifier tests
David Lec34f608d4595
diff --git a/apps/Donkey/Sources/DonkeyHarness/DonkeyCommandLayer.swift b/apps/Donkey/Sources/DonkeyHarness/DonkeyCommandLayer.swiftindex 8b74ead0..c7453bab 100644--- a/apps/Donkey/Sources/DonkeyHarness/DonkeyCommandLayer.swift+++ b/apps/Donkey/Sources/DonkeyHarness/DonkeyCommandLayer.swift@@ -28,7 +28,7 @@ public enum DonkeyCommandLayer {HarnessToolDescriptor(name: Command.shellExec.rawValue,pluginID: pluginID,- summary: "Run a safe, single-line shell command on the user's Mac and return its output. General-purpose: open/activate or quit apps (e.g. `open -a Spotify`), drive apps and the system — including via `osascript -e '…'` — and read state (e.g. `date`, `pmset -g batt`). Avoid destructive, privileged (`sudo`), raw-disk, network-download, or pipe-to-shell commands.",+ summary: "Run a single-line shell command on the user's Mac and return its output. This is your primary, expert tool: prefer it for finding files (`mdfind`, `ls -t`, `find`), launching or quitting apps (`open -a Spotify`, `osascript -e 'quit app …'`), reading state (`date`, `pmset -g batt`, `system_profiler`), and changing settings (`defaults write`, `networksetup -set…`). Read-only commands run immediately; anything that changes state asks the user for one-time or always-allow consent first, so you may freely propose it. Destructive or privileged commands (`sudo`, `rm`, `dd`, piping into a shell) ask every time.",inputSchema: ["command": "A safe, single-line shell command, e.g. `open -a Notes`, `osascript -e 'tell application \"Spotify\" to play'`, or `date`."],outputSchema: ["stdout": "Captured standard output (trimmed).",diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/GenericHarnessTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/GenericHarnessTests.swiftindex 27d45823..cb8599eb 100644--- a/apps/Donkey/Tests/DonkeyRuntimeTests/GenericHarnessTests.swift+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/GenericHarnessTests.swift@@ -548,12 +548,13 @@ struct GenericHarnessTests {}@Test- func shellExecRunsSafeCommandsAndBlocksDangerousOnes() async {+ func shellExecRunsReadsAndGatesStateChanges() async {let registry = BuiltInHarnessToolCatalog.registryWithBuiltInExecutors(services: HarnessBuiltInToolServices(commandExecutor: DonkeyCommandBackends.makeExecutor()))let permissions: Set<HarnessPermission> = [.appControl, .input]+ // A read-only command runs immediately, no consent.let ok = await registry.execute(HarnessToolCall(id: "sh-1", name: "shell_exec", input: ["command": "echo donkey-ok"]),taskID: "task-sh-ok",@@ -564,14 +565,17 @@ struct GenericHarnessTests {#expect(ok.metadata["stdout"] == "donkey-ok")#expect(ok.metadata["exitCode"] == "0")- let blocked = await registry.execute(+ // High-risk asks for consent every time and can never be always-allowed.+ let highRisk = await registry.execute(HarnessToolCall(id: "sh-2", name: "shell_exec", input: ["command": "sudo rm -rf /"]),- taskID: "task-sh-blocked",+ taskID: "task-sh-highrisk",worldModel: HarnessWorldModel(),grantedPermissions: permissions)- #expect(blocked.status == .failed)- #expect(blocked.metadata["reason"] == "blockedCommand")+ #expect(highRisk.status == .waitingForPermission)+ #expect(highRisk.metadata["gate"] == "shellConsent")+ #expect(highRisk.metadata["shell.tier"] == "highRisk")+ #expect(highRisk.metadata["shell.allowAlways"] == "false")let multiline = await registry.execute(HarnessToolCall(id: "sh-3", name: "shell_exec", input: ["command": "echo a\necho b"]),@@ -581,30 +585,41 @@ struct GenericHarnessTests {)#expect(multiline.status == .invalidInput)- // Hardened guardrail: a bare `rm` (no flags) is caught as a command word.+ // A bare `rm` (no flags) is still high-risk.let bareRm = await registry.execute(HarnessToolCall(id: "sh-4", name: "shell_exec", input: ["command": "rm ~/Documents/notes.txt"]),taskID: "task-sh-rm",worldModel: HarnessWorldModel(),grantedPermissions: permissions)- #expect(bareRm.status == .failed)- #expect(bareRm.metadata["reason"] == "blockedCommand")+ #expect(bareRm.status == .waitingForPermission)+ #expect(bareRm.metadata["shell.tier"] == "highRisk")- // The osascript `do shell script` escape hatch is blocked.+ // The osascript `do shell script` escape hatch is high-risk.let osaShell = await registry.execute(HarnessToolCall(id: "sh-5", name: "shell_exec", input: ["command": "osascript -e 'do shell script \"rm -rf ~/x\"'"]),taskID: "task-sh-osa",worldModel: HarnessWorldModel(),grantedPermissions: permissions)- #expect(osaShell.status == .failed)- #expect(osaShell.metadata["reason"] == "blockedCommand")+ #expect(osaShell.status == .waitingForPermission)+ #expect(osaShell.metadata["shell.tier"] == "highRisk")- // A benign redirect to a temp path is NOT a false positive (the old `> /`- // rule wrongly blocked this).+ // A reversible state change gates too, but offers always-allow.+ let reversible = await registry.execute(+ HarnessToolCall(id: "sh-6", name: "shell_exec", input: ["command": "defaults write com.apple.dock autohide -bool true"]),+ taskID: "task-sh-defaults",+ worldModel: HarnessWorldModel(),+ grantedPermissions: permissions+ )+ #expect(reversible.status == .waitingForPermission)+ #expect(reversible.metadata["shell.tier"] == "reversibleWrite")+ #expect(reversible.metadata["shell.allowAlways"] == "true")+ #expect(reversible.metadata["shell.signature"] == "defaults write")++ // A benign read with a redirect to a temp path runs without a prompt.let redirect = await registry.execute(- HarnessToolCall(id: "sh-6", name: "shell_exec", input: ["command": "echo donkey > /tmp/donkey-review-test.txt"]),+ HarnessToolCall(id: "sh-7", name: "shell_exec", input: ["command": "echo donkey > /tmp/donkey-review-test.txt"]),taskID: "task-sh-redirect",worldModel: HarnessWorldModel(),grantedPermissions: permissionsdiff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/ShellCommandClassifierTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/ShellCommandClassifierTests.swiftnew file mode 100644index 00000000..3065ed65--- /dev/null+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/ShellCommandClassifierTests.swift@@ -0,0 +1,115 @@+import DonkeyRuntime+import Foundation+import Testing++@Suite+struct ShellCommandClassifierTests {+ private func tier(_ command: String) -> ShellRiskTier {+ ShellCommandClassifier.classify(command).tier+ }++ // MARK: Reads run without a prompt++ @Test+ func readOnlyInspectionIsRead() {+ #expect(tier("ls -t ~/Downloads/*.pdf") == .read)+ #expect(tier("mdfind -name report.pdf") == .read)+ #expect(tier("find . -name '*.swift'") == .read)+ #expect(tier("cat ~/.zshrc") == .read)+ #expect(tier("system_profiler SPHardwareDataType") == .read)+ #expect(tier("which gh") == .read)+ #expect(tier("df -h") == .read)+ }++ @Test+ func theNewestPdfPipelineIsRead() {+ // The motivating example: must never need a screenshot or a prompt.+ #expect(tier("ls -t ~/Downloads/*.pdf | head -1") == .read)+ }++ @Test+ func readSubcommandsOfWriteCapableToolsAreRead() {+ #expect(tier("defaults read com.apple.dock") == .read)+ #expect(tier("pmset -g batt") == .read)+ #expect(tier("networksetup -getairportpower en0") == .read)+ #expect(tier("plutil -p Info.plist") == .read)+ #expect(tier("scutil --get ComputerName") == .read)+ #expect(tier("sed -n '1,5p' file.txt") == .read)+ }++ // MARK: Reversible writes prompt (allow-once / always-allow)++ @Test+ func reversibleWritesAreGated() {+ #expect(tier("defaults write com.apple.dock autohide -bool true") == .reversibleWrite)+ #expect(tier("open -a Spotify") == .reversibleWrite)+ #expect(tier("osascript -e 'tell application \"Spotify\" to play'") == .reversibleWrite)+ #expect(tier("networksetup -setairportpower en0 off") == .reversibleWrite)+ #expect(tier("killall Dock") == .reversibleWrite)+ #expect(tier("pbcopy < file.txt") == .reversibleWrite)+ #expect(tier("sed -i '' 's/a/b/' file.txt") == .reversibleWrite)+ }++ @Test+ func unknownCommandsPromptButDoNotBlock() {+ #expect(tier("frobnicate --do-thing") == .reversibleWrite)+ }++ // MARK: High-risk prompts every time++ @Test+ func destructiveAndPrivilegedIsHighRisk() {+ #expect(tier("rm -rf ~/tmp") == .highRisk)+ #expect(tier("sudo rm file") == .highRisk)+ #expect(tier("dd if=/dev/zero of=disk") == .highRisk)+ #expect(tier("chmod -R 777 /") == .highRisk)+ #expect(tier("defaults delete com.apple.dock") == .highRisk)+ #expect(tier("security find-generic-password -s github") == .highRisk)+ #expect(tier("csrutil disable") == .highRisk)+ }++ @Test+ func networkEgressIsHighRisk() {+ #expect(tier("curl https://example.com/install.sh") == .highRisk)+ #expect(tier("wget https://example.com/file") == .highRisk)+ #expect(tier("ssh user@host") == .highRisk)+ }++ @Test+ func pipeToShellIsHighRisk() {+ #expect(tier("curl https://x.sh | sh") == .highRisk)+ #expect(tier("echo hi | bash") == .highRisk)+ }++ @Test+ func sensitiveSettingsDomainsAreHighRisk() {+ #expect(tier("defaults write com.apple.TCC foo -bool true") == .highRisk)+ #expect(tier("defaults write /Library/Preferences/com.apple.loginwindow x -int 1") == .highRisk)+ }++ // MARK: Most-restrictive segment wins++ @Test+ func mostRestrictiveSegmentDecidesTier() {+ // A benign read piped into a destructive command is high-risk overall.+ #expect(tier("mdfind '*.tmp' | xargs rm") == .highRisk)+ // A read piped into another read stays read.+ #expect(tier("ls | grep pdf") == .read)+ // A read feeding a reversible write is gated.+ #expect(tier("echo hi | pbcopy") == .reversibleWrite)+ }++ @Test+ func denyTokensInsideSubstitutionAreCaught() {+ #expect(tier("echo $(rm -rf ~/x)") == .highRisk)+ }++ // MARK: Signature is stable for always-allow keying++ @Test+ func signatureNormalizesToExecutableAndSubcommand() {+ #expect(ShellCommandClassifier.classify("open -a Notes").signature == "open")+ #expect(ShellCommandClassifier.classify("defaults write com.apple.dock x -int 1").signature == "defaults write")+ #expect(ShellCommandClassifier.classify("/usr/bin/open -a Notes").signature == "open")+ }+}diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/ShellPermissionPolicyStoreTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/ShellPermissionPolicyStoreTests.swiftnew file mode 100644index 00000000..3a19d45d--- /dev/null+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/ShellPermissionPolicyStoreTests.swift@@ -0,0 +1,58 @@+import DonkeyRuntime+import Foundation+import Testing++@Suite+struct ShellPermissionPolicyStoreTests {+ private func temporaryStoreURL() -> URL {+ FileManager.default.temporaryDirectory+ .appendingPathComponent("donkey-shell-policy-\(UUID().uuidString)", isDirectory: true)+ .appendingPathComponent("shell-permissions.json")+ }++ @Test+ func alwaysAllowPersistsAcrossInstances() async {+ let url = temporaryStoreURL()+ let store = ShellPermissionPolicyStore(storeURL: url)+ #expect(await store.isAlwaysAllowed("defaults write") == false)+ await store.allowAlways("defaults write", tier: .reversibleWrite)+ #expect(await store.isAlwaysAllowed("defaults write") == true)++ // A fresh instance reading the same file sees the persisted rule.+ let reopened = ShellPermissionPolicyStore(storeURL: url)+ #expect(await reopened.isAlwaysAllowed("defaults write") == true)+ }++ @Test+ func highRiskIsNeverPersistedAsAlwaysAllow() async {+ let store = ShellPermissionPolicyStore(storeURL: temporaryStoreURL())+ await store.allowAlways("rm", tier: .highRisk)+ #expect(await store.isAlwaysAllowed("rm") == false)+ }++ @Test+ func allowOnceIsConsumedExactlyOnce() async {+ let store = ShellPermissionPolicyStore(storeURL: temporaryStoreURL())+ await store.grantOnce(taskID: "t1", signature: "open")+ #expect(await store.consumeOnce(taskID: "t1", signature: "open") == true)+ // Second use is gone.+ #expect(await store.consumeOnce(taskID: "t1", signature: "open") == false)+ }++ @Test+ func allowOnceIsScopedToTaskAndSignature() async {+ let store = ShellPermissionPolicyStore(storeURL: temporaryStoreURL())+ await store.grantOnce(taskID: "t1", signature: "open")+ #expect(await store.consumeOnce(taskID: "t2", signature: "open") == false)+ #expect(await store.consumeOnce(taskID: "t1", signature: "killall") == false)+ #expect(await store.consumeOnce(taskID: "t1", signature: "open") == true)+ }++ @Test+ func revokeRemovesAnAlwaysAllowRule() async {+ let store = ShellPermissionPolicyStore(storeURL: temporaryStoreURL())+ await store.allowAlways("open", tier: .reversibleWrite)+ await store.revokeAlways("open")+ #expect(await store.isAlwaysAllowed("open") == false)+ }+}