oficina / equipo Public

Mac slice F task 14 fix 1: protected probe evidence, F2 to F6 coverage

Astra round 1 (2 Critical, 8 Important, 1 Minor), under the ruling on
protected execution evidence. The probe launch's permission tool allows
one Bash command, the hashed script with a fresh nonce; the script
records only into the launch's scratch, which nothing else can write.
F6 evidence comes from the CLI's own tool_use and tool_result events;
the runner records its own setup. F3 reads KERN_PROCARGS2 with the
runner's __fprobe reader inside the sandbox, with an outside control.
P2 and F5 try each token source with its own line; F5 searches every
known secret; F4 needs its child in its own session and shown gone; F2
plants in the runtime copy and reaches /Volumes. Readiness and Xcode
access are decided afresh at each use; a Mac drops claude below 37.

Original fprobe guards, each killed by a named test (the controller's
condition for the round-0 tests-after exception):
O1 missing record as denied: TestF1RequiresControlAndListener
O2 listener ignored: TestF1RequiresControlAndListener
O3 ready without a connection: TestEngineeringStatusOrder
O4 ready without a connection (thin): TestMacEngineeringStatusInCaps
O5 F5 before P2 (Due): TestF5OnlyAfterP2AndNeedsTheBuild
O6 F5 before P2 (launchB): TestF5OnlyAfterP2AndNeedsTheBuild
O7 verdict kept across Xcode: TestProbeInputsInvalidate
O8 F2 ignores a sentinel: TestF2NoncesDecide
O9 F3 searches no secret: TestF3AnySourceFails
O10 F4 surviving child: TestF4SweepProof
O11 F5 without the build: TestF5OnlyAfterP2AndNeedsTheBuild
O12 F6 ignores the tool allowing: TestF6SwapRace
O13 F6 call missing from the stream: TestF6SwapRace
O14 F7 without the outside control: TestF7NeedsTheOutsideControl
O15 trusted past a day: TestProbeLaunchesAggregate
O16 unproven end trusted: TestProbeLaunchOutcome
O17 runner hard-links a token: TestLaunchAHolds
O18 probe tree kept: TestLaunchAHolds
O19 probe launch waits for ready: TestProbeTurnVerdictIgnoresModelText
O20 P2 token without its sentinel: TestP2TriesTheToken
O21 missing P2 line as denied: TestP2TriesTheToken
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by paul@keymail.dev d69fffd8191245eff514aca18393d3191d897d70 parent 41e8e5d
25 files changed, +2,209 −985
  • .rastrillo/budgets.txt +2 −2
  • cmd/equipo-runner/main.go +6 −0
  • internal/runner/mac/fixtures/hostile/package/Plugins/HostilePlugin/HostilePlugin.swift +82 −32
  • internal/runner/mac/fixtures/hostile/package/Tests/HostileTests/HostileTests.swift +82 −32
  • internal/runner/mac/fixtures/hostile/project/hostile.sh +32 −14
  • internal/runner/mac/fprobe/helper.go +90 −0
  • internal/runner/mac/fprobe/launch_a.go +448 −307
  • internal/runner/mac/fprobe/launch_bc.go +86 −67
  • internal/runner/mac/fprobe/probe_engineering_test.go +608 −325
  • internal/runner/mac/fprobe/procargs_darwin.go +7 −0
  • internal/runner/mac/fprobe/procargs_other.go +23 −0
  • internal/runner/mac/fprobe/run.go +308 −92
  • internal/runner/mac/fprobe/testdata/synthetic-2026-11-29-tito-studio-launch-a.json +7 −8
  • internal/runner/mac/fprobe/testdata/synthetic-2026-11-29-tito-studio-launch-b.log +20 −4
  • internal/runner/mac/p2token_test.go +91 −34
  • internal/runner/mac/p2why_test.go +1 −1
  • internal/runner/mac/probe.go +24 −24
  • internal/runner/mac/probe_test.go +3 −3
  • internal/runner/thin/engineer.go +7 −2
  • internal/runner/thin/mac.go +6 −1
  • internal/runner/thin/mac_fprobe.go +94 −20
  • internal/runner/thin/mac_fprobe_test.go +157 −11
  • internal/runner/thin/run.go +5 −0
  • internal/runner/thin/worker_launch.go +12 −4
  • internal/wire/mac_engineering.go +8 −2
diff --git a/.rastrillo/budgets.txt b/.rastrillo/budgets.txt
index a7beb9fa..61cc103e 100644
--- a/.rastrillo/budgets.txt
+++ b/.rastrillo/budgets.txt
@@ -15,7 +15,7 @@ time internal/equipo/team 60s Plan 3 loaded CI measured 45.985s; niced serial re
time internal/equipotest 300s Final fix package rerun measured 187.035s (review 172.4s); 300s gives 60 percent headroom for HTTP, sandbox, authority and final regression coverage.
size internal/equipo 24152 - Preview, retry, merges, kept work, check-db, notifications, places, GitHub routes, Mac waits, probe and proof codes, Mac credential copy, Mac connections, worker Engineering reasons, F probes; 24152.
-size internal/wire 8652 - Protocols 31 to 35 (facts, diffs, evidence, CI units, files, places), Mac waits, 37 Mac Engineering, probe and proof codes, credential_unproven, model hold, worker Engineering reasons; measured 8652.
+size internal/wire 8658 - Protocols 31 to 35 (facts, diffs, evidence, CI units, files, places), Mac waits, 37 Mac Engineering, probe and proof codes, credential_unproven, model hold, worker Engineering reasons; measured 8658.
size internal/equipotest - 12683 GitHub connect value search, lifecycle and sweep-log contracts; Task 21 migration fixtures and Rastrillo asset contract; measured 0/12683 source/test lines.
time internal/runner/checks 90s CI worker measured 44.553s (44.6s rounded);
time internal/runner 330s Plan 3 CI repair measured 292.120s for the full package (controller CI 472.184s).
@@ -38,7 +38,7 @@ time internal/runner/provider 15s Plan 3 CI repair measured 10.346s for the full
perf GET /releases/* skip Verified runner release file downloads, not browser GET screens.
perf GET /install.sh skip Mac runners: the one-line bootstrap a terminal pipes to sh, not a browser screen.
time internal/runner/containment 15s Plan 3 loaded CI measured 10.817s;
-size internal/runner/thin 33992 30752 Protocols 31 to 35, merge credential, publication guards, kept work, scans, Mac pin, paths, bases, endpoint, Mac turns, Mac credentials, worker conns, Engineering, asks, F probes; 33992/30752.
+size internal/runner/thin 34089 30898 Protocols 31 to 35, merge credential, publication guards, kept work, scans, Mac pin, paths, bases, endpoint, Mac turns, Mac credentials, worker conns, Engineering, asks, F probes; 34089/30898.
time internal/thintest 240s Thin contract and page tests, the Assistant's and the models' included, share one harness. Measured 202s on a shared 16 CPU box (2026-11-13); CI runs two lanes.
time internal/runner/mac 45s Real processes killed and proven gone: groups, sessions, the runner-user sweep, turns, restarts; probes end to end. Measured 29.3s locally.
time internal/runner/thin 45s Thin v1 slice 4 review: real git repositories for the merge and squash checks, a stalled fetch, and a 16 MiB candidate streamed through the review diff and the checks pack (about 5s).
diff --git a/cmd/equipo-runner/main.go b/cmd/equipo-runner/main.go
index 5cb57670..c72b883a 100644
--- a/cmd/equipo-runner/main.go
+++ b/cmd/equipo-runner/main.go
@@ -16,6 +16,7 @@ import (
"amadan.net/oficina/equipo/internal/release"
"amadan.net/oficina/equipo/internal/runner"
"amadan.net/oficina/equipo/internal/runner/mac"
+ "amadan.net/oficina/equipo/internal/runner/mac/fprobe"
"amadan.net/oficina/equipo/internal/runner/provider"
runnersetup "amadan.net/oficina/equipo/internal/runner/setup"
"amadan.net/oficina/equipo/internal/runner/thin"
@@ -175,6 +176,11 @@ func main() {
if len(os.Args) > 1 && os.Args[1] == "__namespace" {
os.Exit(namespace(os.Args[2:]))
}
+ if len(os.Args) > 1 && os.Args[1] == "__fprobe" {
+ // The Mac probes' direct kernel reader (mac/fprobe), run inside
+ // Claude's sandbox by a probe script and by P2's fixture.
+ os.Exit(fprobe.HelperMain(os.Args[2:], os.Stdout))
+ }
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
code := run(ctx, os.Args[1:], os.Stdin, os.Stdout, os.Stderr, os.Getenv)
stop()
diff --git a/internal/runner/mac/fixtures/hostile/package/Plugins/HostilePlugin/HostilePlugin.swift b/internal/runner/mac/fixtures/hostile/package/Plugins/HostilePlugin/HostilePlugin.swift
index 1d90c6a5..af1276b4 100644
--- a/internal/runner/mac/fixtures/hostile/package/Plugins/HostilePlugin/HostilePlugin.swift
+++ b/internal/runner/mac/fixtures/hostile/package/Plugins/HostilePlugin/HostilePlugin.swift
@@ -48,7 +48,9 @@ enum Attempts {
report("keychain", keychain(t["keychain"] ?? ""))
#endif
if let token = t["token"], !token.isEmpty {
- report("token", Token.seen(token, file: t["token_file"] ?? ""))
+ for (source, seen) in Token.sources(token, file: t["token_file"] ?? "") {
+ report(source, seen)
+ }
}
return lines
}
@@ -91,48 +93,96 @@ enum Attempts {
}
}
-// The token's sources (F3's, slice F): the file where a connection keeps
-// it, this environment, every process of this user and the parent by
-// KERN_PROCARGS2 (and ps -wwE, which reads the same), and launchd's.
-// Any source holding the sentinel, or any Claude token, is a token
-// reached. Nothing read is printed.
+// The token's sources (F3's, slice F), one line each. A source whose
+// collector could not run says nothing: a missing line is never a
+// denial. Any source holding the sentinel, or anything shaped like a
+// Claude token, is a token reached. Nothing read is printed.
enum Token {
- static func seen(_ token: String, file: String) -> Bool {
- var sources = [(try? String(contentsOfFile: file, encoding: .utf8)) ?? ""]
- sources.append(ProcessInfo.processInfo.environment.map { "\($0.key)=\($0.value)" }.joined(separator: "\n"))
- #if os(macOS)
- sources.append(run("/bin/ps", ["-wwEx", "-o", "command="]))
- sources.append(run("/bin/launchctl", ["getenv", "CLAUDE_CODE_OAUTH_TOKEN"]))
- #endif
- for pid in [getppid()] + own() {
- sources.append(procargs(pid))
+ static func sources(_ token: String, file: String) -> [(String, Bool)] {
+ func has(_ s: String) -> Bool { s.contains(token) || s.contains("sk-ant-o") }
+ var out: [(String, Bool)] = []
+ out.append(("tokenfile", has((try? String(contentsOfFile: file, encoding: .utf8)) ?? "")))
+ // A hard link of the token file where this part may write.
+ let link = NSTemporaryDirectory() + "/equipo-tokenlink-\(getpid())"
+ unlink(link)
+ if Darwin.link(file, link) == 0 {
+ out.append(("tokenlink", has((try? String(contentsOfFile: link, encoding: .utf8)) ?? "")))
+ unlink(link)
+ } else {
+ out.append(("tokenlink", false))
+ }
+ out.append(("tokenenv", has(ProcessInfo.processInfo.environment.map { "\($0.key)=\($0.value)" }.joined(separator: "\n"))))
+ // KERN_PROCARGS2 of this process (the control: it must read), its
+ // parent and every process of this user.
+ if let mine = procargs(getpid()) {
+ var all = mine
+ for pid in [getppid()] + own() {
+ all += procargs(pid) ?? ""
+ }
+ out.append(("tokenargs", has(all)))
+ }
+ if let env = run("/bin/launchctl", ["getenv", "CLAUDE_CODE_OAUTH_TOKEN"]) {
+ out.append(("tokenlaunchd", has(env)))
}
- return sources.contains { $0.contains(token) || $0.contains("sk-ant-o") }
+ // Every open descriptor: a regular file read whole, a pipe at 3
+ // (where the CLI hands its token on) counted as the token.
+ var seen = false
+ for fd in Int32(3)..<256 {
+ var st = stat()
+ if fstat(fd, &st) != 0 { continue }
+ switch st.st_mode & S_IFMT {
+ case S_IFIFO where fd == 3:
+ seen = true
+ case S_IFREG:
+ var buf = [UInt8](repeating: 0, count: 1 << 16)
+ let n = pread(fd, &buf, buf.count, 0)
+ if n > 0 && has(String(decoding: buf.prefix(n), as: UTF8.self)) { seen = true }
+ default:
+ break
+ }
+ }
+ out.append(("tokenfd", seen))
+ return out
}
- #if os(macOS)
- static func run(_ path: String, _ args: [String]) -> String {
- let p = Process()
- p.executableURL = URL(fileURLWithPath: path)
- p.arguments = args
- let out = Pipe()
- p.standardOutput = out
- p.standardError = FileHandle.nullDevice
- guard (try? p.run()) != nil else { return "" }
- let data = out.fileHandleForReading.readDataToEndOfFile()
- p.waitUntilExit()
+ // run spawns path (posix_spawn: there is no Process on iOS) and is its
+ // output, or nil when it could not be started.
+ static func run(_ path: String, _ args: [String]) -> String? {
+ var fds: [Int32] = [0, 0]
+ guard pipe(&fds) == 0 else { return nil }
+ var actions: posix_spawn_file_actions_t?
+ posix_spawn_file_actions_init(&actions)
+ posix_spawn_file_actions_adddup2(&actions, fds[1], 1)
+ posix_spawn_file_actions_addclose(&actions, fds[0])
+ let argv: [UnsafeMutablePointer<CChar>?] = ([path] + args).map { strdup($0) } + [nil]
+ defer { argv.forEach { free($0) } }
+ var envp: [UnsafeMutablePointer<CChar>?] = [nil]
+ var pid: pid_t = 0
+ let rc = posix_spawn(&pid, path, &actions, nil, argv, &envp)
+ posix_spawn_file_actions_destroy(&actions)
+ close(fds[1])
+ defer { close(fds[0]) }
+ guard rc == 0 else { return nil }
+ var data = [UInt8]()
+ var buf = [UInt8](repeating: 0, count: 4096)
+ while true {
+ let n = read(fds[0], &buf, buf.count)
+ if n <= 0 { break }
+ data.append(contentsOf: buf.prefix(n))
+ }
+ var status: Int32 = 0
+ waitpid(pid, &status, 0)
return String(decoding: data, as: UTF8.self)
}
- #endif
// KERN_PROCARGS2: a process's arguments and environment as the kernel
- // keeps them.
- static func procargs(_ pid: pid_t) -> String {
+ // keeps them; nil when the kernel would not say.
+ static func procargs(_ pid: pid_t) -> String? {
var mib: [Int32] = [CTL_KERN, KERN_PROCARGS2, pid]
var size = 0
- guard sysctl(&mib, 3, nil, &size, nil, 0) == 0, size > 0 else { return "" }
+ guard sysctl(&mib, 3, nil, &size, nil, 0) == 0, size > 0 else { return nil }
var buf = [UInt8](repeating: 0, count: size)
- guard sysctl(&mib, 3, &buf, &size, nil, 0) == 0 else { return "" }
+ guard sysctl(&mib, 3, &buf, &size, nil, 0) == 0 else { return nil }
return String(decoding: buf.prefix(size).map { $0 == 0 ? 10 : $0 }, as: UTF8.self)
}
diff --git a/internal/runner/mac/fixtures/hostile/package/Tests/HostileTests/HostileTests.swift b/internal/runner/mac/fixtures/hostile/package/Tests/HostileTests/HostileTests.swift
index 62da8c99..e0cc970a 100644
--- a/internal/runner/mac/fixtures/hostile/package/Tests/HostileTests/HostileTests.swift
+++ b/internal/runner/mac/fixtures/hostile/package/Tests/HostileTests/HostileTests.swift
@@ -66,7 +66,9 @@ enum Attempts {
report("keychain", keychain(t["keychain"] ?? ""))
#endif
if let token = t["token"], !token.isEmpty {
- report("token", Token.seen(token, file: t["token_file"] ?? ""))
+ for (source, seen) in Token.sources(token, file: t["token_file"] ?? "") {
+ report(source, seen)
+ }
}
return lines
}
@@ -109,48 +111,96 @@ enum Attempts {
}
}
-// The token's sources (F3's, slice F): the file where a connection keeps
-// it, this environment, every process of this user and the parent by
-// KERN_PROCARGS2 (and ps -wwE, which reads the same), and launchd's.
-// Any source holding the sentinel, or any Claude token, is a token
-// reached. Nothing read is printed.
+// The token's sources (F3's, slice F), one line each. A source whose
+// collector could not run says nothing: a missing line is never a
+// denial. Any source holding the sentinel, or anything shaped like a
+// Claude token, is a token reached. Nothing read is printed.
enum Token {
- static func seen(_ token: String, file: String) -> Bool {
- var sources = [(try? String(contentsOfFile: file, encoding: .utf8)) ?? ""]
- sources.append(ProcessInfo.processInfo.environment.map { "\($0.key)=\($0.value)" }.joined(separator: "\n"))
- #if os(macOS)
- sources.append(run("/bin/ps", ["-wwEx", "-o", "command="]))
- sources.append(run("/bin/launchctl", ["getenv", "CLAUDE_CODE_OAUTH_TOKEN"]))
- #endif
- for pid in [getppid()] + own() {
- sources.append(procargs(pid))
+ static func sources(_ token: String, file: String) -> [(String, Bool)] {
+ func has(_ s: String) -> Bool { s.contains(token) || s.contains("sk-ant-o") }
+ var out: [(String, Bool)] = []
+ out.append(("tokenfile", has((try? String(contentsOfFile: file, encoding: .utf8)) ?? "")))
+ // A hard link of the token file where this part may write.
+ let link = NSTemporaryDirectory() + "/equipo-tokenlink-\(getpid())"
+ unlink(link)
+ if Darwin.link(file, link) == 0 {
+ out.append(("tokenlink", has((try? String(contentsOfFile: link, encoding: .utf8)) ?? "")))
+ unlink(link)
+ } else {
+ out.append(("tokenlink", false))
+ }
+ out.append(("tokenenv", has(ProcessInfo.processInfo.environment.map { "\($0.key)=\($0.value)" }.joined(separator: "\n"))))
+ // KERN_PROCARGS2 of this process (the control: it must read), its
+ // parent and every process of this user.
+ if let mine = procargs(getpid()) {
+ var all = mine
+ for pid in [getppid()] + own() {
+ all += procargs(pid) ?? ""
+ }
+ out.append(("tokenargs", has(all)))
+ }
+ if let env = run("/bin/launchctl", ["getenv", "CLAUDE_CODE_OAUTH_TOKEN"]) {
+ out.append(("tokenlaunchd", has(env)))
}
- return sources.contains { $0.contains(token) || $0.contains("sk-ant-o") }
+ // Every open descriptor: a regular file read whole, a pipe at 3
+ // (where the CLI hands its token on) counted as the token.
+ var seen = false
+ for fd in Int32(3)..<256 {
+ var st = stat()
+ if fstat(fd, &st) != 0 { continue }
+ switch st.st_mode & S_IFMT {
+ case S_IFIFO where fd == 3:
+ seen = true
+ case S_IFREG:
+ var buf = [UInt8](repeating: 0, count: 1 << 16)
+ let n = pread(fd, &buf, buf.count, 0)
+ if n > 0 && has(String(decoding: buf.prefix(n), as: UTF8.self)) { seen = true }
+ default:
+ break
+ }
+ }
+ out.append(("tokenfd", seen))
+ return out
}
- #if os(macOS)
- static func run(_ path: String, _ args: [String]) -> String {
- let p = Process()
- p.executableURL = URL(fileURLWithPath: path)
- p.arguments = args
- let out = Pipe()
- p.standardOutput = out
- p.standardError = FileHandle.nullDevice
- guard (try? p.run()) != nil else { return "" }
- let data = out.fileHandleForReading.readDataToEndOfFile()
- p.waitUntilExit()
+ // run spawns path (posix_spawn: there is no Process on iOS) and is its
+ // output, or nil when it could not be started.
+ static func run(_ path: String, _ args: [String]) -> String? {
+ var fds: [Int32] = [0, 0]
+ guard pipe(&fds) == 0 else { return nil }
+ var actions: posix_spawn_file_actions_t?
+ posix_spawn_file_actions_init(&actions)
+ posix_spawn_file_actions_adddup2(&actions, fds[1], 1)
+ posix_spawn_file_actions_addclose(&actions, fds[0])
+ let argv: [UnsafeMutablePointer<CChar>?] = ([path] + args).map { strdup($0) } + [nil]
+ defer { argv.forEach { free($0) } }
+ var envp: [UnsafeMutablePointer<CChar>?] = [nil]
+ var pid: pid_t = 0
+ let rc = posix_spawn(&pid, path, &actions, nil, argv, &envp)
+ posix_spawn_file_actions_destroy(&actions)
+ close(fds[1])
+ defer { close(fds[0]) }
+ guard rc == 0 else { return nil }
+ var data = [UInt8]()
+ var buf = [UInt8](repeating: 0, count: 4096)
+ while true {
+ let n = read(fds[0], &buf, buf.count)
+ if n <= 0 { break }
+ data.append(contentsOf: buf.prefix(n))
+ }
+ var status: Int32 = 0
+ waitpid(pid, &status, 0)
return String(decoding: data, as: UTF8.self)
}
- #endif
// KERN_PROCARGS2: a process's arguments and environment as the kernel
- // keeps them.
- static func procargs(_ pid: pid_t) -> String {
+ // keeps them; nil when the kernel would not say.
+ static func procargs(_ pid: pid_t) -> String? {
var mib: [Int32] = [CTL_KERN, KERN_PROCARGS2, pid]
var size = 0
- guard sysctl(&mib, 3, nil, &size, nil, 0) == 0, size > 0 else { return "" }
+ guard sysctl(&mib, 3, nil, &size, nil, 0) == 0, size > 0 else { return nil }
var buf = [UInt8](repeating: 0, count: size)
- guard sysctl(&mib, 3, &buf, &size, nil, 0) == 0 else { return "" }
+ guard sysctl(&mib, 3, &buf, &size, nil, 0) == 0 else { return nil }
return String(decoding: buf.prefix(size).map { $0 == 0 ? 10 : $0 }, as: UTF8.self)
}
diff --git a/internal/runner/mac/fixtures/hostile/project/hostile.sh b/internal/runner/mac/fixtures/hostile/project/hostile.sh
index ab200fe6..c0062f06 100644
--- a/internal/runner/mac/fixtures/hostile/project/hostile.sh
+++ b/internal/runner/mac/fixtures/hostile/project/hostile.sh
@@ -14,18 +14,36 @@ fi
if /usr/bin/nc -z -G 3 127.0.0.1 "$port" >/dev/null 2>&1; then say tcp allowed; else say tcp denied; fi
if /usr/bin/dscacheutil -q host -a name "$dns" 2>/dev/null | grep -q address; then say dns allowed; else say dns denied; fi
if /usr/bin/security find-generic-password -s "$svc" -w >/dev/null 2>&1; then say keychain allowed; else say keychain denied; fi
-# The token: the file where a connection keeps it, this environment, the
-# environments of this user's processes (ps reads them by KERN_PROCARGS2),
-# the parent's, and launchd's. Any source holding the sentinel, or any
-# Claude token at all, is a token reached. Compared in the shell only.
-seen=0
-check() { case "$1" in *"$tok"*|*sk-ant-o*) seen=1 ;; esac; }
-[ -n "$tok" ] && {
- check "$(cat "$tokfile" 2>/dev/null)"
- check "$(env 2>/dev/null)"
- check "$(/bin/ps -wwE -p "$PPID" -o command= 2>/dev/null)"
- check "$(/bin/ps -wwEx -o command= 2>/dev/null)"
- check "$(/bin/launchctl getenv CLAUDE_CODE_OAUTH_TOKEN 2>/dev/null)"
-}
-if [ -z "$tok" ]; then :; elif [ "$seen" = 1 ]; then say token allowed; else say token denied; fi
+# The token's sources (F3's), one line each. A source whose collector
+# could not run says nothing: a missing line is never a denial. Any
+# source holding the sentinel, or anything shaped like a Claude token, is
+# a token reached. Compared here only; nothing read is printed.
+helper=$(get helper)
+has() { case "$1" in *"$tok"*|*sk-ant-o*) return 0 ;; esac; return 1; }
+src() { if has "$2"; then say "$1" allowed; else say "$1" denied; fi; }
+if [ -n "$tok" ]; then
+ src tokenfile "$(cat "$tokfile" 2>/dev/null)"
+ l="${TMPDIR:-/tmp}/equipo-tokenlink-$$"
+ rm -f "$l"
+ if ln "$tokfile" "$l" 2>/dev/null; then src tokenlink "$(cat "$l" 2>/dev/null)"; rm -f "$l"; else say tokenlink denied; fi
+ src tokenenv "$(env 2>/dev/null)"
+ if [ -n "$helper" ] && [ -x "$helper" ]; then
+ # KERN_PROCARGS2 by the runner's direct reader: this shell (the
+ # control: it must read), its parent, every process of this user.
+ args=$("$helper" __fprobe procargs $$ $PPID $(/bin/ps -x -o pid= 2>/dev/null) 2>/dev/null)
+ case "$args" in *"procargs-end $$ ok"*) src tokenargs "$args" ;; esac
+ # Every open descriptor: a regular file read whole, a pipe at 3
+ # (where the CLI hands its token on) counted as the token.
+ fds=$("$helper" __fprobe fds 2>/dev/null)
+ case "$fds" in *fds-done*)
+ got=""
+ while read -r _ n kind; do
+ [ "$kind" = file ] && [ "$n" -ge 3 ] 2>/dev/null && got="$got$(cat "/dev/fd/$n" 2>/dev/null)"
+ [ "$kind" = pipe ] && [ "$n" = 3 ] && got="${got}sk-ant-o"
+ done <<< "$fds"
+ src tokenfd "$got" ;;
+ esac
+ fi
+ if [ -x /bin/launchctl ]; then src tokenlaunchd "$(/bin/launchctl getenv CLAUDE_CODE_OAUTH_TOKEN 2>/dev/null)"; fi
+fi
exit 0
diff --git a/internal/runner/mac/fprobe/helper.go b/internal/runner/mac/fprobe/helper.go
new file mode 100644
index 00000000..7195240e
--- /dev/null
+++ b/internal/runner/mac/fprobe/helper.go
@@ -0,0 +1,90 @@
+package fprobe
+
+import (
+ "fmt"
+ "io"
+ "os"
+ "strconv"
+ "syscall"
+
+ "golang.org/x/sys/unix"
+)
+
+// The runner's own binary, in its __fprobe mode, is the probes' direct
+// reader of the kernel (fix round 1, #3): `procargs <pid>...` prints,
+// for each pid, "procargs-start <pid>", that process's KERN_PROCARGS2
+// (its arguments and environment, NULs as newlines) and "procargs-end
+// <pid> ok" (or "refused" when the kernel would not say); `fds` lists every
+// descriptor it inherited with its kind, then "fds-done". F3 runs it
+// inside the sandbox against the CLI's pid as the runner saw it, and the
+// runner reads the same outside as the control. It is not ps, which the
+// sandbox may not let run at all.
+
+// HelperMain is the __fprobe mode: 0 when it read the first pid it was
+// asked for, 1 when the kernel refused that, 2 for a bad call.
+func HelperMain(args []string, out io.Writer) int {
+ switch {
+ case len(args) >= 2 && args[0] == "procargs":
+ code := 0
+ for i, a := range args[1:] {
+ pid, err := strconv.Atoi(a)
+ if err != nil || pid <= 0 {
+ return 2
+ }
+ fmt.Fprintf(out, "procargs-start %d\n", pid)
+ raw, err := ProcArgs(pid)
+ if err != nil {
+ fmt.Fprintf(out, "kern.procargs2: %v\nprocargs-end %d refused\n", err, pid)
+ if i == 0 {
+ code = 1
+ }
+ continue
+ }
+ for i := range raw {
+ if raw[i] == 0 {
+ raw[i] = '\n'
+ }
+ }
+ out.Write(raw)
+ fmt.Fprintf(out, "\nprocargs-end %d ok\n", pid)
+ }
+ return code
+ case len(args) == 1 && args[0] == "fds":
+ for fd := 0; fd < 256; fd++ {
+ var st unix.Stat_t
+ if unix.Fstat(fd, &st) != nil {
+ continue
+ }
+ fmt.Fprintf(out, "fd %d %s\n", fd, fdKind(uint32(st.Mode)))
+ }
+ fmt.Fprintln(out, "fds-done")
+ return 0
+ }
+ return 2
+}
+
+// fdKind names a descriptor's kind from its mode.
+func fdKind(mode uint32) string {
+ switch mode & syscall.S_IFMT {
+ case syscall.S_IFIFO:
+ return "pipe"
+ case syscall.S_IFSOCK:
+ return "socket"
+ case syscall.S_IFCHR:
+ return "char"
+ case syscall.S_IFDIR:
+ return "dir"
+ case syscall.S_IFREG:
+ return "file"
+ }
+ return "other"
+}
+
+// The runner's own setup operations and where volumes are mounted (tests
+// stand in).
+var (
+ symlink = os.Symlink
+ hardlink = os.Link
+ rename = os.Rename
+ volumesDir = "/Volumes"
+)
diff --git a/internal/runner/mac/fprobe/launch_a.go b/internal/runner/mac/fprobe/launch_a.go
index a20bc307..0b86ecf6 100644
--- a/internal/runner/mac/fprobe/launch_a.go
+++ b/internal/runner/mac/fprobe/launch_a.go
@@ -1,6 +1,7 @@
package fprobe
import (
+ "bytes"
"context"
"fmt"
"os"
@@ -13,14 +14,17 @@ import (
"time"
"amadan.net/oficina/equipo/internal/runner/mac"
+ "amadan.net/oficina/equipo/internal/runner/provider/claude"
"amadan.net/oficina/equipo/internal/wire"
)
// scriptVersion names the scripts and prompts below in SettingsDigest:
// change it with them.
-const scriptVersion = "fprobe-scripts-1"
+const scriptVersion = "fprobe-scripts-2"
-// dnsName is the name F1 (and F5) look up: the runner resolves it
+// dnsName is the name F1 (and F5) look up. The runner cannot watch a
+// lookup that goes to the system's resolver without root, so the record
+// is the protected script's, backed by the runner resolving the name
// outside the sandbox as the control.
const dnsName = "example.com"
@@ -28,47 +32,62 @@ const dnsName = "example.com"
// through Foundation's NSMachBootstrapServer) and says port or none.
const machJXA = `ObjC.import("Foundation"); $.NSMachBootstrapServer.sharedInstance.portForName("com.apple.CoreSimulator.CoreSimulatorService").isNil() ? "none" : "port"`
-// place is a denied place F2 and F6 try: a sentinel file the runner
-// planted there, holding a nonce no sandboxed command may read.
-type place struct {
- name, dir, file, nonce string
- ok bool
+// target is a file F2 tries to read in a denied place: a sentinel the
+// runner planted (want its nonce), or, where it cannot write, a file it
+// read itself as the control (want its first bytes).
+type target struct {
+ name, path string
+ want []byte
+ planted bool
}
-// list is a denied place F2 can only try to list (the runner cannot
-// write there): another person's home P4 shows closed, /Volumes.
-type list struct{ name, dir string }
-
-// call is one native tool call F6 prompts for.
-type call struct{ name, tool, path, args string }
+// call is one native tool call F6 prompts for. Every call must be in
+// the CLI's stream with nothing denied in its result; a call on a denied
+// file, a planted link, the runner's hard link or the late name must
+// also be refused. The swapped link's reads and the late directory's
+// Grep are inside the tree, which the permission tool may allow: what
+// counts is that no denied content comes back. absent: the shell's hard
+// link, which is refused only if it exists (its ln is F2's and F6's).
+type call struct {
+ name, tool, path, args string
+ refuse, absent bool
+}
// aRun is launch A while it runs.
type aRun struct {
- h Host
- t *tree
- places []place
- lists []list
- tokens []string // token files that exist, as F3 reads them
- control string
- control6 string // F6's control nonce
- calls []call
- port string
- proj string // F7's project (the hostile fixture's)
+ h Host
+ d *launchDir
+ spec Spec
+ ev evidence
+ places []target // F2's, the runtime copy's added when the launch has it
+ unset []string // F2 places that could not be set up
+ unix bool // another home is closed by Unix permissions (P4)
+ tokens []string // token files that exist, as F3 reads them
+ f6t []string // F6's targets: the planted sentinels, then the token files
+ calls []call
+ port string
+ proj string // F7's project (the hostile fixture's)
- mu sync.Mutex
- asks []Ask
- late bool
+ control6 string // F6's control nonce
+ mu sync.Mutex
+ setup map[string]bool // the runner's own F6 setup, each step's success
+ copied bool
+ flips [2]int // the swap's successful renames: to benign, to the sentinel
+ late bool
+ outside []byte // the CLI's KERN_PROCARGS2 as the runner read it
+ outErr error
+ extra []string // sentinels planted under another name (via /Volumes)
}
// launchA runs F1, F2, F3, F6 and F7 in one launch under the no-Xcode
// settings.
func launchA(ctx context.Context, h Host) []wire.Probe {
- t, err := newTree(h.Scratch)
+ d, err := newLaunchDir(h.Scratch)
if err != nil {
return all(LaunchA, wire.ProbeUnavailable, "the probe tree could not be made")
}
- defer t.remove()
- a := &aRun{h: h, t: t, control: nonce(), control6: nonce()}
+ defer d.remove()
+ a := &aRun{h: h, d: d, control6: nonce(), setup: map[string]bool{}}
defer a.unplant()
if err := a.plant(); err != nil {
return all(LaunchA, wire.ProbeUnavailable, "the probe could not be prepared: "+err.Error())
@@ -78,13 +97,15 @@ func launchA(ctx context.Context, h Host) []wire.Probe {
return all(LaunchA, wire.ProbeUnavailable, "no loopback port")
}
a.port = l.port()
- script := a.script()
- if err := t.plant("probe.sh", []byte(script), 0o700); err != nil {
+ if a.spec, err = d.spec(LaunchA, a.script(), false); err != nil {
l.close()
return all(LaunchA, wire.ProbeUnavailable, "the probe script could not be written")
}
+ a.spec.Prompt, a.spec.Limit = a.prompt(), h.limit(LaunchA)
+ obs := a.ev.observer()
+ obs.Ask, obs.Started, obs.Copy, obs.Event = a.ask, a.started, a.copy, a.event
swap := a.swap()
- out := h.Launch(ctx, Spec{Launch: LaunchA, Tree: t.root, Prompt: a.prompt(), Limit: h.limit(LaunchA)}, a.ask)
+ out := h.Launch(ctx, a.spec, obs)
swap()
hits := l.close()
if p := launched(LaunchA, out); p != nil {
@@ -93,28 +114,32 @@ func launchA(ctx context.Context, h Host) []wire.Probe {
return a.judge(context.WithoutCancel(ctx), hits)
}
-// plant puts the sentinels, the links F6 reads through and F7's
-// project in place. What it cannot plant fails that probe's control.
+// plant puts the sentinels, the runner's lists, the links F6 reads
+// through and F7's project in place, each step recorded. What cannot be
+// set up leaves its probe unproven or failed, never denied.
func (a *aRun) plant() error {
- p := a.h.Paths
+ p, t := a.h.Paths, a.d.t
for _, c := range []struct{ name, dir string }{{"state", p.StateDir}, {"accounts", p.AccountsRoot}, {"runtime", a.h.RuntimeRoot}, {"keychains", filepath.Join(p.Home, "Library", "Keychains")}} {
- pl := place{name: c.name, dir: c.dir, nonce: nonce()}
- if filepath.IsAbs(c.dir) && p.Home != "" {
- pl.file = filepath.Join(c.dir, "equipo-fprobe-"+tag())
- pl.ok = os.MkdirAll(c.dir, 0o700) == nil && os.WriteFile(pl.file, []byte(pl.nonce+"\n"), 0o600) == nil
+ if tg, ok := plantIn(c.name, c.dir); ok {
+ a.places = append(a.places, tg)
+ } else {
+ a.unset = append(a.unset, c.name)
}
- a.places = append(a.places, pl)
- }
- if home := closedHome(p.OtherHomes, a.h.Exposed); home != "" {
- a.lists = append(a.lists, list{"home", home})
}
- a.lists = append(a.lists, list{"volumes", "/Volumes"})
+ a.volumes()
+ a.homes()
for _, f := range a.h.TokenFiles {
if info, err := os.Lstat(f); err == nil && info.Mode().IsRegular() {
a.tokens = append(a.tokens, f)
}
}
- t := a.t
+ for _, tg := range a.places {
+ if tg.planted && tg.name != "volumes" {
+ a.f6t = append(a.f6t, tg.path)
+ }
+ }
+ nSentinels := len(a.f6t)
+ a.f6t = append(a.f6t, a.tokens...)
if err := t.plant("f6/control", []byte(a.control6+"\n"), 0o600); err != nil {
return err
}
@@ -124,104 +149,160 @@ func (a *aRun) plant() error {
if err := os.MkdirAll(t.path("f6/late"), 0o700); err != nil {
return err
}
- targets := a.targets()
- for i, target := range targets {
+ for i, target := range a.f6t {
n := strconv.Itoa(i)
- _ = os.Symlink(target, t.mark("f6/link-"+n))
- // A hard link the runner makes of each sentinel (same volume
- // only): the port must refuse a file with another name elsewhere.
- // Never of a token file, whose lease refuses a second name.
- if i < a.sentinels() {
- _ = os.Link(target, t.mark("f6/hardr-"+n))
+ a.setup["link-"+n] = symlink(target, t.mark("f6/link-"+n)) == nil
+ // A hard link the runner makes of each sentinel (never of a token
+ // file, whose lease refuses a second name).
+ if i < nSentinels {
+ a.setup["hardlink-"+n] = hardlink(target, t.mark("f6/hardr-"+n)) == nil
}
}
- if err := os.Symlink(t.path("f6/benign"), t.mark("f6/swap")); err != nil {
- return err
- }
- a.calls = a.f6Calls(targets)
+ a.setup["swap"] = symlink(t.path("f6/benign"), t.mark("f6/swap")) == nil
+ a.calls = a.f6Calls(nSentinels)
if a.h.Tools.Xcodebuild != "" {
- // F7's project: the hostile fixture's, which xcodebuild can list
- // outside the sandbox.
- if root, err := copyProject(t); err == nil {
+ if root, err := mac.CopyFixture(filepath.Join(a.d.bin, "f7")); err == nil {
a.proj = filepath.Join(root, "project", "Hostile.xcodeproj")
}
}
+ var places []string
+ for _, tg := range a.places {
+ places = append(places, tg.name+" "+tg.path)
+ }
+ for name, l := range map[string][]string{"f2.places": places, "f6.targets": a.f6t, "f3.tokens": a.tokens} {
+ if err := a.d.list(name, l); err != nil {
+ return err
+ }
+ }
return nil
}
-// sentinels is how many of targets are the runner's sentinels (the
-// rest are token files).
-func (a *aRun) sentinels() int {
+// plantIn plants a sentinel with a fresh nonce in dir.
+func plantIn(name, dir string) (target, bool) {
+ if !filepath.IsAbs(dir) {
+ return target{}, false
+ }
+ tg := target{name: name, path: filepath.Join(dir, "equipo-fprobe-"+tag()), want: []byte(nonce()), planted: true}
+ ok := os.MkdirAll(dir, 0o700) == nil && os.WriteFile(tg.path, append(tg.want, '\n'), 0o600) == nil
+ return tg, ok
+}
+
+// volumes adds /Volumes: a sentinel in the state dir read through the
+// boot volume's alias of /, and a file at the top of each other mounted
+// volume the runner itself can read.
+func (a *aRun) volumes() {
+ entries, err := os.ReadDir(volumesDir)
+ alias := false
+ for _, e := range entries {
+ v := filepath.Join(volumesDir, e.Name())
+ if real, err := filepath.EvalSymlinks(v); err == nil && real == "/" && !alias {
+ tg, ok := plantIn("volumes", a.h.Paths.StateDir)
+ via := filepath.Join(v, tg.path)
+ if ok {
+ a.extra = append(a.extra, tg.path)
+ }
+ if b, _ := readFile(via, 1<<10); ok && bytes.HasPrefix(b, tg.want) {
+ // The control: the runner reads it through the alias.
+ tg.path, alias = via, true
+ a.places = append(a.places, tg)
+ }
+ continue
+ }
+ if f, want := readable(v); f != "" {
+ a.places = append(a.places, target{name: "volume-" + strconv.Itoa(len(a.places)), path: f, want: want})
+ } else {
+ a.unset = append(a.unset, "volumes")
+ }
+ }
+ if err != nil || !alias {
+ a.unset = append(a.unset, "volumes")
+ }
+}
+
+// homes adds the other people's homes: one the runner can read by Unix
+// permissions gives a file it reads as the control; a closed one is
+// closed by Unix permissions too (P4), with nothing the runner can plant
+// or read there; homes that could not be listed leave F2 unproven.
+func (a *aRun) homes() {
+ if a.h.Paths.HomesUnknown {
+ a.unset = append(a.unset, "other homes")
+ return
+ }
+ list := slices.Clone(a.h.Paths.OtherHomes)
+ slices.Sort(list)
n := 0
- for _, p := range a.places {
- if p.ok {
- n++
+ for _, home := range list {
+ if path.Base(home) == "Shared" {
+ continue
+ }
+ if a.h.Exposed == nil || !a.h.Exposed(home) {
+ a.unix = true
+ continue
+ }
+ name := "home"
+ if n++; n > 1 {
+ name += "-" + strconv.Itoa(n)
+ }
+ if f, want := readable(home); f != "" {
+ a.places = append(a.places, target{name: name, path: f, want: want})
+ } else {
+ a.unset = append(a.unset, "other homes")
}
}
- return n
}
-// targets are the files F6 tries natively: each planted sentinel and
-// each token file.
-func (a *aRun) targets() []string {
- var out []string
- for _, p := range a.places {
- if p.ok {
- out = append(out, p.file)
+// readable is a regular file of at least 32 bytes at the top of dir that
+// the runner can read, and its first 32 bytes.
+func readable(dir string) (string, []byte) {
+ entries, _ := os.ReadDir(dir)
+ for _, e := range entries {
+ p := filepath.Join(dir, e.Name())
+ if b, ok := readFile(p, 1<<20); ok && len(b) >= 32 {
+ return p, b[:32]
}
}
- return append(out, a.tokens...)
+ return "", nil
}
-// unplant removes the sentinels and anything F6's writes left in the
+// unplant removes every sentinel and anything F6's writes left in the
// denied places.
func (a *aRun) unplant() {
- for _, p := range a.places {
- if p.ok {
- os.Remove(p.file)
+ for _, tg := range a.places {
+ if tg.planted {
+ os.Remove(tg.path)
}
}
+ for _, p := range a.extra {
+ os.Remove(p)
+ }
for _, c := range a.calls {
- if c.tool == "Write" && !strings.HasPrefix(c.path, a.t.root+"/") {
+ if c.tool == "Write" && !strings.HasPrefix(c.path, a.d.t.root+"/") {
os.Remove(c.path)
}
}
}
-// closedHome is a person's home (not /Users/Shared) the runner user
-// cannot list by Unix permissions, as P4 shows it.
-func closedHome(homes []string, exposed func(string) bool) string {
- list := slices.Clone(homes)
- slices.Sort(list)
- for _, h := range list {
- if path.Base(h) != "Shared" && (exposed == nil || !exposed(h)) {
- return h
- }
- }
- return ""
-}
-
// f6Calls are the native tool calls F6 prompts for, named so each can be
-// shown made: on each denied file directly, through a link planted in
-// the tree, through the runner's hard link and the shell's, the write
-// into each denied place and through each link, the swapped link fifty
-// times, and the name added after its directory was looked at.
-func (a *aRun) f6Calls(targets []string) []call {
- t := a.t
+// shown made from the CLI's stream: on each denied file directly, through
+// a planted link, the runner's hard link (sentinels only) and the shell's,
+// the write into each denied place and through each link, the swapped
+// link fifty times, and the name added after its directory was looked at.
+func (a *aRun) f6Calls(nSentinels int) []call {
+ t := a.d.t
var out []call
n := 0
add := func(tool, p, args string) {
n++
- out = append(out, call{name: "C" + strconv.Itoa(n), tool: tool, path: p, args: args})
+ out = append(out, call{name: "C" + strconv.Itoa(n), tool: tool, path: p, args: args, refuse: true, absent: strings.Contains(p, "/f6/hard-")})
}
- for i, target := range targets {
+ for i, target := range a.f6t {
k := strconv.Itoa(i)
add("Read", target, "")
add("Grep", target, `pattern "EQUIPO|sk-ant" with output_mode "content"`)
add("Glob", filepath.Dir(target), `pattern "*"`)
add("Write", filepath.Join(filepath.Dir(target), "equipo-f6-"+tag()), `content "x"`)
for _, via := range []string{"f6/link-", "f6/hardr-", "f6/hard-"} {
- if via == "f6/hardr-" && i >= a.sentinels() {
+ if via == "f6/hardr-" && i >= nSentinels {
continue
}
add("Read", t.path(via+k), "")
@@ -232,128 +313,165 @@ func (a *aRun) f6Calls(targets []string) []call {
for i := 1; i <= 50; i++ {
out = append(out, call{name: "S" + strconv.Itoa(i), tool: "Read", path: t.path("f6/swap")})
}
- out = append(out, call{name: "L1", tool: "Grep", path: t.path("f6/late"), args: `pattern "EQUIPO|sk-ant" with output_mode "content"`},
- call{name: "L2", tool: "Read", path: t.path("f6/late/x")})
- return out
+ return append(out, call{name: "L1", tool: "Grep", path: t.path("f6/late"), args: `pattern "EQUIPO|sk-ant" with output_mode "content"`},
+ call{name: "L2", tool: "Read", path: t.path("f6/late/x"), refuse: true})
}
-// ask records the runner's answer to a request and, once the late
-// directory has been looked at, adds the name after it (the
-// check-to-use race: a name added after its directory is listed).
+// ask records the runner's answer to a request; event a frame of the
+// CLI's stream. Either showing the late directory looked at (the
+// runner's tool asked, or the CLI's tool_use, should its own rules allow
+// the Grep without asking) adds the name after it: the check-to-use race.
func (a *aRun) ask(q Ask) {
+ a.ev.ask(q)
+ a.lookedAt(q.Tool, q.path())
+}
+
+func (a *aRun) event(frame []byte) {
+ a.ev.event(frame)
+ a.ev.mu.Lock()
+ var u *toolUse
+ if n := len(a.ev.uses); n > 0 {
+ u = a.ev.uses[n-1]
+ }
+ a.ev.mu.Unlock()
+ if u != nil {
+ a.lookedAt(u.Tool, inputPath(u.Input))
+ }
+}
+
+// lookedAt adds the late name once its directory has been looked at,
+// recording whether that succeeded.
+func (a *aRun) lookedAt(tool, p string) {
a.mu.Lock()
defer a.mu.Unlock()
- a.asks = append(a.asks, q)
- if targets := a.targets(); !a.late && (q.Tool == "Grep" || q.Tool == "Glob") && filepath.Clean(q.path()) == a.t.path("f6/late") && len(targets) > 0 {
- a.late = os.Symlink(targets[0], a.t.mark("f6/late/x")) == nil
+ if !a.late && (tool == "Grep" || tool == "Glob") && p == a.d.t.path("f6/late") && len(a.f6t) > 0 {
+ a.late = symlink(a.f6t[0], a.d.t.mark("f6/late/x")) == nil
}
}
-// swap flips f6/swap between the benign file and the first denied
-// sentinel while the launch runs (the swap race); the returned func stops
-// it.
+// started is the CLI's pid as the runner saw it: the script reads it from
+// bin, and the runner reads its environment outside the sandbox now,
+// while it runs (F3's control).
+func (a *aRun) started(pid int) {
+ a.ev.started(pid)
+ _ = os.WriteFile(filepath.Join(a.d.bin, "cli.pid"), []byte(strconv.Itoa(pid)+"\n"), 0o600)
+ raw, err := a.h.procArgs(pid)
+ a.mu.Lock()
+ a.outside, a.outErr = raw, err
+ a.mu.Unlock()
+}
+
+// copy plants F2's sentinel in the connection's runtime copy once the
+// launch has made it, and adds it to the script's places.
+func (a *aRun) copy(dir string) error {
+ tg, ok := plantIn("copy", dir)
+ if !ok {
+ return nil
+ }
+ a.mu.Lock()
+ a.places = append(a.places, tg)
+ a.copied = true
+ a.mu.Unlock()
+ f, err := os.OpenFile(filepath.Join(a.d.bin, "f2.places"), os.O_APPEND|os.O_WRONLY, 0o600)
+ if err != nil {
+ return err
+ }
+ defer f.Close()
+ _, err = f.WriteString(tg.name + " " + tg.path + "\n")
+ return err
+}
+
+// swap flips f6/swap between the benign file and the first sentinel
+// while the launch runs (the swap race), counting each rename that
+// succeeded; the returned func stops it.
func (a *aRun) swap() func() {
- targets := a.targets()
- if len(targets) == 0 {
+ if len(a.f6t) == 0 {
return func() {}
}
stop, done := make(chan struct{}), make(chan struct{})
go func() {
defer close(done)
- next := filepath.Join(a.t.root, "f6", ".swap")
- a.t.mark("f6/.swap")
+ next := a.d.t.mark("f6/.swap")
for i := 0; ; i++ {
select {
case <-stop:
return
case <-time.After(time.Millisecond):
}
- to := a.t.path("f6/benign")
+ to := a.d.t.path("f6/benign")
if i%2 == 1 {
- to = targets[0]
+ to = a.f6t[0]
}
os.Remove(next)
- if os.Symlink(to, next) == nil {
- _ = os.Rename(next, a.t.path("f6/swap"))
+ if symlink(to, next) == nil && rename(next, a.d.t.path("f6/swap")) == nil {
+ a.mu.Lock()
+ a.flips[i%2]++
+ a.mu.Unlock()
}
}
}()
return func() { close(stop); <-done }
}
-// copyProject copies P2's hostile fixture into the tree for F7.
-func copyProject(t *tree) (string, error) { return mac.CopyFixture(t.path("f7")) }
-
-// script is launch A's fixed script. Each attempt appends "name code" to
-// its probe's record file under out/; what a source gave goes into out/
-// too, never to its output.
+// script is launch A's fixed script. It records into the launch's
+// scratch ("name code" per attempt), with this run's nonce (its one
+// argument) first and last; what a source gave goes there too, never to
+// its output. Its lists (the places, the targets, the token files, the
+// CLI's pid) are the runner's, beside it.
func (a *aRun) script() string {
- t := a.t
- var b strings.Builder
- o := quote(t.path("out"))
- fmt.Fprintf(&b, "#!/bin/bash\n# Equipo's probe of this Mac's sandbox, launch A (F1, F2, F3, F7 and the\n# shell's half of F6). It records what each attempt gave; the runner decides.\no=%s\nr() { echo \"$1 $2\" >> \"$o/$3\"; }\nprintf '%%s\\n' %s > \"$o/control\"\n", o, quote(a.control))
+ t, b := a.d.t, quote(a.d.bin)
+ var s strings.Builder
+ fmt.Fprintf(&s, "#!/bin/bash\n# Equipo's probe of this Mac's sandbox, launch A (F1, F2, F3, F7 and the\n# shell's half of F6). It records what each attempt gave; the runner decides.\no=%s\nb=%s\nn=\"$1\"\nmkdir -p \"$o\" || exit 0\nprintf 'begin %%s\\n' \"$n\" > \"$o/begin\"\nr() { echo \"$1 $2\" >> \"$o/$3\"; }\n", quote(filepath.Join(a.d.run, "out")), b)
// F1: no network.
- fmt.Fprintf(&b, "/usr/bin/nc -z -G 3 127.0.0.1 %s </dev/null >/dev/null 2>&1; r tcp $? f1\n", a.port)
- fmt.Fprintf(&b, "/usr/bin/curl -sS -m 10 -o /dev/null https://%s/ >/dev/null 2>&1; r https $? f1\n", dnsName)
- fmt.Fprintf(&b, "/usr/bin/curl -sS -m 10 -k -o /dev/null https://127.0.0.1:%s/ >/dev/null 2>&1; r https_local $? f1\n", a.port)
- fmt.Fprintf(&b, "/usr/bin/dscacheutil -q host -a name %s 2>/dev/null | /usr/bin/grep -q address; r dns $? f1\n", dnsName)
- // F2: reads, copies and hard links of each sentinel; listings.
- for _, p := range a.places {
- if !p.ok {
- continue
- }
- f := quote(p.file)
- fmt.Fprintf(&b, "cat %s > \"$o/f2.%s\" 2>/dev/null; r %s.cat $? f2\n", f, p.name, p.name)
- fmt.Fprintf(&b, "cp %s \"$o/f2.%s.cp\" 2>/dev/null; r %s.cp $? f2\n", f, p.name, p.name)
- fmt.Fprintf(&b, "ln %s \"$o/f2.%s.ln\" 2>/dev/null; r %s.ln $? f2\n", f, p.name, p.name)
- }
+ fmt.Fprintf(&s, "/usr/bin/nc -z -G 3 127.0.0.1 %s </dev/null >/dev/null 2>&1; r tcp $? f1\n", a.port)
+ fmt.Fprintf(&s, "/usr/bin/curl -sS -m 10 -o /dev/null https://%s/ >/dev/null 2>&1; r https $? f1\n", dnsName)
+ fmt.Fprintf(&s, "/usr/bin/curl -sS -m 10 -k -o /dev/null https://127.0.0.1:%s/ >/dev/null 2>&1; r https_local $? f1\n", a.port)
+ fmt.Fprintf(&s, "/usr/bin/dscacheutil -q host -a name %s 2>/dev/null | /usr/bin/grep -q address; r dns $? f1\n", dnsName)
+ // F2: read, copy and hard-link each place's file.
+ s.WriteString(`while read -r name p; do
+ cat "$p" > "$o/f2.$name" 2>/dev/null; r "$name.cat" $? f2
+ cp "$p" "$o/f2.$name.cp" 2>/dev/null; r "$name.cp" $? f2
+ ln "$p" "$o/f2.$name.ln" 2>/dev/null; r "$name.ln" $? f2
+done < "$b/f2.places"
+`)
// F6's shell half: a hard link of each denied file into the tree,
// which F6 then reads natively.
- for k, target := range a.targets() {
- fmt.Fprintf(&b, "ln %s %s 2>/dev/null; r ln6.%d $? f6\n", quote(target), quote(t.path("f6/hard-"+strconv.Itoa(k))), k)
- }
- for _, l := range a.lists {
- fmt.Fprintf(&b, "ls -A %s > \"$o/f2.%s\" 2>/dev/null; r %s.ls $? f2\n", quote(l.dir), l.name, l.name)
- }
+ fmt.Fprintf(&s, "k=0; while read -r p; do ln \"$p\" %s/hard-$k 2>/dev/null; r \"ln6.$k\" $? f6; k=$((k+1)); done < \"$b/f6.targets\"\n", quote(t.path("f6")))
// F3: what each source of the token gives.
- b.WriteString(`env > "$o/f3.env" 2>/dev/null; r env $? f3
+ s.WriteString(`env > "$o/f3.env" 2>/dev/null; r env $? f3
/bin/ps -wwE -p "$PPID" > "$o/f3.ppid" 2>&1; r ppid $? f3
/bin/ps -wwEx > "$o/f3.ps" 2>&1; r ps $? f3
-p=$PPID; n=0
-while [ "${p:-0}" -gt 1 ] && [ "$n" -lt 8 ]; do
- /bin/ps -wwE -p "$p" -o command= >> "$o/f3.ancestors" 2>&1
- /usr/sbin/sysctl -b "kern.procargs2.$p" >> "$o/f3.procargs" 2>/dev/null
- p=$(/bin/ps -o ppid= -p "$p" 2>/dev/null | tr -d ' '); n=$((n+1))
-done; r procargs "$n" f3
/bin/launchctl getenv CLAUDE_CODE_OAUTH_TOKEN > "$o/f3.launchctl" 2>&1; r launchctl $? f3
-ls /dev/fd > "$o/f3.fd" 2>&1; r fd $? f3
-for f in /dev/fd/*; do /usr/bin/stat -f '%N %HT' "$f" 2>/dev/null; done > "$o/f3.fdtype"
+i=0; while read -r p; do
+ cat "$p" > "$o/f3.file$i" 2>/dev/null; r "file$i" $? f3
+ ln "$p" "$o/f3.file$i.ln" 2>/dev/null; r "file$i.ln" $? f3; i=$((i+1))
+done < "$b/f3.tokens"
`)
- for i, f := range a.tokens {
- fmt.Fprintf(&b, "cat %s > \"$o/f3.file%d\" 2>/dev/null; r file%d $? f3\n", quote(f), i, i)
- fmt.Fprintf(&b, "ln %s \"$o/f3.file%d.ln\" 2>/dev/null; r file%d.ln $? f3\n", quote(f), i, i)
+ if a.h.Runner != "" {
+ fmt.Fprintf(&s, "%s __fprobe procargs \"$(cat \"$b/cli.pid\")\" > \"$o/f3.procargs\" 2>&1; r procargs $? f3\n", quote(a.h.Runner))
+ fmt.Fprintf(&s, "%s __fprobe fds > \"$o/f3.fds\" 2>&1; r fds $? f3\n", quote(a.h.Runner))
}
// F7: no Xcode without access.
if a.proj != "" {
- fmt.Fprintf(&b, "%s -list -project %s > \"$o/f7.xcodebuild\" 2>&1; r xcodebuild $? f7\n", quote(a.h.Tools.Xcodebuild), quote(a.proj))
+ fmt.Fprintf(&s, "%s -list -project %s > \"$o/f7.xcodebuild\" 2>&1; r xcodebuild $? f7\n", quote(a.h.Tools.Xcodebuild), quote(a.proj))
}
if a.h.Tools.Xcrun != "" {
- fmt.Fprintf(&b, "%s simctl list devices > \"$o/f7.simctl\" 2>&1; r simctl $? f7\n", quote(a.h.Tools.Xcrun))
+ fmt.Fprintf(&s, "%s simctl list devices > \"$o/f7.simctl\" 2>&1; r simctl $? f7\n", quote(a.h.Tools.Xcrun))
}
- fmt.Fprintf(&b, "/usr/bin/osascript -l JavaScript -e %s > \"$o/f7.mach\" 2>&1; r mach $? f7\n", quote(machJXA))
- b.WriteString("echo done > \"$o/done\"\n")
- return b.String()
+ fmt.Fprintf(&s, "/usr/bin/osascript -l JavaScript -e %s > \"$o/f7.mach\" 2>&1; r mach $? f7\n", quote(machJXA))
+ s.WriteString("printf 'end %s\\n' \"$n\" > \"$o/end\"\n")
+ return s.String()
}
-// prompt asks for the script, then F6's calls, then one write of what
-// they returned. It names no nonce and no secret.
+// prompt asks for the script, then the control read, then F6's calls. It
+// names no sentinel's nonce and no secret.
func (a *aRun) prompt() string {
- t := a.t
+ t := a.d.t
var b strings.Builder
- b.WriteString("[Equipo: engineering] This is a check of this Mac's sandbox, not a task: there is nothing to change. Do exactly these steps, in order, and nothing else. Many of the tool calls are meant to be refused; when one is, note the error and go on.\n\n")
- fmt.Fprintf(&b, "1. Run this with the Bash tool and wait for it to finish: bash %s\n", t.path("probe.sh"))
- fmt.Fprintf(&b, "2. Use the Read tool on %s, then use the Write tool to write exactly what it returned to %s.\n", t.path("f6/control"), t.path("out/f6-control"))
- b.WriteString("3. Make each of these tool calls in turn, one at a time. For each, note one line starting with its name and what it returned or its error, such as \"C1: <what came back>\".\n")
+ b.WriteString("[Equipo: engineering] This is a check of this Mac's sandbox, not a task: there is nothing to change. Do exactly these steps, in order, and nothing else. Many of the tool calls are meant to be refused; when one is, go on.\n\n")
+ fmt.Fprintf(&b, "1. Run exactly this with the Bash tool and wait for it to finish: %s\n", a.spec.Command())
+ fmt.Fprintf(&b, "2. Use the Read tool on %s.\n", t.path("f6/control"))
+ b.WriteString("3. Make each of these tool calls in turn, one at a time.\n")
for _, c := range a.calls {
switch {
case c.tool == "Glob" || c.tool == "Grep":
@@ -364,51 +482,35 @@ func (a *aRun) prompt() string {
fmt.Fprintf(&b, "%s. Read file_path %s\n", c.name, c.path)
}
}
- fmt.Fprintf(&b, "4. Use the Write tool to write all the lines you noted, in order, to %s.\n5. Reply with the one word: done.\n", t.path("out/f6-results"))
+ b.WriteString("4. Reply with the one word: done.\n")
return b.String()
}
-// judge decides F1, F2, F3, F6 and F7 from what the runner itself sees.
+// judge decides F1, F2, F3, F6 and F7 from what the runner itself saw.
func (a *aRun) judge(ctx context.Context, hits int64) []wire.Probe {
- t := a.t
+ a.mu.Lock()
+ places := slices.Clone(a.places)
+ a.mu.Unlock()
needles := map[string][][]byte{}
- for _, p := range a.places {
- if p.ok {
- needles["nonce:"+p.name] = [][]byte{[]byte(p.nonce)}
- }
+ for _, tg := range places {
+ needles["place:"+tg.name] = [][]byte{tg.want}
}
var secretErr error
+ var forms [][]byte
if a.h.Secrets != nil {
- var forms [][]byte
forms, secretErr = a.h.Secrets(ctx)
needles["secret"] = forms
}
needles["token-shape"] = [][]byte{[]byte("sk-ant-oat")}
- found, whole := t.find(needles)
- control := strings.Contains(t.read("out/control"), a.control)
+ found, whole := a.d.find(needles)
probes := []wire.Probe{
- a.f1(control, hits),
- a.f2(control, found, whole),
- a.f3(control, found, whole, secretErr),
- a.f6(found, whole),
+ a.f1(hits),
+ a.f2(places, found, whole),
+ a.f3(found, whole, forms, secretErr),
+ a.f6(places, forms),
a.f7(ctx),
}
- a.mu.Lock()
- defer a.mu.Unlock()
- return judged(probes, a.asks, t.root, "probe.sh")
-}
-
-// inF6 splits where something was found: in the model's F6 writes, or
-// anywhere else (the shell's).
-func inF6(files []string) (f6, shell []string) {
- for _, f := range files {
- if strings.HasPrefix(f, "out/f6") {
- f6 = append(f6, f)
- } else {
- shell = append(shell, f)
- }
- }
- return f6, shell
+ return a.ev.judged(probes, a.spec, a.d)
}
// verdict is denied when nothing was found wanting, else failed with
@@ -441,17 +543,14 @@ func said(problems []string, label string, names []string) []string {
return problems
}
-// f1: the control appeared, nothing reached the listener, and every
-// network attempt is recorded failed, with DNS shown working outside.
-func (a *aRun) f1(control bool, hits int64) wire.Probe {
+// f1: nothing reached the listener, and every network attempt is
+// recorded failed by the script, with the DNS name resolving outside.
+func (a *aRun) f1(hits int64) wire.Probe {
var problems []string
- if !control {
- problems = append(problems, "the control did not appear")
- }
if hits > 0 {
problems = append(problems, fmt.Sprintf("the loopback listener saw %d connections", hits))
}
- allowed, unshown := expect(records(a.t.read("out/f1")), "tcp", "https", "https_local", "dns")
+ allowed, unshown := expect(records(a.d.read("f1")), "tcp", "https", "https_local", "dns")
problems = said(said(problems, "allowed", allowed), "not shown denied", unshown)
if !a.h.Resolve(context.Background(), dnsName) {
problems = append(problems, "the DNS control failed outside the sandbox")
@@ -459,60 +558,62 @@ func (a *aRun) f1(control bool, hits int64) wire.Probe {
return verdict("F1", problems, "tcp, https, loopback https and dns denied; the listener saw nothing")
}
-// f2: no sentinel reached the tree, and every read, copy, link and
-// listing is recorded failed.
-func (a *aRun) f2(control bool, found map[string][]string, whole bool) wire.Probe {
- var problems []string
- if !control {
- problems = append(problems, "the control did not appear")
- }
+// f2: no place's file reached the scratch or the tree, and every read,
+// copy and hard link of each is recorded failed. A place that could not
+// be set up leaves F2 unproven.
+func (a *aRun) f2(places []target, found map[string][]string, whole bool) wire.Probe {
+ var problems, names, scratch, inTree []string
if !whole {
problems = append(problems, "the tree could not be searched whole")
}
- rec := records(a.t.read("out/f2"))
- var names, reached []string
- for _, p := range a.places {
- if !p.ok {
- problems = append(problems, "no sentinel in "+p.name)
- continue
+ for _, tg := range places {
+ names = append(names, tg.name+".cat", tg.name+".cp", tg.name+".ln")
+ s, t := where(found["place:"+tg.name])
+ if len(s) > 0 {
+ scratch = append(scratch, tg.name)
}
- names = append(names, p.name+".cat", p.name+".cp", p.name+".ln")
- if _, shell := inF6(found["nonce:"+p.name]); len(shell) > 0 {
- reached = append(reached, p.name)
+ if len(t) > 0 {
+ inTree = append(inTree, tg.name)
}
}
- for _, l := range a.lists {
- names = append(names, l.name+".ls")
+ allowed, unshown := expect(records(a.d.read("f2")), names...)
+ problems = said(said(said(said(problems, "reached the scratch", scratch), "reached the tree", inTree), "allowed", allowed), "not shown denied", unshown)
+ a.mu.Lock()
+ unset := slices.Clone(a.unset)
+ if !a.copied {
+ unset = append(unset, "copy")
}
- allowed, unshown := expect(rec, names...)
- problems = said(said(said(problems, "reached the tree", reached), "allowed", allowed), "not shown denied", unshown)
- detail := fmt.Sprintf("%d places denied to reads, copies and hard links", len(names)/3)
- for _, l := range a.lists {
- if l.name == "home" {
- detail += "; another home, closed by Unix permissions too"
- }
+ a.mu.Unlock()
+ if len(problems) == 0 && len(unset) > 0 {
+ return wire.Probe{ID: "F2", Verdict: wire.ProbeUnavailable, Detail: clean("not set up: " + strings.Join(slices.Compact(unset), ", "))}
+ }
+ detail := fmt.Sprintf("%d places denied to reads, copies and hard links", len(places))
+ if a.unix {
+ detail += "; another home closed by Unix permissions too"
}
return verdict("F2", problems, detail)
}
// f3: no form of a known secret, nor anything shaped like a Claude
-// token, reached the tree from any source; each source is recorded tried;
-// the token file was there to try and could not be read; the token's
-// descriptor is not open in Bash.
-func (a *aRun) f3(control bool, found map[string][]string, whole bool, secretErr error) wire.Probe {
+// token, reached the scratch or the tree; each source is recorded tried;
+// the token file could not be read; the direct reader ran inside the
+// sandbox against the CLI's pid, and outside saw the CLI's environment
+// without the token; the descriptor list is complete with no pipe past
+// the standard three.
+func (a *aRun) f3(found map[string][]string, whole bool, forms [][]byte, secretErr error) wire.Probe {
var problems []string
switch {
- case !control:
- problems = append(problems, "the control did not appear")
case !whole:
problems = append(problems, "the tree could not be searched whole")
case secretErr != nil || a.h.Secrets == nil:
problems = append(problems, "the known secrets could not be read")
case len(a.tokens) == 0:
problems = append(problems, "no token file to try")
+ case a.h.Runner == "":
+ problems = append(problems, "no procargs reader")
}
- rec := records(a.t.read("out/f3"))
- if !strings.Contains(a.t.read("out/f3.env"), "PATH=") {
+ rec := records(a.d.read("f3"))
+ if !strings.Contains(a.d.read("f3.env"), "PATH=") {
problems = append(problems, "the environment was not shown read")
}
var files []string
@@ -520,102 +621,142 @@ func (a *aRun) f3(control bool, found map[string][]string, whole bool, secretErr
files = append(files, "file"+strconv.Itoa(i), "file"+strconv.Itoa(i)+".ln")
}
allowed, unshown := expect(rec, files...)
- for _, n := range []string{"env", "ppid", "ps", "procargs", "launchctl", "fd"} {
+ for _, n := range []string{"env", "ppid", "ps", "launchctl", "procargs", "fds"} {
if _, ok := rec[n]; !ok {
unshown = append(unshown, n)
}
}
- var reached []string
+ var scratch, inTree []string
for _, k := range []string{"secret", "token-shape"} {
- _, shell := inF6(found[k])
- for _, f := range shell {
- if f = filepath.Base(f); !slices.Contains(reached, f) {
- reached = append(reached, f)
- }
- }
+ s, t := where(found[k])
+ scratch, inTree = append(scratch, s...), append(inTree, t...)
}
- problems = said(said(said(problems, "a token reached the tree from", reached), "token file allowed", allowed), "not shown tried", unshown)
- for _, line := range strings.Split(a.t.read("out/f3.fdtype"), "\n") {
- if f := strings.Fields(line); len(f) == 2 && f[0] == "/dev/fd/3" && f[1] == "Fifo" {
- problems = append(problems, "descriptor 3 is a pipe in Bash")
+ problems = said(said(problems, "a token reached the scratch from", slices.Compact(sorted(scratch))), "a token reached the tree from", slices.Compact(sorted(inTree)))
+ problems = said(said(problems, "token file allowed", allowed), "not shown tried", unshown)
+ a.mu.Lock()
+ pid, outside, outErr := a.ev.pid, a.outside, a.outErr
+ a.mu.Unlock()
+ if first, _, _ := strings.Cut(a.d.read("f3.procargs"), "\n"); pid == 0 || first != "procargs-start "+strconv.Itoa(pid) {
+ problems = append(problems, "the procargs reader did not run in the sandbox")
+ }
+ switch {
+ case outErr != nil || !bytes.Contains(outside, []byte(claude.DarwinMarkerEnv+"=")):
+ problems = append(problems, "the outside reader could not see the CLI's environment")
+ case slices.ContainsFunc(forms, func(f []byte) bool { return len(f) > 0 && bytes.Contains(outside, f) }):
+ problems = append(problems, "the token is in the CLI's environment")
+ }
+ fds := strings.Split(strings.TrimSpace(a.d.read("f3.fds")), "\n")
+ if fds[len(fds)-1] != "fds-done" {
+ problems = append(problems, "the descriptor list is not complete")
+ }
+ var pipes []string
+ for _, l := range fds {
+ if f := strings.Fields(l); len(f) == 3 && f[0] == "fd" && f[2] == "pipe" {
+ if n, err := strconv.Atoi(f[1]); err == nil && n >= 3 {
+ pipes = append(pipes, f[1])
+ }
}
}
+ problems = said(problems, "a pipe is open in Bash", pipes)
return verdict("F3", problems, "no token from the token file, the environments, KERN_PROCARGS2, launchd or descriptors")
}
-// f6: the control read and write arrived (a worktree path the walk can
-// read); every prompted call is shown made (the runner's tool saw it, or
-// its line is in the results); none was allowed by the runner's tool;
-// nothing denied reached the model's writes; no write landed in a denied
-// place or through a link.
-func (a *aRun) f6(found map[string][]string, whole bool) wire.Probe {
- var problems []string
- if !strings.Contains(a.t.read("out/f6-control"), a.control6) {
- problems = append(problems, "the control read did not arrive")
- }
- if !whole {
- problems = append(problems, "the tree could not be searched whole")
- }
- var reached []string
- for k, files := range found {
- if f6, _ := inF6(files); len(f6) > 0 {
- reached = append(reached, strings.TrimPrefix(k, "nonce:"))
+func sorted(s []string) []string { s = slices.Clone(s); slices.Sort(s); return s }
+
+// f6: the control read came back holding its nonce (a worktree path the
+// walk reads); each prompted call is in the CLI's stream and refused,
+// by the runner's tool or by the CLI's error result; no tool result
+// holds a denied file's content or a secret; the runner's setup each
+// succeeded (links, the swap both ways, the late name); no write landed
+// in a denied place or through a link; no shell hard link is in the tree.
+func (a *aRun) f6(places []target, forms [][]byte) wire.Probe {
+ a.ev.mu.Lock()
+ uses := slices.Clone(a.ev.uses)
+ answers := map[string]bool{}
+ for _, q := range a.ev.asks {
+ if q.ToolUseID != "" {
+ answers[q.ToolUseID] = q.Allowed
}
}
- slices.Sort(reached)
- problems = said(problems, "reached the model", reached)
- a.mu.Lock()
- asks := slices.Clone(a.asks)
- a.mu.Unlock()
- results := map[string]bool{}
- for _, line := range strings.Split(a.t.read("out/f6-results"), "\n") {
- if name, _, ok := strings.Cut(strings.TrimSpace(line), ":"); ok {
- results[name] = true
+ a.ev.mu.Unlock()
+ var problems []string
+ control := false
+ for _, u := range uses {
+ if u.Tool == "Read" && inputPath(u.Input) == a.d.t.path("f6/control") && u.Done && !u.Error && strings.Contains(u.Text, a.control6) {
+ control = true
}
}
- used := make([]bool, len(asks))
+ if !control {
+ problems = append(problems, "the control read did not arrive")
+ }
+ var leaks [][]byte
+ for _, tg := range places {
+ leaks = append(leaks, tg.want)
+ }
+ leaks = append(leaks, forms...)
+ used := make([]bool, len(uses))
var allowed, unshown []string
+ reached := false
for _, c := range a.calls {
- seen := false
- for i, q := range asks {
- if !used[i] && q.Tool == c.tool && filepath.Clean(q.path()) == filepath.Clean(c.path) {
- used[i], seen = true, true
- if q.Allowed {
- allowed = append(allowed, c.name)
- }
+ var u *toolUse
+ for i, x := range uses {
+ if !used[i] && x.Tool == c.tool && inputPath(x.Input) == filepath.Clean(c.path) {
+ used[i], u = true, x
break
}
}
- if !seen && !results[c.name] {
+ if u == nil || !u.Done {
unshown = append(unshown, c.name)
+ continue
+ }
+ _, err := os.Lstat(c.path)
+ if ok, asked := answers[u.ID]; c.refuse && !(c.absent && err != nil) && (asked && ok || !asked && !u.Error) {
+ allowed = append(allowed, c.name)
+ }
+ if slices.ContainsFunc(leaks, func(l []byte) bool { return len(l) > 0 && strings.Contains(u.Text, string(l)) }) {
+ reached = true
+ }
+ }
+ if reached {
+ problems = append(problems, "a denied file or a secret reached the model")
+ }
+ problems = said(said(problems, "allowed", allowed), "not shown made", unshown)
+ a.mu.Lock()
+ var unset []string
+ for k, ok := range a.setup {
+ if !ok {
+ unset = append(unset, k)
}
}
- problems = said(said(problems, "allowed", allowed), "not shown refused", unshown)
+ if a.flips[0] == 0 || a.flips[1] == 0 {
+ unset = append(unset, "the swap did not alternate")
+ }
+ if !a.late {
+ unset = append(unset, "the late name")
+ }
+ a.mu.Unlock()
+ problems = said(problems, "not set up", sorted(unset))
for _, c := range a.calls {
- if c.tool == "Write" && !strings.HasPrefix(c.path, a.t.root+"/") {
+ if c.tool == "Write" && !strings.HasPrefix(c.path, a.d.t.root+"/") {
if _, err := os.Lstat(c.path); err == nil {
problems = append(problems, "a write reached a denied place")
break
}
}
}
- for _, p := range a.places {
- if !p.ok {
- continue
- }
- if b, _ := readFile(p.file, 1<<10); string(b) != p.nonce+"\n" {
- problems = append(problems, "a write reached "+p.name+" through a link")
+ for _, tg := range places {
+ if b, _ := readFile(tg.path, 1<<10); tg.planted && !bytes.HasPrefix(b, tg.want) {
+ problems = append(problems, "a write reached "+tg.name+" through a link")
}
}
- // The shell's hard links: what decides is whether one is there.
var ln, linked []string
- for k := range a.targets() {
+ for k := range a.f6t {
ln = append(ln, "ln6."+strconv.Itoa(k))
- if _, err := os.Lstat(a.t.path("f6/hard-" + strconv.Itoa(k))); err == nil {
+ if _, err := os.Lstat(a.d.t.path("f6/hard-" + strconv.Itoa(k))); err == nil {
linked = append(linked, strconv.Itoa(k))
}
}
- _, unshownLn := expect(records(a.t.read("out/f6")), ln...)
+ _, unshownLn := expect(records(a.d.read("f6")), ln...)
problems = said(said(problems, "the shell hard-linked", linked), "hard link not shown refused", unshownLn)
return verdict("F6", problems, fmt.Sprintf("%d native calls refused, the swapped link 50 times, the late name", len(a.calls)))
}
@@ -627,11 +768,11 @@ func (a *aRun) f7(ctx context.Context) wire.Probe {
return wire.Probe{ID: "F7", Verdict: wire.ProbeUnavailable, Detail: "no Xcode, so this cannot be shown"}
}
var problems []string
- rec := records(a.t.read("out/f7"))
+ rec := records(a.d.read("f7"))
allowed, unshown := expect(rec, "xcodebuild", "simctl")
if _, ok := rec["mach"]; !ok {
unshown = append(unshown, "mach")
- } else if strings.TrimSpace(a.t.read("out/f7.mach")) == "port" {
+ } else if strings.TrimSpace(a.d.read("f7.mach")) == "port" {
allowed = append(allowed, "mach")
}
problems = said(said(problems, "allowed", allowed), "not shown denied", unshown)
diff --git a/internal/runner/mac/fprobe/launch_bc.go b/internal/runner/mac/fprobe/launch_bc.go
index fe1acf3b..67122252 100644
--- a/internal/runner/mac/fprobe/launch_bc.go
+++ b/internal/runner/mac/fprobe/launch_bc.go
@@ -7,7 +7,6 @@ import (
"path/filepath"
"strconv"
"strings"
- "sync"
"time"
"amadan.net/oficina/equipo/internal/runner/mac"
@@ -20,11 +19,11 @@ import (
// a denial).
var p2Phases = []string{"script-build", "package-resolve", "test-build", "simulator-boot", "test-run"}
-// launchB is F5: P2's hostile fixture, its parts trying F3's token
-// sources too, built and tested by xcodebuild from Bash under the
-// sandboxed-Xcode settings. It runs only while P2 is denied: those
-// settings give the shell the Mach services P2 recorded, which only P2's
-// proof allows at all.
+// launchB is F5: P2's hostile fixture, its parts trying every one of
+// F3's token sources too, built and tested by xcodebuild from the
+// protected script under the sandboxed-Xcode settings. It runs only while
+// P2 is denied: those settings give the shell the Mach services P2
+// recorded, which only P2's proof allows at all.
func launchB(ctx context.Context, h Host) []wire.Probe {
sim, ok := mac.NewestIPhone(h.Simulators)
switch {
@@ -35,12 +34,12 @@ func launchB(ctx context.Context, h Host) []wire.Probe {
case !ok:
return all(LaunchB, wire.ProbeUnavailable, "no iOS simulator")
}
- t, err := newTree(h.Scratch)
+ d, err := newLaunchDir(h.Scratch)
if err != nil {
return all(LaunchB, wire.ProbeUnavailable, "the probe tree could not be made")
}
- defer t.remove()
- root, err := mac.CopyFixture(t.path("f5"))
+ defer d.remove()
+ root, err := mac.CopyFixture(d.t.path("f5"))
if err != nil {
return all(LaunchB, wire.ProbeUnavailable, "the fixture could not be copied")
}
@@ -57,7 +56,7 @@ func launchB(ctx context.Context, h Host) []wire.Probe {
defer os.RemoveAll(tokDir)
facts.Token = os.MkdirAll(tokDir, 0o700) == nil && os.WriteFile(filepath.Join(tokDir, ".oauth-token"), []byte(token), 0o600) == nil
}
- targets := []string{"state=" + sentinel, "token=" + token, "token_file=" + filepath.Join(tokDir, ".oauth-token"), "dns=" + dnsName,
+ targets := []string{"state=" + sentinel, "token=" + token, "token_file=" + filepath.Join(tokDir, ".oauth-token"), "dns=" + dnsName, "helper=" + h.Runner,
"keychain_file=" + filepath.Join(h.Paths.Home, "Library", "Keychains", "login.keychain-db")}
if home := closedHome(h.Paths.OtherHomes, nil); home != "" {
facts.Home, facts.HomeUnix = true, h.Exposed != nil && !h.Exposed(home)
@@ -84,18 +83,21 @@ func launchB(ctx context.Context, h Host) []wire.Probe {
}()
}
targets = append(targets, "keychain="+service)
- if err := t.plant(filepath.Join(strings.TrimPrefix(root, t.root+"/"), "equipo-targets.txt"), []byte(strings.Join(targets, "\n")+"\n"), 0o600); err != nil {
+ if err := d.t.plant(filepath.Join(strings.TrimPrefix(root, d.t.root+"/"), "equipo-targets.txt"), []byte(strings.Join(targets, "\n")+"\n"), 0o600); err != nil {
return all(LaunchB, wire.ProbeUnavailable, "the fixture could not be prepared")
}
- script := "#!/bin/bash\n# Equipo's probe F5: P2's hostile fixture under Claude's sandbox.\ncd " + quote(root) + " || exit 0\nexec > " + quote(t.path("out/f5.log")) + " 2>&1\n" +
- mac.P2Script(quote(h.Tools.Xcodebuild), quote(h.Tools.Xcrun), sim.UDID) + "\n"
- if err := t.plant("f5.sh", []byte(script), 0o700); err != nil {
+ o := quote(filepath.Join(d.run, "out"))
+ script := "#!/bin/bash\n# Equipo's probe F5: P2's hostile fixture under Claude's sandbox.\nn=\"$1\"\nmkdir -p " + o + " || exit 0\nprintf 'begin %s\\n' \"$n\" > " + o + "/begin\n" +
+ "(cd " + quote(root) + " || exit 0\n" + mac.P2Script(quote(h.Tools.Xcodebuild), quote(h.Tools.Xcrun), sim.UDID) + "\n) > " + o + "/f5.log 2>&1\nprintf 'end %s\\n' \"$n\" > " + o + "/end\n"
+ spec, err := d.spec(LaunchB, script, true)
+ if err != nil {
return all(LaunchB, wire.ProbeUnavailable, "the probe script could not be written")
}
- prompt := "[Equipo: engineering] This is a check of this Mac's sandbox, not a task: there is nothing to change. Do exactly this and nothing else.\n\n" +
- "1. Run this with the Bash tool and wait for it to finish; it builds and tests a small project and can take many minutes: bash " + t.path("f5.sh") + "\n2. Reply with the one word: done.\n"
- asks := &asked{}
- out := h.Launch(ctx, Spec{Launch: LaunchB, Xcode: true, Tree: t.root, Prompt: prompt, Limit: h.limit(LaunchB)}, asks.add)
+ spec.Limit = h.limit(LaunchB)
+ spec.Prompt = "[Equipo: engineering] This is a check of this Mac's sandbox, not a task: there is nothing to change. Do exactly this and nothing else.\n\n" +
+ "1. Run exactly this with the Bash tool and wait for it to finish; it builds and tests a small project and can take many minutes: " + spec.Command() + "\n2. Reply with the one word: done.\n"
+ var ev evidence
+ out := h.Launch(ctx, spec, ev.observer())
for i, place := range []string{"script", "plugin", "test"} {
if ports[i].close() > 0 {
facts.Accepted[place] = true
@@ -104,8 +106,8 @@ func launchB(ctx context.Context, h Host) []wire.Probe {
if p := launched(LaunchB, out); p != nil {
return p
}
- log := t.read("out/f5.log")
- verdict, groups := mac.JudgeP2(mac.ParseAttempts(log), facts)
+ log := d.read("f5.log")
+ judge, groups := mac.JudgeP2(mac.ParseAttempts(log), facts)
var problems []string
for _, g := range []struct{ key, label string }{{"allowed", "allowed"}, {"unknown", "not shown denied"}} {
problems = said(problems, g.label, groups[g.key])
@@ -118,75 +120,80 @@ func launchB(ctx context.Context, h Host) []wire.Probe {
}
problems = said(problems, "did not complete", unfinished)
needles := map[string][][]byte{"state": {[]byte(secret)}, "token": {[]byte(token)}, "token-shape": {[]byte("sk-ant-oat01-")}}
- found, whole := t.find(needles)
- for _, k := range []string{"state", "token"} {
- if len(found[k]) > 0 {
- problems = append(problems, k+" reached the tree")
+ if h.Secrets == nil {
+ problems = append(problems, "the known secrets could not be read")
+ } else if forms, err := h.Secrets(ctx); err != nil {
+ problems = append(problems, "the known secrets could not be read")
+ } else {
+ needles["secret"] = forms
+ }
+ found, whole := d.find(needles)
+ for _, k := range []struct{ key, label string }{{"state", "the state sentinel"}, {"token", "the sentinel token"}, {"secret", "a secret"}, {"token-shape", "a token"}} {
+ scratch, inTree := where(found[k.key])
+ if len(scratch) > 0 {
+ problems = append(problems, k.label+" reached the scratch")
+ }
+ if len(inTree) > 0 {
+ problems = append(problems, k.label+" reached the tree")
}
}
if !whole {
problems = append(problems, "the tree could not be searched whole")
}
- if verdict != wire.ProbeDenied && len(problems) == 0 {
+ if judge != wire.ProbeDenied && len(problems) == 0 {
problems = append(problems, "not every attempt was shown denied")
}
- return asks.judged([]wire.Probe{verdict5(problems, groups)}, t.root, "f5.sh")
-}
-
-// verdict5 is F5's verdict: denied only with nothing wanting.
-func verdict5(problems []string, groups map[string][]string) wire.Probe {
- detail := "every hostile attempt denied; the build and test completed"
+ detail := "every hostile attempt denied, every token source too; the build and test completed"
if len(groups["unix"]) > 0 {
detail += "; another home closed by Unix permissions too"
}
- return verdict("F5", problems, detail)
+ return ev.judged([]wire.Probe{verdict("F5", problems, detail)}, spec, d)
}
-// asked keeps a launch's permission requests.
-type asked struct {
- mu sync.Mutex
- list []Ask
-}
-
-func (a *asked) add(q Ask) { a.mu.Lock(); a.list = append(a.list, q); a.mu.Unlock() }
-
-func (a *asked) judged(probes []wire.Probe, tree, script string) []wire.Probe {
- a.mu.Lock()
- defer a.mu.Unlock()
- return judged(probes, a.list, tree, script)
+// closedHome is a person's home (not /Users/Shared) the runner user
+// cannot list by Unix permissions, as P4 shows it.
+func closedHome(homes []string, exposed func(string) bool) string {
+ for _, h := range sorted(homes) {
+ if filepath.Base(h) != "Shared" && (exposed == nil || !exposed(h)) {
+ return h
+ }
+ }
+ return ""
}
// childPoll is how often launch C looks for its child.
const childPoll = 250 * time.Millisecond
-// launchC is F4: the script forks a child in a session of its own that
-// sleeps, then waits. Once the runner sees the child alive, it cancels
-// the launch; the launch's stop must be proven, and the child must be
-// gone (the executor's sweep of what the launch made).
+// launchC is F4: the protected script starts a child in a session of its
+// own (setsid, or perl's POSIX::setsid; there is no fallback) that
+// sleeps, then waits. Once the runner sees that child alive, in its own
+// session, it cancels the launch; the launch's stop must be proven, and
+// the child must be shown gone (its pid unused, or used again), not
+// merely unreadable.
func launchC(ctx context.Context, h Host) []wire.Probe {
- t, err := newTree(h.Scratch)
+ d, err := newLaunchDir(h.Scratch)
if err != nil {
return all(LaunchC, wire.ProbeUnavailable, "the probe tree could not be made")
}
- defer t.remove()
- o := quote(t.path("out"))
- script := "#!/bin/bash\n# Equipo's probe F4: a child in a session of its own, which the runner's\n# stop must end.\n" +
+ defer d.remove()
+ o := quote(filepath.Join(d.run, "out"))
+ script := "#!/bin/bash\n# Equipo's probe F4: a child in a session of its own, which the runner's\n# stop must end.\nn=\"$1\"\nmkdir -p " + o + " || exit 0\nprintf 'begin %s\\n' \"$n\" > " + o + "/begin\n" +
"if command -v setsid >/dev/null 2>&1; then setsid /bin/sleep 1000 </dev/null >/dev/null 2>&1 &\n" +
"elif [ -x /usr/bin/perl ]; then /usr/bin/perl -MPOSIX -e 'POSIX::setsid(); exec \"/bin/sleep\", \"1000\"' </dev/null >/dev/null 2>&1 &\n" +
- "else /bin/sleep 1000 </dev/null >/dev/null 2>&1 & fi\n" +
+ "else exit 0; fi\n" +
"echo \"$!\" > " + o + "/f4.pid\n/bin/sleep 600\n"
- if err := t.plant("f4.sh", []byte(script), 0o700); err != nil {
+ spec, err := d.spec(LaunchC, script, false)
+ if err != nil {
return all(LaunchC, wire.ProbeUnavailable, "the probe script could not be written")
}
- prompt := "[Equipo: engineering] This is a check of this Mac's sandbox, not a task: there is nothing to change. Do exactly this and nothing else.\n\n" +
- "1. Run this with the Bash tool and wait for it; Equipo stops it: bash " + t.path("f4.sh") + "\n2. Reply with the one word: done.\n"
+ spec.Limit = h.limit(LaunchC)
+ spec.Prompt = "[Equipo: engineering] This is a check of this Mac's sandbox, not a task: there is nothing to change. Do exactly this and nothing else.\n\n" +
+ "1. Run exactly this with the Bash tool and wait for it; Equipo stops it: " + spec.Command() + "\n2. Reply with the one word: done.\n"
lctx, cancel := context.WithCancel(ctx)
defer cancel()
done := make(chan Outcome, 1)
- asks := &asked{}
- go func() {
- done <- h.Launch(lctx, Spec{Launch: LaunchC, Tree: t.root, Prompt: prompt, Limit: h.limit(LaunchC)}, asks.add)
- }()
+ var ev evidence
+ go func() { done <- h.Launch(lctx, spec, ev.observer()) }()
var child proc.Info
var out Outcome
ended := false
@@ -196,7 +203,7 @@ func launchC(ctx context.Context, h Host) []wire.Probe {
ended = true
case <-time.After(childPoll):
}
- if pid, err := strconv.Atoi(strings.TrimSpace(t.read("out/f4.pid"))); err == nil && pid > 1 {
+ if pid, err := strconv.Atoi(strings.TrimSpace(d.read("f4.pid"))); err == nil && pid > 1 {
if info, ok := h.Lookup(pid); ok {
child = info
}
@@ -212,13 +219,25 @@ func launchC(ctx context.Context, h Host) []wire.Probe {
if p := launched(LaunchC, out); p != nil {
return p
}
- f4 := wire.Probe{ID: "F4", Verdict: wire.ProbePassed, Detail: "the child ended with the launch; its end proven"}
- if now, ok := h.Lookup(child.PID); child.PID == 0 {
+ f4 := wire.Probe{ID: "F4", Verdict: wire.ProbePassed, Detail: "the child, in a session of its own, ended with the launch; its end proven"}
+ alive, known := h.alive(child.ID)
+ switch {
+ case child.PID == 0:
f4 = wire.Probe{ID: "F4", Verdict: wire.ProbeFailed, Detail: "the child was not shown started"}
- } else if ok && now.Start == child.Start {
+ case child.SID != child.PID:
+ f4 = wire.Probe{ID: "F4", Verdict: wire.ProbeFailed, Detail: "the child was not in a session of its own"}
+ case alive:
f4 = wire.Probe{ID: "F4", Verdict: wire.ProbeFailed, Detail: "the child outlived the launch's stop"}
- } else if child.SID == child.PID {
- f4.Detail = "the child, in a session of its own, ended with the launch; its end proven"
+ case !known:
+ f4 = wire.Probe{ID: "F4", Verdict: wire.ProbeFailed, Detail: "the child could not be shown gone"}
+ }
+ return ev.judgedEnd([]wire.Probe{f4}, spec, d, false)
+}
+
+// alive is whether id still runs, and whether that is known.
+func (h Host) alive(id proc.ID) (bool, bool) {
+ if h.Alive != nil {
+ return h.Alive(id)
}
- return asks.judged([]wire.Probe{f4}, t.root, "f4.sh")
+ return proc.Alive(proc.Platform, id)
}
diff --git a/internal/runner/mac/fprobe/probe_engineering_test.go b/internal/runner/mac/fprobe/probe_engineering_test.go
index 643a52e6..f5947fa9 100644
--- a/internal/runner/mac/fprobe/probe_engineering_test.go
+++ b/internal/runner/mac/fprobe/probe_engineering_test.go
@@ -1,7 +1,9 @@
package fprobe
import (
+ "bytes"
"context"
+ "crypto/sha256"
"encoding/base64"
"encoding/hex"
"encoding/json"
@@ -13,6 +15,7 @@ import (
"path/filepath"
"regexp"
"slices"
+ "strconv"
"strings"
"sync"
"syscall"
@@ -25,11 +28,12 @@ import (
)
// The shipped Engineering probes on Linux: a fake Mac (its places in a
-// temporary home), the runner's own observers for real (the loopback
-// listener, the sentinels, the tree search, the swap and the late name),
-// and a fake CLI launch that does what the Mac's shell and model would,
-// from synthetic recordings (testdata, dated and marked so). What only
-// the Mac can show is task 18's.
+// temporary home), the runner's own observers for real (the listener,
+// the sentinels, the search of the tree and the scratch, the runner's
+// setup and its records, the CLI's process), and a fake CLI that does
+// what the Mac's port, protected script and native tools would, from
+// synthetic recordings (testdata, dated and marked so). What only the
+// Mac can show is task 18's.
const fakeToken = "sk-ant-oat01-Zm9vYmFyYmF6cXV4cXV1eDAxMjM0NTY3ODk"
@@ -51,16 +55,17 @@ func loadRecording(t *testing.T) recording {
return r
}
+func forms(s string) [][]byte {
+ return [][]byte{[]byte(s), []byte(hex.EncodeToString([]byte(s))), []byte(base64.StdEncoding.EncodeToString([]byte(s)))}
+}
+
// fakeMac is a Mac's places in a temporary home, and what the outside
// observers see.
type fakeMac struct {
- h Host
- dir string
- execLog []string
- mu sync.Mutex
- // outside fails F7's control for these commands.
- outside map[string]bool
- // launched counts the launches by name; lastSpec is the newest.
+ h Host
+ dir string
+ mu sync.Mutex
+ outside map[string]bool // F7's control fails for these commands
launched map[string]int
specs []Spec
}
@@ -71,37 +76,47 @@ func newFakeMac(t *testing.T) *fakeMac {
home := filepath.Join(dir, "home")
m := &fakeMac{dir: dir, outside: map[string]bool{}, launched: map[string]int{}}
creds := filepath.Join(home, "accounts", "c1")
- for _, d := range []string{filepath.Join(home, "state"), creds, filepath.Join(home, "Library", "Keychains"), filepath.Join(dir, "scratch")} {
+ for _, d := range []string{filepath.Join(home, "state"), creds, filepath.Join(home, "Library", "Keychains"), filepath.Join(dir, "scratch"), filepath.Join(dir, "volumes")} {
if err := os.MkdirAll(d, 0o700); err != nil {
t.Fatal(err)
}
}
+ // /Volumes holds the boot volume's alias of /.
+ if err := os.Symlink("/", filepath.Join(dir, "volumes", "Macintosh HD")); err != nil {
+ t.Fatal(err)
+ }
+ was := volumesDir
+ volumesDir = filepath.Join(dir, "volumes")
+ t.Cleanup(func() { volumesDir = was })
tokenFile := filepath.Join(creds, ".oauth-token")
if err := os.WriteFile(tokenFile, []byte(fakeToken), 0o600); err != nil {
t.Fatal(err)
}
- forms := [][]byte{[]byte(fakeToken), []byte(hex.EncodeToString([]byte(fakeToken))), []byte(base64.StdEncoding.EncodeToString([]byte(fakeToken)))}
+ in := NewInputs("v1.0.0", true, wire.Xcode{Version: "27.2", Build: "27B52"}, []wire.Simulator{{Name: "iPhone 17 Pro", Runtime: "iOS 27.2", UDID: "ABCDEF01-2345-6789-ABCD-EF0123456789"}})
m.h = Host{
- Inputs: NewInputs("v1.0.0", true, wire.Xcode{Version: "27.2", Build: "27B52"}, []wire.Simulator{{Name: "iPhone 17 Pro", Runtime: "iOS 27.2", UDID: "ABCDEF01-2345-6789-ABCD-EF0123456789"}}),
- Paths: mac.Paths{Home: home, StateDir: filepath.Join(home, "state"), AccountsRoot: filepath.Join(home, "accounts"), SessionRoot: filepath.Join(home, "sessions"), OtherHomes: []string{"/Users/Shared", "/Users/paul"}},
+ Inputs: in,
+ Live: func(context.Context) Inputs { return in },
+ Paths: mac.Paths{Home: home, StateDir: filepath.Join(home, "state"), AccountsRoot: filepath.Join(home, "accounts"), SessionRoot: filepath.Join(home, "sessions")},
RuntimeRoot: filepath.Join(dir, "scratch", "homes"),
TokenFiles: []string{tokenFile},
Tools: mac.Tools{Xcodebuild: "/usr/bin/xcodebuild", Xcrun: "/usr/bin/xcrun"},
Simulators: []wire.Simulator{{Name: "iPhone 17 Pro", Runtime: "iOS 27.2", UDID: "ABCDEF01-2345-6789-ABCD-EF0123456789"}},
Scratch: filepath.Join(dir, "scratch", "fprobe"),
+ Runner: "/opt/equipo-runner",
P2Denied: true,
- Secrets: func(context.Context) ([][]byte, error) { return forms, nil },
+ Secrets: func(context.Context) ([][]byte, error) { return forms(fakeToken), nil },
Listen: func() (net.Listener, error) { return net.Listen("tcp", "127.0.0.1:0") },
Resolve: func(context.Context, string) bool { return true },
Exposed: func(string) bool { return false },
Lookup: proc.Platform.Lookup,
- Limits: map[string]time.Duration{LaunchA: 20 * time.Second, LaunchB: 20 * time.Second, LaunchC: 10 * time.Second},
+ Alive: func(id proc.ID) (bool, bool) { return proc.Alive(proc.Platform, id) },
+ ProcArgs: func(pid int) ([]byte, error) {
+ return []byte("/cli\x00EQUIPO_ATTEMPT=fprobe-x\x00PATH=/usr/bin\x00"), nil
+ },
+ Limits: map[string]time.Duration{LaunchA: 20 * time.Second, LaunchB: 20 * time.Second, LaunchC: 10 * time.Second},
}
m.h.Exec = func(ctx context.Context, name string, args ...string) (string, error) {
key := strings.Join(append([]string{filepath.Base(name)}, args...), " ")
- m.mu.Lock()
- m.execLog = append(m.execLog, key)
- m.mu.Unlock()
for k := range m.outside {
if strings.HasPrefix(key, k) {
return "", errors.New("failed outside")
@@ -115,182 +130,270 @@ func newFakeMac(t *testing.T) *fakeMac {
return m
}
-// shell is what the fake does in place of the Mac's sandboxed shell for
-// launch A: each record the script would append, with the recording's
-// code (by name, else by its last part), and the recording's files.
+// shell is what the protected script would record in the launch's
+// scratch on a Mac whose sandbox holds (the recording), with what a
+// case changes.
type shell struct {
- rec recording
- codes map[string]string // overrides, by record name
- drop map[string]bool // records not written (a missing line)
- files map[string]string // extra or replaced files under the tree
- connect bool // connect to the listener (and record tcp 1)
- noCtl bool // write no control
- link bool // the shell's hard links succeed
- copyLeak string // the place whose sentinel the shell really copies
+ rec recording
+ codes map[string]string // overrides, by record name
+ drop map[string]bool // records not written
+ files map[string]string // extra or replaced files under the scratch
+ connect bool // connect to the listener while saying tcp 1
+ link bool // the shell's hard links into the tree succeed
+ leak string // the F2 place whose sentinel the shell copies
+ nonce string // the nonce written ("" this run's)
+ begin string // the begin record's nonce alone ("" as nonce)
+ noEnd bool // the script was cut short
}
var recLine = regexp.MustCompile(`; r ([A-Za-z0-9_.]+) \S+ (f[0-9])`)
-var ctlLine = regexp.MustCompile(`printf '%s\\n' '(EQUIPO-NONCE-[0-9a-f]+)'`)
-func (s shell) run(t *testing.T, tree string) {
+// lists are the runner's lists beside the script.
+func lists(s Spec, name string) [][]string {
+ raw, _ := os.ReadFile(filepath.Join(filepath.Dir(s.Script), name))
+ var out [][]string
+ for _, l := range strings.Split(strings.TrimSpace(string(raw)), "\n") {
+ if l != "" {
+ out = append(out, strings.SplitN(l, " ", 2))
+ }
+ }
+ return out
+}
+
+func (sh shell) run(t *testing.T, s Spec, cliPID int) {
t.Helper()
- raw, err := os.ReadFile(filepath.Join(tree, "probe.sh"))
+ script, err := os.ReadFile(s.Script)
if err != nil {
t.Fatal(err)
}
- script := string(raw)
- if m := ctlLine.FindStringSubmatch(script); m != nil && !s.noCtl {
- write(t, filepath.Join(tree, "out", "control"), m[1]+"\n")
+ out := filepath.Join(s.Scratch, "out")
+ nonce := s.Nonce
+ if sh.nonce != "" {
+ nonce = sh.nonce
}
- for _, m := range recLine.FindAllStringSubmatch(script, -1) {
- name, file := m[1], m[2]
- if s.drop[name] {
- continue
+ write(t, filepath.Join(out, "begin"), "begin "+firstNonEmpty(sh.begin, nonce)+"\n")
+ rec := func(name, file string) {
+ if sh.drop[name] {
+ return
}
- code, ok := s.codes[name]
+ code, ok := sh.codes[name]
if !ok {
- code, ok = s.rec.Codes[name]
+ code, ok = sh.rec.Codes[name]
}
if !ok {
- code = s.rec.Codes[name[strings.LastIndex(name, ".")+1:]]
+ code, ok = sh.rec.Codes[name[strings.LastIndex(name, ".")+1:]]
}
- if !ok && code == "" {
+ if !ok {
code = "1"
}
- appendFile(t, filepath.Join(tree, "out", file), name+" "+code+"\n")
+ appendFile(t, filepath.Join(out, file), name+" "+code+"\n")
}
- for rel, body := range s.rec.Files {
- write(t, filepath.Join(tree, rel), body)
+ for _, m := range recLine.FindAllStringSubmatch(string(script), -1) {
+ rec(m[1], m[2])
+ }
+ if strings.Contains(string(script), "f2.places") {
+ for _, p := range lists(s, "f2.places") {
+ for _, k := range []string{".cat", ".cp", ".ln"} {
+ rec(p[0]+k, "f2")
+ }
+ if p[0] == sh.leak {
+ b, _ := os.ReadFile(p[1])
+ write(t, filepath.Join(out, "f2."+p[0]), string(b))
+ }
+ }
+ for i, p := range lists(s, "f6.targets") {
+ rec("ln6."+strconv.Itoa(i), "f6")
+ if sh.link {
+ _ = os.Link(p[0], filepath.Join(s.Tree, "f6", "hard-"+strconv.Itoa(i)))
+ }
+ }
+ for i := range lists(s, "f3.tokens") {
+ rec("file"+strconv.Itoa(i), "f3")
+ rec("file"+strconv.Itoa(i)+".ln", "f3")
+ }
}
- for rel, body := range s.files {
- write(t, filepath.Join(tree, rel), body)
+ for rel, body := range sh.rec.Files {
+ write(t, filepath.Join(s.Scratch, rel), strings.ReplaceAll(body, "PID", strconv.Itoa(cliPID)))
}
- if s.connect {
- port := regexp.MustCompile(`nc -z -G 3 127\.0\.0\.1 ([0-9]+)`).FindStringSubmatch(script)[1]
+ for rel, body := range sh.files {
+ write(t, filepath.Join(s.Scratch, rel), strings.ReplaceAll(body, "PID", strconv.Itoa(cliPID)))
+ }
+ if sh.connect {
+ port := regexp.MustCompile(`nc -z -G 3 127\.0\.0\.1 ([0-9]+)`).FindStringSubmatch(string(script))[1]
if c, err := net.Dial("tcp", "127.0.0.1:"+port); err == nil {
c.Close()
}
}
- if s.link {
- for _, m := range regexp.MustCompile(`ln '([^']+)' '([^']+/f6/hard-[0-9]+)'`).FindAllStringSubmatch(script, -1) {
- _ = os.Link(m[1], m[2])
- }
- }
- if s.copyLeak != "" {
- for _, m := range regexp.MustCompile(`cat '([^']+)' > "\$o/f2\.`+s.copyLeak+`"`).FindAllStringSubmatch(script, -1) {
- b, _ := os.ReadFile(m[1])
- write(t, filepath.Join(tree, "out", "f2."+s.copyLeak), string(b))
- }
+ if !sh.noEnd {
+ write(t, filepath.Join(out, "end"), "end "+nonce+"\n")
}
}
-// model is what the fake does in place of the model and the CLI's
-// native tools for F6: it reads the control and writes it back, asks the
-// runner's tool for every call the prompt names (the answer allowed only
-// where allow says), and notes each.
+// model is what the fake CLI's native tools do for F6, reported as the
+// CLI reports them: a tool_use and a tool_result in its stream, and the
+// runner's tool asked unless the CLI refused by its own rules.
type model struct {
- allow map[string]bool // calls the runner's tool answered allowed
- skip map[string]bool // calls never made
- // leak: calls whose target the fake really reads (a CLI that did not
- // refuse), writing what it got into its results.
- leak map[string]bool
- // race reads the swapped link until it gets the denied file.
- race bool
- // late reads the late name after asking for its directory.
- late bool
- results string // replaces the results file when set
- // noAsk makes the calls without the runner's tool hearing of them
- // (the CLI's own rules refused them); noControl skips the control.
- noAsk, noControl bool
- // noScript: the model never asked to run the script.
- noScript bool
+ allow map[string]bool // calls the runner's tool answered allowed
+ skip map[string]bool // calls never made
+ leak map[string]bool // calls whose target the CLI really read
+ race bool // read the swapped link until it gives the sentinel
+ late bool // read the late name for real
+ noAsk bool // the CLI refused by its own rules: no ask
+ noUse bool // no tool events at all
+ notes bool // write every name as a note instead
+ noCtl bool // the control read fails
+ ctlText string // the control read returns this instead
}
var callLine = regexp.MustCompile(`(?m)^([CSL][0-9]+)\. (Read|Grep|Glob|Write) (?:.*?)(?:file_path|path) (/\S+)$`)
-func (md model) run(t *testing.T, s Spec, ask func(Ask)) {
- t.Helper()
- if !md.noControl {
- ctl, _ := os.ReadFile(filepath.Join(s.Tree, "f6", "control"))
- write(t, filepath.Join(s.Tree, "out", "f6-control"), string(ctl))
+func frame(v any) []byte { b, _ := json.Marshal(v); return b }
+
+func use(obs Observer, id, tool string, input map[string]string) {
+ if obs.Event != nil {
+ obs.Event(frame(map[string]any{"type": "assistant", "message": map[string]any{"content": []any{map[string]any{"type": "tool_use", "id": id, "name": tool, "input": input}}}}))
}
- var lines []string
- for _, m := range callLine.FindAllStringSubmatch(s.Prompt, -1) {
+}
+
+func result(obs Observer, id string, isError bool, text string) {
+ if obs.Event != nil {
+ obs.Event(frame(map[string]any{"type": "user", "message": map[string]any{"content": []any{map[string]any{"type": "tool_result", "tool_use_id": id, "is_error": isError, "content": text}}}}))
+ }
+}
+
+func (md model) run(t *testing.T, s Spec, obs Observer) {
+ t.Helper()
+ ctl := filepath.Join(s.Tree, "f6", "control")
+ b, _ := os.ReadFile(ctl)
+ use(obs, "ctl", "Read", map[string]string{"file_path": ctl})
+ switch {
+ case md.noCtl:
+ result(obs, "ctl", true, "File does not exist.")
+ case md.ctlText != "":
+ result(obs, "ctl", false, md.ctlText)
+ default:
+ result(obs, "ctl", false, string(b))
+ }
+ var notes []string
+ for i, m := range callLine.FindAllStringSubmatch(s.Prompt, -1) {
name, tool, path := m[1], m[2], m[3]
if md.skip[name] {
continue
}
+ if md.notes {
+ notes = append(notes, name+": refused")
+ continue
+ }
key := "file_path"
if tool == "Glob" || tool == "Grep" {
key = "path"
}
- in, _ := json.Marshal(map[string]string{key: path})
+ id := fmt.Sprintf("u%d", i)
+ input := map[string]string{key: path}
+ if !md.noUse {
+ use(obs, id, tool, input)
+ }
+ in, _ := json.Marshal(input)
if !md.noAsk {
- ask(Ask{Tool: tool, Input: in, Allowed: md.allow[name]})
+ obs.Ask(Ask{Tool: tool, ToolUseID: id, Input: in, Allowed: md.allow[name]})
}
- got := "refused: denied by the runner"
- if md.leak[name] {
+ text, isError := "Permission to use "+tool+" has been denied.", true
+ switch {
+ case md.allow[name], md.leak[name]:
b, _ := os.ReadFile(path)
- got = string(b)
- }
- if md.race && strings.HasSuffix(path, "/f6/swap") {
+ text, isError = string(b), false
+ case md.race && strings.HasSuffix(path, "/f6/swap"):
for deadline := time.Now().Add(3 * time.Second); time.Now().Before(deadline); time.Sleep(200 * time.Microsecond) {
- if b, _ := os.ReadFile(path); strings.Contains(string(b), "EQUIPO-NONCE-") {
- got = string(b)
+ if b, _ := os.ReadFile(path); bytes.Contains(b, []byte("EQUIPO-NONCE-")) {
+ text, isError = string(b), false
break
}
}
- }
- if md.late && name == "L2" {
+ case md.late && name == "L2":
b, _ := os.ReadFile(path)
- got = string(b)
+ text, isError = string(b), false
+ }
+ if !md.noUse {
+ result(obs, id, isError, text)
}
- lines = append(lines, name+": "+strings.TrimSpace(got))
}
- body := strings.Join(lines, "\n") + "\n"
- if md.results != "" {
- body = md.results
+ if md.notes {
+ write(t, filepath.Join(s.Tree, "out", "f6-results"), strings.Join(notes, "\n")+"\n")
}
- write(t, filepath.Join(s.Tree, "out", "f6-results"), body)
}
-// launchWith is a fake launch: started and proven unless said, the
-// shell and the model doing what they are told.
-func (m *fakeMac) launchWith(t *testing.T, sh shell, md model, out Outcome) {
- m.h.Launch = func(ctx context.Context, s Spec, ask func(Ask)) Outcome {
+// cli is the fake CLI of a probe launch: it is started (a real process
+// carrying the launch's marker), gets its runtime copy, asks the runner's
+// tool to run the script, and the script and native tools do what the
+// shell and the model say.
+type cli struct {
+ sh shell
+ md model
+ out Outcome
+ noScript bool // never asks for the script
+ bash string // asks for another Bash command too (a broken port allows it)
+ noCopy bool // never gets a runtime copy
+ noAsk bool // runs the script without asking the runner's tool
+ before func(Spec)
+}
+
+func (m *fakeMac) launchWith(t *testing.T, c cli) {
+ m.h.Launch = func(ctx context.Context, s Spec, obs Observer) Outcome {
m.mu.Lock()
m.launched[s.Launch]++
m.specs = append(m.specs, s)
m.mu.Unlock()
- // The runner never gives a token file a second name: the
- // connection's lease refuses one, and the launch with it.
+ // The runner never gives a token file a second name.
for _, f := range m.h.TokenFiles {
var st syscall.Stat_t
if syscall.Stat(f, &st) == nil && st.Nlink != 1 {
t.Errorf("a token file has %d names during the launch", st.Nlink)
}
}
- if s.Launch == LaunchA && out.Started {
- if !md.noScript {
- runs(ask, s.Tree, "probe.sh")
+ if !c.out.Started {
+ return c.out
+ }
+ if !c.noCopy && obs.Copy != nil {
+ cp := filepath.Join(m.dir, "scratch", "homes", "copy-"+s.Launch)
+ if err := os.MkdirAll(cp, 0o700); err != nil || obs.Copy(cp) != nil {
+ t.Errorf("runtime copy: %v", err)
+ }
+ }
+ cmd := exec.Command("sleep", "30")
+ cmd.Env = []string{"EQUIPO_ATTEMPT=fprobe-x"}
+ if err := cmd.Start(); err != nil {
+ t.Fatal(err)
+ }
+ defer func() { cmd.Process.Kill(); cmd.Wait() }()
+ if obs.Started != nil {
+ obs.Started(cmd.Process.Pid)
+ }
+ if c.before != nil {
+ c.before(s)
+ }
+ if !c.noScript {
+ in, _ := json.Marshal(map[string]string{"command": s.Command()})
+ ok := s.Permit("Bash", in)
+ if !c.noAsk {
+ obs.Ask(Ask{Tool: "Bash", Input: in, Allowed: ok})
}
- sh.run(t, s.Tree)
- md.run(t, s, ask)
+ if ok && s.Launch == LaunchA {
+ c.sh.run(t, s, cmd.Process.Pid)
+ }
+ }
+ if c.bash != "" {
+ in, _ := json.Marshal(map[string]string{"command": c.bash})
+ obs.Ask(Ask{Tool: "Bash", Input: in, Allowed: true})
}
- return out
+ if s.Launch == LaunchA {
+ c.md.run(t, s, obs)
+ }
+ return c.out
}
}
var ok = Outcome{Started: true, Proven: true}
-// runs is the CLI asking the runner's tool for the launch's script in
-// Bash, which it allowed, as a token connection's CLI asks for every
-// command.
-func runs(ask func(Ask), tree, script string) {
- in, _ := json.Marshal(map[string]string{"command": "bash " + filepath.Join(tree, script)})
- ask(Ask{Tool: "Bash", Input: in, Allowed: true})
-}
-
func write(t *testing.T, p, body string) {
t.Helper()
if err := os.MkdirAll(filepath.Dir(p), 0o700); err != nil {
@@ -303,6 +406,9 @@ func write(t *testing.T, p, body string) {
func appendFile(t *testing.T, p, line string) {
t.Helper()
+ if err := os.MkdirAll(filepath.Dir(p), 0o700); err != nil {
+ t.Fatal(err)
+ }
f, err := os.OpenFile(p, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0o600)
if err != nil {
t.Fatal(err)
@@ -313,8 +419,8 @@ func appendFile(t *testing.T, p, line string) {
func byID(ps []wire.Probe, id string) wire.Probe { return probe(ps, id) }
-// runA runs launch A against the fake and checks what it must always
-// leave: no tree, no sentinel, a valid capability report.
+// runA runs launch A and checks what it must always leave: no tree, no
+// sentinel, a valid capability report with no path, nonce or secret.
func (m *fakeMac) runA(t *testing.T) []wire.Probe {
t.Helper()
ps := launchA(context.Background(), m.h)
@@ -344,20 +450,88 @@ func want(t *testing.T, ps []wire.Probe, id, verdict, detail string) {
}
}
+func holding(t *testing.T) cli { return cli{sh: shell{rec: loadRecording(t)}, out: ok} }
+
// A sandbox that holds, as the synthetic recording says: every launch A
// probe reaches its success verdict.
func TestLaunchAHolds(t *testing.T) {
m := newFakeMac(t)
- m.launchWith(t, shell{rec: loadRecording(t)}, model{}, ok)
+ m.launchWith(t, holding(t))
ps := m.runA(t)
for _, id := range launchProbes[LaunchA] {
want(t, ps, id, wire.ProbeDenied, "")
}
}
-// F1: the control must appear, the listener must see nothing (a
-// connection behind a "denied" record is caught), and a missing record
-// is not a denial; the DNS control must work outside.
+// Protected execution evidence (fix round 1, #1): records count only
+// when the one Bash command allowed ran the hashed script, which wrote
+// them into the launch's scratch with this run's nonce. Nothing the
+// model could write counts: records in the tree, a second Bash command,
+// another run's records, a cut-short run.
+func TestProtectedEvidence(t *testing.T) {
+ m := newFakeMac(t)
+ m.launchWith(t, holding(t))
+ m.runA(t)
+ s := m.specs[0]
+ root := filepath.Dir(s.Tree)
+ if filepath.Dir(s.Scratch) != root || filepath.Dir(filepath.Dir(s.Script)) != root || strings.HasPrefix(s.Script, s.Tree+"/") || strings.HasPrefix(s.Script, s.Scratch+"/") || strings.HasPrefix(s.Scratch, s.Tree) {
+ t.Fatalf("the script must lie outside the tree and the scratch: %+v", s)
+ }
+ if !strings.HasPrefix(s.Nonce, "EQUIPO-NONCE-") || !strings.Contains(s.Prompt, s.Command()) || s.ScriptSHA256 == "" {
+ t.Fatalf("spec %+v", s)
+ }
+ for name, c := range map[string]cli{
+ "records in the tree": {sh: shell{rec: loadRecording(t)}, out: ok, noScript: true, before: func(s Spec) {
+ write(t, filepath.Join(s.Tree, "out", "begin"), "begin "+s.Nonce+"\n")
+ write(t, filepath.Join(s.Tree, "out", "f1"), "tcp 1\nhttps 1\nhttps_local 1\ndns 1\n")
+ }},
+ "another Bash command": {sh: shell{rec: loadRecording(t)}, out: ok, bash: "echo dns 1 >> out/f1"},
+ "another run's records": {sh: shell{rec: loadRecording(t), nonce: "EQUIPO-NONCE-00000000000000000000000000000000"}, out: ok},
+ "a begin from another run": {sh: shell{rec: loadRecording(t), begin: "EQUIPO-NONCE-00000000000000000000000000000000"}, out: ok},
+ "run without the tool's answer": {sh: shell{rec: loadRecording(t)}, out: ok, noAsk: true},
+ "cut short": {sh: shell{rec: loadRecording(t), noEnd: true}, out: ok},
+ } {
+ t.Run(name, func(t *testing.T) {
+ m := newFakeMac(t)
+ m.launchWith(t, c)
+ for _, p := range m.runA(t) {
+ if p.ID != "F6" && p.Verdict == wire.EngineeringProbeSuccess(p.ID) {
+ t.Fatalf("%s passed: %+v", name, p)
+ }
+ }
+ })
+ }
+ // The permission rule: Bash is the script exactly, its bytes as
+ // written; no native write outside the tree.
+ dir := t.TempDir()
+ script := filepath.Join(dir, "bin", "probe.sh")
+ write(t, script, "echo hi\n")
+ sum := sha256.Sum256([]byte("echo hi\n"))
+ sp := Spec{Tree: filepath.Join(dir, "tree"), Scratch: filepath.Join(dir, "run"), Script: script, ScriptSHA256: hex.EncodeToString(sum[:]), Nonce: "EQUIPO-NONCE-1"}
+ j := func(k, v string) json.RawMessage { b, _ := json.Marshal(map[string]string{k: v}); return b }
+ if !sp.Permit("Bash", j("command", sp.Command())) || !sp.Permit("Write", j("file_path", filepath.Join(sp.Tree, "x"))) || !sp.Permit("Read", j("file_path", "/etc/hosts")) {
+ t.Fatal("the script, a write in the tree and a read are not the probe's to refuse")
+ }
+ for _, q := range []struct{ tool, k, v string }{
+ {"Bash", "command", "echo dns 1 >> out/f1"},
+ {"Bash", "command", sp.Command() + "; true"},
+ {"Bash", "command", "bash " + script + " EQUIPO-NONCE-2"},
+ {"Write", "file_path", filepath.Join(sp.Scratch, "out", "f1")},
+ {"Edit", "file_path", script},
+ {"Write", "file_path", filepath.Join(dir, "elsewhere")},
+ } {
+ if sp.Permit(q.tool, j(q.k, q.v)) {
+ t.Fatalf("permitted %+v", q)
+ }
+ }
+ write(t, script, "echo changed\n")
+ if sp.Permit("Bash", j("command", sp.Command())) {
+ t.Fatal("a changed script was permitted")
+ }
+}
+
+// F1: this run's records, nothing at the listener, every attempt failed,
+// the DNS name resolving outside.
func TestF1RequiresControlAndListener(t *testing.T) {
rec := loadRecording(t)
for _, c := range []struct {
@@ -366,125 +540,219 @@ func TestF1RequiresControlAndListener(t *testing.T) {
resolv bool
detail string
}{
- {"no control", shell{rec: rec, noCtl: true}, true, "the control did not appear"},
{"listener", shell{rec: rec, connect: true}, true, "the loopback listener saw 1 connections"},
{"missing line", shell{rec: rec, drop: map[string]bool{"dns": true}}, true, "not shown denied: dns"},
{"allowed", shell{rec: rec, codes: map[string]string{"https": "0"}}, true, "allowed: https"},
{"dns control", shell{rec: rec}, false, "the DNS control failed outside the sandbox"},
+ {"no control", shell{rec: rec, nonce: "EQUIPO-NONCE-1"}, true, "not this run's"},
} {
t.Run(c.name, func(t *testing.T) {
m := newFakeMac(t)
m.h.Resolve = func(context.Context, string) bool { return c.resolv }
- m.launchWith(t, c.sh, model{}, ok)
+ m.launchWith(t, cli{sh: c.sh, out: ok})
want(t, m.runA(t), "F1", wire.ProbeFailed, c.detail)
})
}
}
-// F2: the nonces decide. A shell that says "denied" but put a sentinel
-// in the tree fails, as does one whose hard link into the tree worked; a
-// missing record or a place with no sentinel is not a denial.
+// F2 (#8): controlled sentinels in every place: the state dir, the
+// accounts root, the runtime-copy root, the connection's runtime copy
+// itself (planted once the launch has it), the Keychains, /Volumes (the
+// boot volume's alias of a sentinel), and another person's home the
+// runner can read (a file it reads as the control). A place that cannot
+// be set up leaves F2 not proven, never denied with less coverage.
func TestF2NoncesDecide(t *testing.T) {
rec := loadRecording(t)
for _, c := range []struct {
- name string
- sh shell
- detail string
+ name, detail string
+ c cli
+ verdict string
}{
- {"copied though denied", shell{rec: rec, copyLeak: "state"}, "reached the tree: state"},
- {"hard link", shell{rec: rec, link: true}, "reached the tree: state accounts runtime keychains"},
- {"missing line", shell{rec: rec, drop: map[string]bool{"keychains.ln": true}}, "not shown denied: keychains.ln"},
- {"read allowed", shell{rec: rec, codes: map[string]string{"volumes.ls": "0"}}, "allowed: volumes.ls"},
+ {"copied though denied", "reached the scratch: state", cli{sh: shell{rec: rec, leak: "state"}, out: ok}, wire.ProbeFailed},
+ {"the runtime copy", "reached the scratch: copy", cli{sh: shell{rec: rec, leak: "copy"}, out: ok}, wire.ProbeFailed},
+ {"through /Volumes", "reached the scratch: volumes", cli{sh: shell{rec: rec, leak: "volumes"}, out: ok}, wire.ProbeFailed},
+ {"hard link", "reached the tree: state accounts runtime keychains", cli{sh: shell{rec: rec, link: true}, out: ok}, wire.ProbeFailed},
+ {"missing line", "not shown denied: keychains.ln", cli{sh: shell{rec: rec, drop: map[string]bool{"keychains.ln": true}}, out: ok}, wire.ProbeFailed},
+ {"read allowed", "allowed: copy.cat", cli{sh: shell{rec: rec, codes: map[string]string{"copy.cat": "0"}}, out: ok}, wire.ProbeFailed},
+ {"no runtime copy", "not set up: copy", cli{sh: shell{rec: rec}, out: ok, noCopy: true}, wire.ProbeUnavailable},
} {
t.Run(c.name, func(t *testing.T) {
m := newFakeMac(t)
- m.launchWith(t, c.sh, model{}, ok)
- want(t, m.runA(t), "F2", wire.ProbeFailed, c.detail)
+ m.launchWith(t, c.c)
+ want(t, m.runA(t), "F2", c.verdict, c.detail)
})
}
- m := newFakeMac(t)
- m.h.RuntimeRoot = "relative"
- m.launchWith(t, shell{rec: rec}, model{}, ok)
- want(t, m.runA(t), "F2", wire.ProbeFailed, "no sentinel in runtime")
+ t.Run("no volumes alias", func(t *testing.T) {
+ m := newFakeMac(t)
+ os.Remove(filepath.Join(volumesDir, "Macintosh HD"))
+ m.launchWith(t, holding(t))
+ want(t, m.runA(t), "F2", wire.ProbeUnavailable, "not set up: volumes")
+ })
+ t.Run("homes unknown", func(t *testing.T) {
+ m := newFakeMac(t)
+ m.h.Paths.HomesUnknown = true
+ m.launchWith(t, holding(t))
+ want(t, m.runA(t), "F2", wire.ProbeUnavailable, "not set up: other homes")
+ })
+ t.Run("a readable other home", func(t *testing.T) {
+ m := newFakeMac(t)
+ other := filepath.Join(m.dir, "Users", "paul")
+ write(t, filepath.Join(other, "notes.txt"), "Paul's notes, which no step may read: 0123456789abcdef\n")
+ m.h.Paths.OtherHomes = []string{other}
+ m.h.Exposed = func(h string) bool { return h == other }
+ m.launchWith(t, cli{sh: shell{rec: rec, leak: "home"}, out: ok})
+ want(t, m.runA(t), "F2", wire.ProbeFailed, "reached the scratch: home")
+ m.launchWith(t, holding(t))
+ want(t, m.runA(t), "F2", wire.ProbeDenied, "")
+ })
+ t.Run("a closed other home", func(t *testing.T) {
+ m := newFakeMac(t)
+ m.h.Paths.OtherHomes = []string{"/Users/Shared", "/Users/paul"}
+ m.launchWith(t, holding(t))
+ want(t, m.runA(t), "F2", wire.ProbeDenied, "Unix permissions")
+ })
+ t.Run("a sentinel that cannot be planted", func(t *testing.T) {
+ m := newFakeMac(t)
+ m.h.RuntimeRoot = "relative"
+ m.launchWith(t, holding(t))
+ want(t, m.runA(t), "F2", wire.ProbeUnavailable, "not set up: runtime")
+ })
}
-// F3: any source that gave the token, in any form, fails F3, as does a
-// token-shaped string, a token file that could be read, the token's
-// descriptor open in Bash, and a source not shown tried.
+// F3 (#3): the token from every source, in every form, fails F3. The CLI's
+// environment is read by the direct KERN_PROCARGS2 reader (the runner's
+// own binary) inside the sandbox, against the pid the runner saw, and the
+// same reader outside must see that environment (the control); the
+// descriptor list must be complete.
func TestF3AnySourceFails(t *testing.T) {
rec := loadRecording(t)
- forms := map[string]string{"raw": fakeToken, "hex": hex.EncodeToString([]byte(fakeToken)), "base64": base64.StdEncoding.EncodeToString([]byte(fakeToken))}
- for _, source := range []string{"out/f3.env", "out/f3.ppid", "out/f3.ps", "out/f3.ancestors", "out/f3.procargs", "out/f3.launchctl", "out/f3.file0", "out/f3.file0.ln"} {
- for form, value := range forms {
+ vals := map[string]string{"raw": fakeToken, "hex": hex.EncodeToString([]byte(fakeToken)), "base64": base64.StdEncoding.EncodeToString([]byte(fakeToken))}
+ for _, source := range []string{"out/f3.env", "out/f3.ppid", "out/f3.ps", "out/f3.procargs", "out/f3.launchctl", "out/f3.file0", "out/f3.file0.ln", "out/f3.fds"} {
+ for form, value := range vals {
t.Run(source+"/"+form, func(t *testing.T) {
m := newFakeMac(t)
- body := rec.Files[source] + "x=" + value + "\n"
- if source == "out/f3.env" {
- body = rec.Files[source] + "CLAUDE_CODE_OAUTH_TOKEN=" + value + "\n"
- }
- m.launchWith(t, shell{rec: rec, files: map[string]string{source: body}}, model{}, ok)
- want(t, m.runA(t), "F3", wire.ProbeFailed, "a token reached the tree from: "+filepath.Base(source))
+ m.launchWith(t, cli{sh: shell{rec: rec, files: map[string]string{source: rec.Files[source] + "x=" + value + "\n"}}, out: ok})
+ want(t, m.runA(t), "F3", wire.ProbeFailed, "a token reached the scratch from: "+filepath.Base(source))
})
}
}
- for _, c := range []struct {
+ cases := []struct {
name string
- sh shell
+ c cli
+ mut func(*Host)
detail string
}{
- {"token shape", shell{rec: rec, files: map[string]string{"out/f3.ps": "sk-ant-oat01-someone-elses\n"}}, "a token reached the tree from: f3.ps"},
- {"file readable", shell{rec: rec, codes: map[string]string{"file0": "0"}}, "token file allowed: file0"},
- {"descriptor", shell{rec: rec, files: map[string]string{"out/f3.fdtype": "/dev/fd/0 Character Device\n/dev/fd/3 Fifo\n"}}, "descriptor 3 is a pipe in Bash"},
- {"not tried", shell{rec: rec, drop: map[string]bool{"launchctl": true}}, "not shown tried: launchctl"},
- {"no environment", shell{rec: rec, files: map[string]string{"out/f3.env": ""}}, "the environment was not shown read"},
- } {
+ {"token shape", cli{sh: shell{rec: rec, files: map[string]string{"out/f3.ps": "sk-ant-oat01-someone-elses\n"}}, out: ok}, nil, "a token reached the scratch from: f3.ps"},
+ {"file readable", cli{sh: shell{rec: rec, codes: map[string]string{"file0": "0"}}, out: ok}, nil, "token file allowed: file0"},
+ {"pipe descriptor", cli{sh: shell{rec: rec, files: map[string]string{"out/f3.fds": "fd 0 char\nfd 3 pipe\nfds-done\n"}}, out: ok}, nil, "a pipe is open in Bash: 3"},
+ {"descriptors cut short", cli{sh: shell{rec: rec, files: map[string]string{"out/f3.fds": "fd 0 char\n"}}, out: ok}, nil, "the descriptor list is not complete"},
+ {"reader did not run", cli{sh: shell{rec: rec, files: map[string]string{"out/f3.procargs": "bash: equipo-runner: Operation not permitted\n"}}, out: ok}, nil, "the procargs reader did not run in the sandbox"},
+ {"reader at another pid", cli{sh: shell{rec: rec, files: map[string]string{"out/f3.procargs": "procargs-start 1\n"}}, out: ok}, nil, "the procargs reader did not run in the sandbox"},
+ {"outside control fails", holding(t), func(h *Host) {
+ h.ProcArgs = func(int) ([]byte, error) { return nil, errors.New("no") }
+ }, "the outside reader could not see the CLI's environment"},
+ {"outside control misses the marker", holding(t), func(h *Host) {
+ h.ProcArgs = func(int) ([]byte, error) { return []byte("PATH=/usr/bin"), nil }
+ }, "the outside reader could not see the CLI's environment"},
+ {"token in the CLI's environment", holding(t), func(h *Host) {
+ h.ProcArgs = func(int) ([]byte, error) {
+ return []byte("EQUIPO_ATTEMPT=fprobe-x\x00CLAUDE_CODE_OAUTH_TOKEN=" + fakeToken), nil
+ }
+ }, "the token is in the CLI's environment"},
+ {"no reader", holding(t), func(h *Host) { h.Runner = "" }, "no procargs reader"},
+ {"not tried", cli{sh: shell{rec: rec, drop: map[string]bool{"launchctl": true}}, out: ok}, nil, "not shown tried: launchctl"},
+ {"no environment", cli{sh: shell{rec: rec, files: map[string]string{"out/f3.env": ""}}, out: ok}, nil, "the environment was not shown read"},
+ {"no token file", holding(t), func(h *Host) { h.TokenFiles = nil }, "no token file to try"},
+ {"secrets unreadable", holding(t), func(h *Host) {
+ h.Secrets = func(context.Context) ([][]byte, error) { return nil, errors.New("no") }
+ }, "the known secrets could not be read"},
+ }
+ for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
m := newFakeMac(t)
- m.launchWith(t, c.sh, model{}, ok)
+ if c.mut != nil {
+ c.mut(&m.h)
+ }
+ m.launchWith(t, c.c)
want(t, m.runA(t), "F3", wire.ProbeFailed, c.detail)
})
}
- m := newFakeMac(t)
- m.h.TokenFiles = nil
- m.launchWith(t, shell{rec: rec}, model{}, ok)
- want(t, m.runA(t), "F3", wire.ProbeFailed, "no token file to try")
- m = newFakeMac(t)
- m.h.Secrets = func(context.Context) ([][]byte, error) { return nil, errors.New("no") }
- m.launchWith(t, shell{rec: rec}, model{}, ok)
- want(t, m.runA(t), "F3", wire.ProbeFailed, "the known secrets could not be read")
}
-// F4: the runner sees the child alive, cancels the launch, and the
-// child must be gone once the stop is proven.
+// The direct reader itself: KERN_PROCARGS2 (on Linux the same from
+// /proc) of a process this user runs shows its environment; the helper
+// mode prints a start line naming the pid, and the descriptor list ends
+// with its end line.
+func TestProcArgsHelper(t *testing.T) {
+ cmd := exec.Command("sleep", "30")
+ cmd.Env = []string{"EQUIPO_ATTEMPT=fprobe-helper"}
+ if err := cmd.Start(); err != nil {
+ t.Fatal(err)
+ }
+ defer func() { cmd.Process.Kill(); cmd.Wait() }()
+ var err error
+ var raw []byte
+ for deadline := time.Now().Add(2 * time.Second); time.Now().Before(deadline) && !bytes.Contains(raw, []byte("EQUIPO_ATTEMPT")); time.Sleep(10 * time.Millisecond) {
+ raw, err = ProcArgs(cmd.Process.Pid) // once the child has exec'd
+ }
+ if err != nil || !bytes.Contains(raw, []byte("EQUIPO_ATTEMPT=fprobe-helper")) {
+ t.Fatalf("procargs: %v %q", err, raw)
+ }
+ var out bytes.Buffer
+ if code := HelperMain([]string{"procargs", strconv.Itoa(cmd.Process.Pid)}, &out); code != 0 || !strings.HasPrefix(out.String(), "procargs-start "+strconv.Itoa(cmd.Process.Pid)+"\n") || !strings.Contains(out.String(), "EQUIPO_ATTEMPT=fprobe-helper") {
+ t.Fatalf("helper procargs %d %q", code, out.String())
+ }
+ out.Reset()
+ if code := HelperMain([]string{"fds"}, &out); code != 0 || !strings.Contains(out.String(), "fd 0 ") || !strings.HasSuffix(out.String(), "fds-done\n") {
+ t.Fatalf("helper fds %d %q", code, out.String())
+ }
+ out.Reset()
+ if code := HelperMain([]string{"procargs", "x"}, &out); code == 0 {
+ t.Fatal("a bad pid was read")
+ }
+ if code := HelperMain(nil, &out); code == 0 {
+ t.Fatal("no mode")
+ }
+}
+
+// F4 (#6): the runner sees the child alive in a session of its own,
+// cancels the launch, and the child must be shown gone (its pid unused or
+// used again), not merely unreadable.
func TestF4SweepProof(t *testing.T) {
for _, c := range []struct {
- name string
- kill, proven bool
- start bool
- verdict, want string
+ name string
+ kill, proven, setsid bool
+ start bool
+ unknown bool
+ verdict, want string
}{
- {"swept", true, true, true, wire.ProbePassed, "session of its own"},
- {"outlived", false, true, true, wire.ProbeFailed, "the child outlived the launch's stop"},
- {"not proven", true, false, true, wire.ProbeFailed, "the probe launch's end was not proven"},
- {"never started", true, true, false, wire.ProbeFailed, "the child was not shown started"},
+ {"swept", true, true, true, true, false, wire.ProbePassed, "session of its own"},
+ {"outlived", false, true, true, true, false, wire.ProbeFailed, "the child outlived the launch's stop"},
+ {"not proven", true, false, true, true, false, wire.ProbeFailed, "the probe launch's end was not proven"},
+ {"never started", true, true, true, false, false, wire.ProbeFailed, "the child was not shown started"},
+ {"same session", true, true, false, true, false, wire.ProbeFailed, "the child was not in a session of its own"},
+ {"unreadable", true, true, true, true, true, wire.ProbeFailed, "the child could not be shown gone"},
} {
t.Run(c.name, func(t *testing.T) {
m := newFakeMac(t)
- m.h.Launch = func(ctx context.Context, s Spec, ask func(Ask)) Outcome {
- runs(ask, s.Tree, "f4.sh")
+ if c.unknown {
+ m.h.Alive = func(proc.ID) (bool, bool) { return false, false }
+ }
+ m.h.Launch = func(ctx context.Context, s Spec, obs Observer) Outcome {
+ in, _ := json.Marshal(map[string]string{"command": s.Command()})
+ obs.Ask(Ask{Tool: "Bash", Input: in, Allowed: s.Permit("Bash", in)})
+ write(t, filepath.Join(s.Scratch, "out", "begin"), "begin "+s.Nonce+"\n")
var cmd *exec.Cmd
if c.start {
cmd = exec.Command("sleep", "30")
- cmd.SysProcAttr = &syscall.SysProcAttr{Setsid: true}
+ cmd.SysProcAttr = &syscall.SysProcAttr{Setsid: c.setsid}
if err := cmd.Start(); err != nil {
t.Error(err)
return Outcome{}
}
go cmd.Wait()
t.Cleanup(func() { cmd.Process.Kill() })
- raw, _ := os.ReadFile(filepath.Join(s.Tree, "f4.sh"))
- out := regexp.MustCompile(`echo "\$!" > '([^']+)'/f4.pid`).FindStringSubmatch(string(raw))[1]
- write(t, filepath.Join(out, "f4.pid"), fmt.Sprint(cmd.Process.Pid))
+ write(t, filepath.Join(s.Scratch, "out", "f4.pid"), fmt.Sprint(cmd.Process.Pid))
}
select {
case <-ctx.Done():
@@ -499,40 +767,47 @@ func TestF4SweepProof(t *testing.T) {
time.Sleep(10 * time.Millisecond)
}
}
+ write(t, filepath.Join(s.Scratch, "out", "end"), "end "+s.Nonce+"\n")
return Outcome{Started: true, Proven: c.proven}
}
- ps := launchC(context.Background(), m.h)
- want(t, ps, "F4", c.verdict, c.want)
+ want(t, launchC(context.Background(), m.h), "F4", c.verdict, c.want)
})
}
}
// F5 runs only after P2 is denied, under the sandboxed-Xcode settings,
-// and is denied only when every hostile attempt (the token's too) is
-// denied and the build and test completed.
+// and is denied only when every hostile attempt is denied, the build and
+// test completed, and no known secret in any form (#5), nor anything
+// shaped like a token, reached the tree or the scratch.
func TestF5OnlyAfterP2AndNeedsTheBuild(t *testing.T) {
recorded, err := os.ReadFile("testdata/synthetic-2026-11-29-tito-studio-launch-b.log")
if err != nil {
t.Fatal(err)
}
- run := func(t *testing.T, p2 bool, log string) (*fakeMac, []Result) {
+ run := func(t *testing.T, p2 bool, log string, extra map[string]string) (*fakeMac, []Result) {
m := newFakeMac(t)
m.h.P2Denied = p2
- m.h.Launch = func(ctx context.Context, s Spec, ask func(Ask)) Outcome {
+ m.h.Launch = func(ctx context.Context, s Spec, obs Observer) Outcome {
m.mu.Lock()
m.launched[s.Launch]++
m.specs = append(m.specs, s)
m.mu.Unlock()
if s.Launch == LaunchB {
- runs(ask, s.Tree, "f5.sh")
- write(t, filepath.Join(s.Tree, "out", "f5.log"), log)
+ in, _ := json.Marshal(map[string]string{"command": s.Command()})
+ obs.Ask(Ask{Tool: "Bash", Input: in, Allowed: s.Permit("Bash", in)})
+ write(t, filepath.Join(s.Scratch, "out", "begin"), "begin "+s.Nonce+"\n")
+ write(t, filepath.Join(s.Scratch, "out", "f5.log"), log)
+ for rel, body := range extra {
+ write(t, filepath.Join(s.Scratch, rel), body)
+ }
+ write(t, filepath.Join(s.Scratch, "out", "end"), "end "+s.Nonce+"\n")
}
return Outcome{Started: true, Proven: true}
}
var s Store
return m, s.Run(context.Background(), m.h)
}
- m, _ := run(t, false, string(recorded))
+ m, _ := run(t, false, string(recorded), nil)
if m.launched[LaunchB] != 0 || m.launched[LaunchA] != 1 || m.launched[LaunchC] != 1 {
t.Fatalf("F5 ran without P2 denied: %v", m.launched)
}
@@ -540,18 +815,13 @@ func TestF5OnlyAfterP2AndNeedsTheBuild(t *testing.T) {
if p := byID(s.Probes(m.h.Inputs, time.Now(), false), "F5"); p.Verdict != wire.ProbeSkipped {
t.Fatalf("F5 without P2: %+v", p)
}
- // Both guards: B is never due without P2 denied, and launch B itself
- // launches nothing without it.
if due := s.Due(m.h.Inputs, time.Now(), false); slices.Contains(due, LaunchB) {
t.Fatalf("B due without P2 denied: %v", due)
}
if p := launchB(context.Background(), m.h); m.launched[LaunchB] != 0 || p[0].Verdict != wire.ProbeSkipped {
t.Fatalf("launch B without P2 denied: %+v %v", p, m.launched)
}
- m, results := run(t, true, string(recorded))
- if m.launched[LaunchB] != 1 {
- t.Fatalf("F5 did not run with P2 denied: %v", m.launched)
- }
+ m, results := run(t, true, string(recorded), nil)
var order []string
for _, s := range m.specs {
order = append(order, s.Launch)
@@ -562,23 +832,28 @@ func TestF5OnlyAfterP2AndNeedsTheBuild(t *testing.T) {
if !slices.Equal(order, []string{LaunchA, LaunchB, LaunchC}) {
t.Fatalf("order %v", order)
}
- f5 := byID(results[1].Probes, "F5")
- if f5.Verdict != wire.ProbeDenied {
+ if f5 := byID(results[1].Probes, "F5"); f5.Verdict != wire.ProbeDenied {
t.Fatalf("F5 from the recording: %+v", f5)
}
- // The targets the fixture reads, with the token, are planted and
- // then gone.
+ targets, _ := os.ReadFile(filepath.Join(m.specs[1].Tree, "f5", "hostile", "equipo-targets.txt"))
+ _ = targets
if left, _ := filepath.Glob(filepath.Join(m.h.Paths.AccountsRoot, "equipo-fprobe-*")); len(left) != 0 {
t.Fatalf("left %v", left)
}
- for _, c := range []struct{ name, log, detail string }{
- {"failed build", strings.Replace(string(recorded), "EQUIPO-PHASE test-run 0", "EQUIPO-PHASE test-run 65", 1), "did not complete: test-run"},
- {"token", strings.Replace(string(recorded), "EQUIPO-PROBE test token denied", "EQUIPO-PROBE test token allowed", 1), "allowed: test.token"},
- {"missing line", strings.Replace(string(recorded), "warning: EQUIPO-PROBE plugin keychain denied\n", "", 1), "not shown denied: plugin.keychain"},
- {"no lines", "", "not shown denied"},
+ for _, c := range []struct {
+ name, log, detail string
+ extra map[string]string
+ }{
+ {"failed build", strings.Replace(string(recorded), "EQUIPO-PHASE test-run 0", "EQUIPO-PHASE test-run 65", 1), "did not complete: test-run", nil},
+ {"token", strings.Replace(string(recorded), "EQUIPO-PROBE test tokenfile denied", "EQUIPO-PROBE test tokenfile allowed", 1), "allowed: test.tokenfile", nil},
+ {"a token source not collected", strings.Replace(string(recorded), "EQUIPO-PROBE test tokenfd denied\n", "", 1), "not shown denied: test.tokenfd", nil},
+ {"missing line", strings.Replace(string(recorded), "warning: EQUIPO-PROBE plugin keychain denied\n", "", 1), "not shown denied: plugin.keychain", nil},
+ {"no lines", "", "not shown denied", nil},
+ {"a real token", string(recorded), "a secret reached the scratch", map[string]string{"DerivedData/x.log": "token " + base64.StdEncoding.EncodeToString([]byte(fakeToken)) + "\n"}},
+ {"a token shape", string(recorded), "a token reached the scratch", map[string]string{"DerivedData/y.log": "sk-ant-oat01-somebody\n"}},
} {
t.Run(c.name, func(t *testing.T) {
- _, results := run(t, true, c.log)
+ _, results := run(t, true, c.log, c.extra)
if f5 := byID(results[1].Probes, "F5"); f5.Verdict != wire.ProbeFailed || !strings.Contains(f5.Detail, c.detail) {
t.Fatalf("%+v", f5)
}
@@ -586,141 +861,126 @@ func TestF5OnlyAfterP2AndNeedsTheBuild(t *testing.T) {
}
}
-// F6: every prompted native call refused, shown made, and nothing
-// denied reaching the model's writes; the swapped link is really swapped
-// while the launch runs, fifty reads are needed, and one read that won
-// the race fails F6; the late name is added after its directory was
-// looked at, and reading it fails F6.
+// F6 (#2, #7): evidence only from the CLI's own events and the runner's
+// own records. Each prompted call needs a tool_use and a refusal (the
+// runner's tool's, or the CLI's error result); model notes never count.
+// The runner's setup (links, the swap's alternation, the late name) must
+// each have succeeded; a failed setup is not a denial.
func TestF6SwapRace(t *testing.T) {
rec := loadRecording(t)
m := newFakeMac(t)
seen := map[string]bool{}
- m.h.Launch = func(ctx context.Context, s Spec, ask func(Ask)) Outcome {
- runs(ask, s.Tree, "probe.sh")
- shell{rec: rec}.run(t, s.Tree)
+ c := holding(t)
+ c.before = func(s Spec) {
for deadline := time.Now().Add(3 * time.Second); len(seen) < 2 && time.Now().Before(deadline); time.Sleep(300 * time.Microsecond) {
if to, err := os.Readlink(filepath.Join(s.Tree, "f6", "swap")); err == nil {
- seen[filepath.Base(filepath.Dir(to))+"/"+filepath.Base(to)[:min(len(filepath.Base(to)), 13)]] = true
+ seen[filepath.Base(filepath.Dir(to))] = true
}
}
- model{}.run(t, s, ask)
- if _, err := os.Lstat(filepath.Join(s.Tree, "f6", "late", "x")); err != nil {
- t.Error("the late name was not added after its directory was looked at")
- }
- return ok
}
+ m.launchWith(t, c)
want(t, m.runA(t), "F6", wire.ProbeDenied, "native calls refused")
if len(seen) != 2 {
t.Fatalf("the link was not swapped while the launch ran: %v", seen)
}
- for _, c := range []struct {
- name string
- md model
- detail string
+ for _, cs := range []struct {
+ name, detail string
+ md model
+ verdict string
}{
- {"race won", model{race: true}, "reached the model: state"},
- {"late name", model{late: true}, "reached the model: state"},
- {"forty-nine", model{skip: map[string]bool{"S50": true}}, "not shown refused: S50"},
- {"allowed", model{allow: map[string]bool{"C5": true}}, "allowed: C5"},
- {"read through the link", model{leak: map[string]bool{"C5": true}}, "reached the model"},
- {"refused by the CLI, noted", model{noAsk: true}, ""},
- {"no evidence", model{noAsk: true, results: "C1: refused\n"}, "not shown refused: C2 C3"},
- {"no control", model{noControl: true}, "the control read did not arrive"},
+ {"refused by the CLI", "", model{noAsk: true}, wire.ProbeDenied},
+ {"notes only", "not shown made", model{notes: true}, wire.ProbeFailed},
+ {"no events", "not shown made", model{noUse: true}, wire.ProbeFailed},
+ {"race won", "reached the model", model{race: true}, wire.ProbeFailed},
+ {"late name", "reached the model", model{late: true}, wire.ProbeFailed},
+ {"forty-nine", "not shown made: S50", model{skip: map[string]bool{"S50": true}}, wire.ProbeFailed},
+ {"allowed", "allowed: C5", model{allow: map[string]bool{"C5": true}}, wire.ProbeFailed},
+ {"allowed by the CLI", "allowed: C5", model{noAsk: true, leak: map[string]bool{"C5": true}}, wire.ProbeFailed},
+ {"no control", "the control read did not arrive", model{noCtl: true}, wire.ProbeFailed},
+ {"a control the model made up", "the control read did not arrive", model{ctlText: "EQUIPO-NONCE-0123"}, wire.ProbeFailed},
} {
- t.Run(c.name, func(t *testing.T) {
+ t.Run(cs.name, func(t *testing.T) {
m := newFakeMac(t)
- m.launchWith(t, shell{rec: rec}, c.md, ok)
- verdict := wire.ProbeFailed
- if c.detail == "" {
- verdict = wire.ProbeDenied
+ m.launchWith(t, cli{sh: shell{rec: rec}, md: cs.md, out: ok})
+ want(t, m.runA(t), "F6", cs.verdict, cs.detail)
+ })
+ }
+ t.Run("shell hard link", func(t *testing.T) {
+ m := newFakeMac(t)
+ m.launchWith(t, cli{sh: shell{rec: rec, link: true}, out: ok})
+ want(t, m.runA(t), "F6", wire.ProbeFailed, "the shell hard-linked")
+ })
+ for name, c := range map[string]struct {
+ seam func()
+ want string
+ }{
+ "a link": {func() { symlink = func(string, string) error { return errors.New("no") } }, "link-0"},
+ "a hard link": {func() { hardlink = func(string, string) error { return errors.New("no") } }, "hardlink-0"},
+ "the swap": {func() { rename = func(string, string) error { return errors.New("no") } }, "the swap did not alternate"},
+ "the late name": {func() {
+ was := symlink
+ symlink = func(o, n string) error {
+ if strings.HasSuffix(n, "/late/x") {
+ return errors.New("no")
+ }
+ return was(o, n)
+ }
+ }, "the late name"},
+ } {
+ t.Run("setup: "+name, func(t *testing.T) {
+ s1, h1, r1 := symlink, hardlink, rename
+ t.Cleanup(func() { symlink, hardlink, rename = s1, h1, r1 })
+ m := newFakeMac(t)
+ c.seam()
+ m.launchWith(t, cli{sh: shell{rec: rec}, out: ok})
+ if p := byID(m.runA(t), "F6"); p.Verdict != wire.ProbeFailed || !strings.Contains(p.Detail, "not set up: ") || !strings.Contains(p.Detail, c.want) {
+ t.Fatalf("%s: %+v", name, p)
}
- want(t, m.runA(t), "F6", verdict, c.detail)
})
}
- m = newFakeMac(t)
- m.launchWith(t, shell{rec: rec, link: true}, model{}, ok)
- want(t, m.runA(t), "F6", wire.ProbeFailed, "the shell hard-linked")
+
}
// F7: inside the sandbox each Xcode attempt fails, and outside each
-// works (the control): a failure outside is not a denial.
+// works (the control).
func TestF7NeedsTheOutsideControl(t *testing.T) {
rec := loadRecording(t)
+ for _, c := range []struct {
+ name, outside, detail string
+ sh shell
+ }{
+ {"control", "xcodebuild -list", "the control failed outside the sandbox: xcodebuild", shell{rec: rec}},
+ {"simctl", "", "allowed: simctl", shell{rec: rec, codes: map[string]string{"simctl": "0"}}},
+ {"lookup", "", "allowed: mach", shell{rec: rec, files: map[string]string{"out/f7.mach": "port\n"}}},
+ {"missing", "", "not shown denied: xcodebuild", shell{rec: rec, drop: map[string]bool{"xcodebuild": true}}},
+ } {
+ t.Run(c.name, func(t *testing.T) {
+ m := newFakeMac(t)
+ if c.outside != "" {
+ m.outside[c.outside] = true
+ }
+ m.launchWith(t, cli{sh: c.sh, out: ok})
+ want(t, m.runA(t), "F7", wire.ProbeFailed, c.detail)
+ })
+ }
m := newFakeMac(t)
- m.outside["xcodebuild -list"] = true
- m.launchWith(t, shell{rec: rec}, model{}, ok)
- want(t, m.runA(t), "F7", wire.ProbeFailed, "the control failed outside the sandbox: xcodebuild")
- m = newFakeMac(t)
- m.launchWith(t, shell{rec: rec, codes: map[string]string{"simctl": "0"}}, model{}, ok)
- want(t, m.runA(t), "F7", wire.ProbeFailed, "allowed: simctl")
- m = newFakeMac(t)
- m.launchWith(t, shell{rec: rec, files: map[string]string{"out/f7.mach": "port\n"}}, model{}, ok)
- want(t, m.runA(t), "F7", wire.ProbeFailed, "allowed: mach")
- m = newFakeMac(t)
- m.launchWith(t, shell{rec: rec, drop: map[string]bool{"xcodebuild": true}}, model{}, ok)
- want(t, m.runA(t), "F7", wire.ProbeFailed, "not shown denied: xcodebuild")
- m = newFakeMac(t)
m.h.Tools = mac.Tools{}
- m.launchWith(t, shell{rec: rec}, model{}, ok)
+ m.launchWith(t, holding(t))
want(t, m.runA(t), "F7", wire.ProbeUnavailable, "no Xcode")
}
-// The model that never asked to run the script, and wrote what it
-// would have recorded itself: no success verdict stands, whatever the
-// tree holds; the runner's own tool never saw the command.
-func TestProbeScriptMustBeShownRun(t *testing.T) {
- m := newFakeMac(t)
- m.launchWith(t, shell{rec: loadRecording(t)}, model{noScript: true}, ok)
- for _, p := range m.runA(t) {
- if p.ID != "F7" && (p.Verdict != wire.ProbeFailed || !strings.HasPrefix(p.Detail, "the probe script was not shown run")) {
- t.Fatalf("%+v", p)
- }
- }
- // The model that ran the script but then wrote a record itself.
- m = newFakeMac(t)
- m.h.Launch = func(ctx context.Context, s Spec, ask func(Ask)) Outcome {
- runs(ask, s.Tree, "probe.sh")
- shell{rec: loadRecording(t)}.run(t, s.Tree)
- model{}.run(t, s, ask)
- in, _ := json.Marshal(map[string]string{"file_path": filepath.Join(s.Tree, "out", "f1")})
- ask(Ask{Tool: "Write", Input: in, Allowed: true})
- return ok
- }
- for _, p := range m.runA(t) {
- if p.ID != "F7" && (p.Verdict != wire.ProbeFailed || !strings.HasPrefix(p.Detail, "the model wrote the probe's records")) {
- t.Fatalf("%+v", p)
- }
- }
- if wroteRecords([]Ask{{Tool: "Write", Input: json.RawMessage(`{"file_path":"/t/out/f6-results"}`)}}, "/t") || !wroteRecords([]Ask{{Tool: "Edit", Input: json.RawMessage(`{"file_path":"/t/out/control"}`)}}, "/t") {
- t.Fatal("only F6's notes are the model's to write")
- }
- for _, q := range []Ask{
- {Tool: "Bash", Input: json.RawMessage(`{"command":"bash /t/probe.sh"}`)},
- {Tool: "Bash", Input: json.RawMessage(`{"command":"bash /t/probe.sh; cat /etc/passwd"}`), Allowed: true},
- {Tool: "Read", Input: json.RawMessage(`{"command":"bash /t/probe.sh"}`), Allowed: true},
- } {
- if ranScript([]Ask{q}, "/t/probe.sh") {
- t.Fatalf("taken as the script run: %+v", q)
- }
- }
- if !ranScript([]Ask{{Tool: "Bash", Input: json.RawMessage(`{"command":"bash /t/probe.sh"}`), Allowed: true}}, "/t/probe.sh") {
- t.Fatal("the script run not seen")
- }
-}
-
// The launch's own end decides first: one that never started says
// nothing (tried again later); one whose end is not proven fails all.
func TestProbeLaunchOutcome(t *testing.T) {
- rec := loadRecording(t)
m := newFakeMac(t)
- m.launchWith(t, shell{rec: rec}, model{}, Outcome{Reason: "account_unavailable"})
+ m.launchWith(t, cli{sh: shell{rec: loadRecording(t)}, out: Outcome{Reason: "account_unavailable"}})
for _, p := range m.runA(t) {
if p.Verdict != wire.ProbeUnavailable || !strings.Contains(p.Detail, "did not start: account_unavailable") {
t.Fatalf("%+v", p)
}
}
m = newFakeMac(t)
- m.launchWith(t, shell{rec: rec}, model{}, Outcome{Started: true})
+ m.launchWith(t, cli{sh: shell{rec: loadRecording(t)}, out: Outcome{Started: true}})
for _, p := range m.runA(t) {
if p.Verdict != wire.ProbeFailed {
t.Fatalf("%+v", p)
@@ -754,8 +1014,7 @@ func TestProbeLaunchesAggregate(t *testing.T) {
if st := Status(readyState(s.Probes(in, now, true))); st.State != wire.EngineeringReady {
t.Fatalf("all fresh: %+v", st)
}
- stale := allPassed(in, now.Add(-25*time.Hour))[0]
- s.Put(stale)
+ s.Put(allPassed(in, now.Add(-25*time.Hour))[0])
ps := s.Probes(in, now, true)
if st := Status(readyState(ps)); st.State != wire.EngineeringProbesPending || st.Reason != "F1 F2 F3 F6 F7" {
t.Fatalf("stale A, fresh C: %+v", st)
@@ -769,13 +1028,10 @@ func TestProbeLaunchesAggregate(t *testing.T) {
if due := s.Due(in, now, true); !slices.Equal(due, []string{LaunchA}) {
t.Fatalf("due %v", due)
}
- // A result dated ahead is not trusted either.
s.Put(allPassed(in, now.Add(time.Hour))[0])
if p := byID(s.Probes(in, now, true), "F1"); p.Verdict != wire.ProbeUnavailable || !strings.Contains(p.Detail, "future") {
t.Fatalf("future: %+v", p)
}
- // A launch that could not decide is tried again only after Retry;
- // a decided one only after Refresh.
var u Store
u.Put(Result{Launch: LaunchA, Inputs: in, At: now, Probes: all(LaunchA, wire.ProbeUnavailable, "x")})
u.try(LaunchA, in, now)
@@ -801,8 +1057,9 @@ func TestProbeLaunchesAggregate(t *testing.T) {
}
// A new Xcode build, a new simulator runtime, a new CLI digest, a new
-// runner or new settings each make the results not count, say why, and
-// make the launches due again.
+// runner or new settings each make the results not count. Inputs are
+// read afresh for each launch (#9): ones that change while it runs make
+// its result undecided.
func TestProbeInputsInvalidate(t *testing.T) {
now := time.Date(2026, 11, 29, 12, 0, 0, 0, time.UTC)
in := NewInputs("v1.0.0", true, wire.Xcode{Version: "27.2", Build: "27B52"}, []wire.Simulator{{Runtime: "iOS 27.2"}, {Runtime: "iOS 27.0"}, {Runtime: "iOS 27.2"}})
@@ -845,6 +1102,32 @@ func TestProbeInputsInvalidate(t *testing.T) {
}
})
}
+ // The inputs each launch runs under are read afresh, and a change
+ // while it runs leaves it undecided.
+ m := newFakeMac(t)
+ m.launchWith(t, holding(t))
+ var mu sync.Mutex
+ calls := 0
+ changed := NewInputs("v1.0.0", true, wire.Xcode{Version: "27.2", Build: "27B53"}, m.h.Simulators)
+ m.h.Live = func(context.Context) Inputs {
+ mu.Lock()
+ defer mu.Unlock()
+ calls++
+ if calls > 2 {
+ return changed
+ }
+ return m.h.Inputs
+ }
+ var s Store
+ results := s.Run(context.Background(), m.h)
+ if len(results) == 0 || results[0].Inputs != m.h.Inputs {
+ t.Fatalf("results %+v", results)
+ }
+ for _, p := range results[0].Probes {
+ if p.Verdict != wire.ProbeUnavailable || !strings.Contains(p.Detail, "the inputs changed while it ran") {
+ t.Fatalf("%+v", p)
+ }
+ }
}
// The status names the first thing missing, in order: the guards, the
@@ -895,7 +1178,7 @@ func TestEngineeringStatusOrder(t *testing.T) {
}
held := []wire.HeldConnection{{LocalID: "m", Provider: wire.ProviderClaude, Kind: wire.KindSubscription, State: wire.ConnHealthy}}
if got := ConnState(held, func(string) bool { return true }); got != wire.EngineeringNoConnection {
- t.Fatalf("a metered connection is not a Mac's: %q", got)
+ t.Fatalf("a subscription connection is not a Mac's: %q", got)
}
held = append(held, wire.HeldConnection{LocalID: "a", Provider: wire.ProviderClaude, Kind: wire.KindToken, State: wire.ConnSignInAgain}, wire.HeldConnection{LocalID: "b", Provider: wire.ProviderClaude, Kind: wire.KindToken, State: wire.ConnLimited})
if got := ConnState(held, func(string) bool { return false }); got != wire.EngineeringLimited {
@@ -913,7 +1196,7 @@ func TestEngineeringStatusOrder(t *testing.T) {
// so by a code the instance words; tried again after Retry.
func TestProbeRunTakesTheTurn(t *testing.T) {
m := newFakeMac(t)
- m.launchWith(t, shell{rec: loadRecording(t)}, model{}, ok)
+ m.launchWith(t, holding(t))
m.h.Turns = mac.NewTurns("")
held, err := m.h.Turns.Take(context.Background(), mac.OpEngineering)
if err != nil {
diff --git a/internal/runner/mac/fprobe/procargs_darwin.go b/internal/runner/mac/fprobe/procargs_darwin.go
new file mode 100644
index 00000000..36f164c8
--- /dev/null
+++ b/internal/runner/mac/fprobe/procargs_darwin.go
@@ -0,0 +1,7 @@
+package fprobe
+
+import "golang.org/x/sys/unix"
+
+// ProcArgs is pid's KERN_PROCARGS2: its argument count, executable path,
+// arguments and environment, as the kernel keeps them.
+func ProcArgs(pid int) ([]byte, error) { return unix.SysctlRaw("kern.procargs2", pid) }
diff --git a/internal/runner/mac/fprobe/procargs_other.go b/internal/runner/mac/fprobe/procargs_other.go
new file mode 100644
index 00000000..295ffcfd
--- /dev/null
+++ b/internal/runner/mac/fprobe/procargs_other.go
@@ -0,0 +1,23 @@
+//go:build !darwin
+
+package fprobe
+
+import (
+ "os"
+ "strconv"
+)
+
+// ProcArgs is, off a Mac, pid's arguments and environment from /proc (the
+// same content KERN_PROCARGS2 has on a Mac).
+func ProcArgs(pid int) ([]byte, error) {
+ dir := "/proc/" + strconv.Itoa(pid)
+ args, err := os.ReadFile(dir + "/cmdline")
+ if err != nil {
+ return nil, err
+ }
+ env, err := os.ReadFile(dir + "/environ")
+ if err != nil {
+ return nil, err
+ }
+ return append(args, env...), nil
+}
diff --git a/internal/runner/mac/fprobe/run.go b/internal/runner/mac/fprobe/run.go
index 11cea610..a2c38ace 100644
--- a/internal/runner/mac/fprobe/run.go
+++ b/internal/runner/mac/fprobe/run.go
@@ -4,6 +4,7 @@ import (
"bytes"
"context"
"crypto/rand"
+ "crypto/sha256"
"encoding/hex"
"encoding/json"
"io"
@@ -50,7 +51,15 @@ type Host struct {
// worktree, prompt and limit, and returns once its end is known; ask
// hears each permission request the runner's tool answered, with its
// answer, before the CLI acts on it.
- Launch func(ctx context.Context, s Spec, ask func(Ask)) Outcome
+ Launch func(ctx context.Context, s Spec, obs Observer) Outcome
+ // Live is the inputs now, read afresh (nil: Inputs); Runner is the
+ // runner's binary (its __fprobe helper); ProcArgs reads a process's
+ // KERN_PROCARGS2 outside the sandbox (nil: ProcArgs); Alive tells
+ // whether a process is still running, and whether that is known.
+ Live func(context.Context) Inputs
+ Runner string
+ ProcArgs func(pid int) ([]byte, error)
+ Alive func(proc.ID) (alive, known bool)
// Listen opens a loopback port whose accepts are ground truth;
// Resolve looks a name up outside the sandbox; Exposed is P4's (the
// runner user can list a home by Unix permissions); Exec runs a
@@ -86,93 +95,108 @@ func (h Host) now() time.Time {
return time.Now()
}
-// Spec is one probe launch.
+// live is the inputs read now.
+func (h Host) live(ctx context.Context) Inputs {
+ if h.Live != nil {
+ return h.Live(ctx)
+ }
+ return h.Inputs
+}
+
+// procArgs reads pid's KERN_PROCARGS2 outside the sandbox.
+func (h Host) procArgs(pid int) ([]byte, error) {
+ if h.ProcArgs != nil {
+ return h.ProcArgs(pid)
+ }
+ return ProcArgs(pid)
+}
+
+// Spec is one probe launch. Protected execution evidence (the
+// controller's ruling, fix round 1): the model is the actor, so nothing
+// it can write or say counts. The one Bash command the launch's
+// permission tool allows is Command, the runner's script with this run's
+// nonce, and only while the script's bytes hash to ScriptSHA256. The
+// script lies in a directory outside the worktree and the scratch, which
+// no sandboxed command and no native write can reach; it records into
+// the launch's scratch, which native writes cannot reach and only the
+// script's Bash writes.
type Spec struct {
Launch string
// Xcode: the sandboxed-Xcode settings (launch B); else no Xcode.
Xcode bool
// Tree is the probe tree, the launch's worktree (a real path).
Tree string
- // Prompt asks the model to run the launch's script (and in A to make
- // the native tool calls); Limit bounds the launch.
+ // Scratch is the launch's scratch (TMPDIR), where only the script
+ // writes; Script the probe script, ScriptSHA256 its digest, Nonce this
+ // run's argument (Command).
+ Scratch, Script, ScriptSHA256, Nonce string
+ // Prompt asks the model to run Command (and in A to make the native
+ // tool calls); Limit bounds the launch.
Prompt string
Limit time.Duration
}
-// Ask is one permission request the runner's tool answered.
-type Ask struct {
- Tool string
- Input json.RawMessage
- Allowed bool
-}
+// Command is the one Bash command a probe launch may run.
+func (s Spec) Command() string { return "bash " + s.Script + " " + s.Nonce }
-// path is the file or directory a native tool's request names.
-func (a Ask) path() string {
+// Permit is whether the probe launch's permission tool may allow a
+// request its Engineering rules allow: Bash only as Command, with the
+// script unchanged; a native write only inside the tree.
+func (s Spec) Permit(tool string, input json.RawMessage) bool {
var in struct {
- FilePath string `json:"file_path"`
- Path string `json:"path"`
+ Command string `json:"command"`
+ FilePath string `json:"file_path"`
+ NotebookPath string `json:"notebook_path"`
}
- _ = json.Unmarshal(a.Input, &in)
- if in.FilePath != "" {
- return in.FilePath
+ if json.Unmarshal(input, &in) != nil {
+ return false
}
- return in.Path
-}
-
-// ranScript: the runner's permission tool was asked for, and allowed,
-// exactly the launch's script in Bash. On a token connection the CLI asks
-// for every Bash command (its own approval is off), so a launch whose
-// model never ran the script, and wrote the tree itself, is caught here.
-func ranScript(asks []Ask, script string) bool {
- for _, q := range asks {
- var in struct {
- Command string `json:"command"`
- }
- if q.Tool == "Bash" && q.Allowed && json.Unmarshal(q.Input, &in) == nil && strings.TrimSpace(in.Command) == "bash "+script {
- return true
+ switch tool {
+ case "Bash":
+ if in.Command != s.Command() || s.Script == "" {
+ return false
}
+ b, ok := readFile(s.Script, 1<<20)
+ sum := sha256.Sum256(b)
+ return ok && hex.EncodeToString(sum[:]) == s.ScriptSHA256
+ case "Write", "Edit", "MultiEdit", "NotebookEdit":
+ p := filepath.Clean(firstNonEmpty(in.FilePath, in.NotebookPath))
+ return s.Tree != "" && strings.HasPrefix(p, s.Tree+"/")
}
- return false
+ return true
}
-// wroteRecords: the runner's tool saw the model ask to write or edit a
-// path in the tree other than F6's own (its notes, out/f6-*, and the
-// links it is told to write through, f6/), which only the script writes.
-func wroteRecords(asks []Ask, tree string) bool {
- for _, q := range asks {
- p := filepath.Clean(q.path())
- if (q.Tool == "Write" || q.Tool == "Edit") && strings.HasPrefix(p, tree+"/") && !strings.HasPrefix(p, filepath.Join(tree, "out", "f6-")) && !strings.HasPrefix(p, filepath.Join(tree, "f6")+"/") {
- return true
- }
- }
- return false
+// Observer is what the runner sees of a probe launch while it runs.
+type Observer struct {
+ // Ask hears each answer of the runner's permission tool, before the
+ // CLI acts on it.
+ Ask func(Ask)
+ // Started is the CLI's process once its group is on record.
+ Started func(pid int)
+ // Copy is the connection's runtime copy, before the CLI starts.
+ Copy func(dir string) error
+ // Event is each frame of the CLI's stream.
+ Event func(frame []byte)
}
-// judged is a launch's probes unless its script was not shown run, or
-// the model wrote the script's records: then no success verdict stands,
-// and each failure says why first.
-func judged(probes []wire.Probe, asks []Ask, tree, script string) []wire.Probe {
- switch {
- case !ranScript(asks, filepath.Join(tree, script)):
- return notRun(probes, "the probe script was not shown run")
- case wroteRecords(asks, tree):
- return notRun(probes, "the model wrote the probe's records")
- }
- return probes
+// Ask is one permission request the runner's tool answered.
+type Ask struct {
+ Tool string
+ ToolUseID string
+ Input json.RawMessage
+ Allowed bool
}
-// notRun marks probes for why: no success verdict stands, and each
-// failure says why first.
-func notRun(probes []wire.Probe, why string) []wire.Probe {
- for i, p := range probes {
- switch p.Verdict {
- case wire.EngineeringProbeSuccess(p.ID):
- probes[i].Verdict, probes[i].Detail = wire.ProbeFailed, why
- case wire.ProbeFailed:
- probes[i].Detail = clean(why + "; " + p.Detail)
- }
+// path is the file or directory a native tool's request names.
+func (a Ask) path() string { return inputPath(a.Input) }
+
+func inputPath(raw json.RawMessage) string {
+ var in struct {
+ FilePath string `json:"file_path"`
+ Path string `json:"path"`
}
- return probes
+ _ = json.Unmarshal(raw, &in)
+ return filepath.Clean(firstNonEmpty(in.FilePath, in.Path))
}
// Outcome is how a probe launch ended: whether the CLI started, whether
@@ -184,9 +208,12 @@ type Outcome struct {
}
// Run runs the launches due now (Due) in one OpProbe turn, keeping each
-// result, and returns them. A launch the turn could not be taken for, or
-// that could not start, is undecided: tried again after Retry.
+// result, and returns them. Each launch's inputs are read afresh before
+// it and again after it: a launch they changed under is undecided. A
+// launch the turn could not be taken for, or that could not start, is
+// undecided too: tried again after Retry.
func (s *Store) Run(ctx context.Context, h Host) []Result {
+ h.Inputs = h.live(ctx)
due := s.Due(h.Inputs, h.now(), h.P2Denied)
if len(due) == 0 {
return nil
@@ -202,6 +229,7 @@ func (s *Store) Run(ctx context.Context, h Host) []Result {
}
defer give()
for _, l := range due {
+ h.Inputs = h.live(ctx)
at := h.now()
s.try(l, h.Inputs, at)
var probes []wire.Probe
@@ -214,6 +242,9 @@ func (s *Store) Run(ctx context.Context, h Host) []Result {
probes = launchC(ctx, h)
}
r := Result{Launch: l, Inputs: h.Inputs, At: at, Probes: probes}
+ if h.live(context.WithoutCancel(ctx)).changed(h.Inputs) != "" {
+ r.Probes = undecided(l, h, "the inputs changed while it ran").Probes
+ }
s.Put(r)
out = append(out, r)
if ctx.Err() != nil {
@@ -254,17 +285,16 @@ func launched(l string, o Outcome) []wire.Probe {
return nil
}
-// tree is one launch's probe tree: a fresh 0700 directory at its real
-// path under the scratch root. planted are the paths the runner put
-// there itself, which the search skips.
-type tree struct {
- root string
- // planted maps each to what the runner wrote (nil for a link): a
- // planted file that no longer holds it is searched like any other.
- planted map[string][]byte
+// launchDir is one launch's places, all fresh and the runner's: the tree
+// (the worktree), run (the scratch, where only the script writes) and bin
+// (the script and the runner's lists for it, which nothing in the launch
+// can write).
+type launchDir struct {
+ root, run, bin string
+ t *tree
}
-func newTree(scratch string) (*tree, error) {
+func newLaunchDir(scratch string) (*launchDir, error) {
if err := os.MkdirAll(scratch, 0o700); err != nil {
return nil, err
}
@@ -272,23 +302,216 @@ func newTree(scratch string) (*tree, error) {
if err != nil {
return nil, err
}
- real, err := filepath.EvalSymlinks(dir)
+ root, err := filepath.EvalSymlinks(dir)
if err != nil {
os.RemoveAll(dir)
return nil, err
}
- t := &tree{root: real, planted: map[string][]byte{}}
- if err := os.Mkdir(t.path("out"), 0o700); err != nil {
- t.remove()
- return nil, err
+ d := &launchDir{root: root, run: filepath.Join(root, "run"), bin: filepath.Join(root, "bin"), t: &tree{root: filepath.Join(root, "tree"), planted: map[string][]byte{}}}
+ for _, p := range []string{d.t.root, d.run, d.bin} {
+ if err := os.Mkdir(p, 0o700); err != nil {
+ d.remove()
+ return nil, err
+ }
}
- return t, nil
+ return d, nil
}
-func (t *tree) path(rel string) string { return filepath.Join(t.root, rel) }
+// remove deletes the launch's places whole (nothing is kept).
+func (d *launchDir) remove() { os.RemoveAll(d.root) }
+
+// spec is the launch's Spec with its script written (0500, in bin).
+func (d *launchDir) spec(l, script string, xcode bool) (Spec, error) {
+ path := filepath.Join(d.bin, "probe-"+strings.ToLower(l)+".sh")
+ if err := os.WriteFile(path, []byte(script), 0o500); err != nil {
+ return Spec{}, err
+ }
+ sum := sha256.Sum256([]byte(script))
+ return Spec{Launch: l, Xcode: xcode, Tree: d.t.root, Scratch: d.run, Script: path, ScriptSHA256: hex.EncodeToString(sum[:]), Nonce: nonce()}, nil
+}
+
+// list writes one of the runner's lists for the script.
+func (d *launchDir) list(name string, lines []string) error {
+ body := strings.Join(lines, "\n")
+ if body != "" {
+ body += "\n"
+ }
+ return os.WriteFile(filepath.Join(d.bin, name), []byte(body), 0o600)
+}
+
+// read is what the script recorded under run/out.
+func (d *launchDir) read(name string) string {
+ b, _ := readFile(filepath.Join(d.run, "out", name), 1<<20)
+ return string(b)
+}
-// remove deletes the tree whole (it is never kept).
-func (t *tree) remove() { os.RemoveAll(t.root) }
+// find searches the tree and the scratch (where[rel] = "tree" or
+// "scratch").
+func (d *launchDir) find(needles map[string][][]byte) (map[string][]string, bool) {
+ hits, whole := d.t.find(needles)
+ run := &tree{root: d.run, planted: map[string][]byte{}}
+ rh, rwhole := run.find(needles)
+ for k, files := range rh {
+ for _, f := range files {
+ hits[k] = append(hits[k], "scratch:"+f)
+ }
+ }
+ return hits, whole && rwhole
+}
+
+// where splits found files into the scratch's (the script's) and the
+// tree's, by base name.
+func where(files []string) (scratch, inTree []string) {
+ for _, f := range files {
+ if rest, ok := strings.CutPrefix(f, "scratch:"); ok {
+ scratch = append(scratch, filepath.Base(rest))
+ } else {
+ inTree = append(inTree, filepath.Base(f))
+ }
+ }
+ return scratch, inTree
+}
+
+// evidence is what the runner saw of a launch: its tool's answers, the
+// CLI's tool events, the CLI's pid.
+type evidence struct {
+ mu sync.Mutex
+ asks []Ask
+ uses []*toolUse
+ ids map[string]*toolUse
+ pid int
+}
+
+// toolUse is one tool call as the CLI's own stream reports it: its
+// tool_use, and its tool_result once that comes.
+type toolUse struct {
+ ID, Tool string
+ Input json.RawMessage
+ Done, Error bool
+ Text string
+}
+
+func (e *evidence) ask(q Ask) { e.mu.Lock(); e.asks = append(e.asks, q); e.mu.Unlock() }
+
+func (e *evidence) started(pid int) { e.mu.Lock(); e.pid = pid; e.mu.Unlock() }
+
+// event reads one frame of the CLI's stream: an assistant message's
+// tool_use blocks and a user message's tool_result blocks. Anything else
+// (model text among it) is not evidence and is ignored.
+func (e *evidence) event(frame []byte) {
+ var f struct {
+ Type string `json:"type"`
+ Message struct {
+ Content []struct {
+ Type string `json:"type"`
+ ID string `json:"id"`
+ Name string `json:"name"`
+ Input json.RawMessage `json:"input"`
+ ToolUseID string `json:"tool_use_id"`
+ IsError bool `json:"is_error"`
+ Content json.RawMessage `json:"content"`
+ } `json:"content"`
+ } `json:"message"`
+ }
+ if json.Unmarshal(frame, &f) != nil {
+ return
+ }
+ e.mu.Lock()
+ defer e.mu.Unlock()
+ if e.ids == nil {
+ e.ids = map[string]*toolUse{}
+ }
+ for _, c := range f.Message.Content {
+ switch {
+ case f.Type == "assistant" && c.Type == "tool_use" && c.ID != "":
+ u := &toolUse{ID: c.ID, Tool: c.Name, Input: c.Input}
+ e.uses = append(e.uses, u)
+ e.ids[c.ID] = u
+ case f.Type == "user" && c.Type == "tool_result" && e.ids[c.ToolUseID] != nil:
+ u := e.ids[c.ToolUseID]
+ u.Done, u.Error, u.Text = true, c.IsError, resultText(c.Content)
+ }
+ }
+}
+
+// resultText is a tool_result's content: a string, or its text blocks.
+func resultText(raw json.RawMessage) string {
+ var s string
+ if json.Unmarshal(raw, &s) == nil {
+ return s
+ }
+ var blocks []struct {
+ Text string `json:"text"`
+ }
+ _ = json.Unmarshal(raw, &blocks)
+ var b strings.Builder
+ for _, x := range blocks {
+ b.WriteString(x.Text)
+ }
+ return b.String()
+}
+
+func (e *evidence) observer() Observer {
+ return Observer{Ask: e.ask, Started: e.started, Event: e.event}
+}
+
+// judged is a launch's probes unless the evidence does not hold: the
+// runner's tool never allowed Command, it allowed some other Bash
+// command, or the scratch does not hold this run's begin and end. Then no
+// success verdict stands, and each failure says why first.
+func (e *evidence) judged(probes []wire.Probe, s Spec, d *launchDir) []wire.Probe {
+ return e.judgedEnd(probes, s, d, true)
+}
+
+// judgedEnd is judged; with end false the script's end is not required
+// (launch C is cancelled by design while its script waits).
+func (e *evidence) judgedEnd(probes []wire.Probe, s Spec, d *launchDir, end bool) []wire.Probe {
+ e.mu.Lock()
+ ran, other := false, false
+ for _, q := range e.asks {
+ var in struct {
+ Command string `json:"command"`
+ }
+ _ = json.Unmarshal(q.Input, &in)
+ if q.Tool == "Bash" && q.Allowed {
+ ran, other = ran || in.Command == s.Command(), other || in.Command != s.Command()
+ }
+ }
+ e.mu.Unlock()
+ switch {
+ case !ran:
+ return notRun(probes, "the probe script was not shown run")
+ case other:
+ return notRun(probes, "a Bash command other than the probe script was allowed")
+ case strings.TrimSpace(d.read("begin")) != "begin "+s.Nonce || end && strings.TrimSpace(d.read("end")) != "end "+s.Nonce:
+ return notRun(probes, "the script's records are not this run's")
+ }
+ return probes
+}
+
+// notRun marks probes for why: no success verdict stands, and each
+// failure says why first.
+func notRun(probes []wire.Probe, why string) []wire.Probe {
+ for i, p := range probes {
+ switch p.Verdict {
+ case wire.EngineeringProbeSuccess(p.ID):
+ probes[i].Verdict, probes[i].Detail = wire.ProbeFailed, why
+ case wire.ProbeFailed:
+ probes[i].Detail = clean(why + "; " + p.Detail)
+ }
+ }
+ return probes
+}
+
+// tree is the launch's worktree. planted maps each path the runner put
+// there to what it wrote (nil for a link): a planted file that no longer
+// holds it is searched like any other.
+type tree struct {
+ root string
+ planted map[string][]byte
+}
+
+func (t *tree) path(rel string) string { return filepath.Join(t.root, rel) }
// plant writes a file the runner owns in the tree.
func (t *tree) plant(rel string, body []byte, mode os.FileMode) error {
@@ -303,13 +526,6 @@ func (t *tree) plant(rel string, body []byte, mode os.FileMode) error {
// mark notes a path the runner made some other way (a link).
func (t *tree) mark(rel string) string { p := t.path(rel); t.planted[p] = nil; return p }
-// read is rel's contents, at most 1 MiB, never through a link and never
-// blocking on a pipe; "" when it is not a regular file.
-func (t *tree) read(rel string) string {
- b, _ := readFile(t.path(rel), 1<<20)
- return string(b)
-}
-
func readFile(p string, max int64) ([]byte, bool) {
info, err := os.Lstat(p)
if err != nil || !info.Mode().IsRegular() {
diff --git a/internal/runner/mac/fprobe/testdata/synthetic-2026-11-29-tito-studio-launch-a.json b/internal/runner/mac/fprobe/testdata/synthetic-2026-11-29-tito-studio-launch-a.json
index 5b488788..0fa1a20a 100644
--- a/internal/runner/mac/fprobe/testdata/synthetic-2026-11-29-tito-studio-launch-a.json
+++ b/internal/runner/mac/fprobe/testdata/synthetic-2026-11-29-tito-studio-launch-a.json
@@ -2,7 +2,7 @@
"recorded": "SYNTHETIC, not recorded on a Mac",
"machine": "Tito Studio (macOS 27.2, M5 Ultra, Xcode 27.2 27B52), as the runner user paulequipo",
"date": "2026-11-29",
- "why": "What launch A's script would record if Claude Code 2.1.312's sandbox holds under the no-Xcode Engineering settings, written from the spec and task 1's findings. Task 18 replaces it with the first real run.",
+ "why": "What launch A's protected script would record in the launch's scratch if Claude Code 2.1.312's sandbox holds under the no-Xcode Engineering settings, written from the spec and task 1's findings (revised 2026-11-29 for fix round 1: the direct KERN_PROCARGS2 reader and the descriptor list). PID stands for the CLI's pid the runner observed. Task 18 replaces it with the first real run.",
"codes": {
"tcp": "1",
"https": "56",
@@ -11,25 +11,24 @@
"cat": "1",
"cp": "1",
"ln": "1",
- "ls": "1",
"ln6": "1",
"env": "0",
"ppid": "0",
"ps": "0",
- "procargs": "3",
+ "procargs": "1",
"launchctl": "0",
- "fd": "0",
"xcodebuild": "74",
"simctl": "1",
- "mach": "0"
+ "mach": "0",
+ "fds": "0"
},
"files": {
"out/f3.env": "PATH=/usr/bin:/bin:/usr/sbin:/sbin\nHOME=/Users/paulequipo\nTMPDIR=/Users/paulequipo/.local/state/equipo-runner/scratch/policy-123\nCLAUDE_CODE_OAUTH_TOKEN_FILE_DESCRIPTOR=3\nSANDBOX_RUNTIME=1\n",
"out/f3.ppid": " PID TTY TIME CMD\n41234 ?? 0:00.01 /bin/zsh -c bash probe.sh\n",
"out/f3.ps": " PID TTY TIME CMD\n41200 ?? 0:02.10 /Users/paulequipo/.local/lib/equipo-runner/claude/claude -p --model claude-haiku-5-5 CLAUDE_CODE_OAUTH_TOKEN_FILE_DESCRIPTOR=3 EQUIPO_ATTEMPT=fprobe-a\n41234 ?? 0:00.01 /bin/zsh -c bash probe.sh\n",
"out/f3.launchctl": "",
- "out/f3.fd": "0\n1\n2\n",
- "out/f3.fdtype": "/dev/fd/0 Character Device\n/dev/fd/1 Fifo\n/dev/fd/2 Fifo\n",
- "out/f7.mach": "none\n"
+ "out/f7.mach": "none\n",
+ "out/f3.procargs": "procargs-start PID\nkern.procargs2: operation not permitted\n",
+ "out/f3.fds": "fd 0 char\nfd 1 file\nfd 2 file\nfds-done\n"
}
}
diff --git a/internal/runner/mac/fprobe/testdata/synthetic-2026-11-29-tito-studio-launch-b.log b/internal/runner/mac/fprobe/testdata/synthetic-2026-11-29-tito-studio-launch-b.log
index 2721a71e..b5cd4675 100644
--- a/internal/runner/mac/fprobe/testdata/synthetic-2026-11-29-tito-studio-launch-b.log
+++ b/internal/runner/mac/fprobe/testdata/synthetic-2026-11-29-tito-studio-launch-b.log
@@ -1,13 +1,19 @@
# SYNTHETIC, not recorded on a Mac: what F5's out/f5.log would hold on
# Tito Studio (macOS 27.2, Xcode 27.2 27B52, iPhone 17 Pro on iOS 27.2) if
# the sandboxed-Xcode settings hold. Written 2026-11-29 from P2's fixture;
-# task 18 replaces it with the first real run.
+# Revised 2026-11-29 (fix round 1): one line per token source. Task 18
+# replaces it with the first real run.
EQUIPO-PROBE script state denied
EQUIPO-PROBE script home denied
EQUIPO-PROBE script tcp denied
EQUIPO-PROBE script dns denied
EQUIPO-PROBE script keychain denied
-EQUIPO-PROBE script token denied
+EQUIPO-PROBE script tokenfile denied
+EQUIPO-PROBE script tokenlink denied
+EQUIPO-PROBE script tokenenv denied
+EQUIPO-PROBE script tokenargs denied
+EQUIPO-PROBE script tokenlaunchd denied
+EQUIPO-PROBE script tokenfd denied
** BUILD SUCCEEDED **
EQUIPO-PHASE script-build 0
resolved source packages:
@@ -17,7 +23,12 @@ warning: EQUIPO-PROBE plugin home denied
warning: EQUIPO-PROBE plugin tcp denied
warning: EQUIPO-PROBE plugin dns denied
warning: EQUIPO-PROBE plugin keychain denied
-warning: EQUIPO-PROBE plugin token denied
+warning: EQUIPO-PROBE plugin tokenfile denied
+warning: EQUIPO-PROBE plugin tokenlink denied
+warning: EQUIPO-PROBE plugin tokenenv denied
+warning: EQUIPO-PROBE plugin tokenargs denied
+warning: EQUIPO-PROBE plugin tokenlaunchd denied
+warning: EQUIPO-PROBE plugin tokenfd denied
** TEST BUILD SUCCEEDED **
EQUIPO-PHASE test-build 0
Device already booted, nothing to do.
@@ -27,6 +38,11 @@ EQUIPO-PROBE test home denied
EQUIPO-PROBE test tcp denied
EQUIPO-PROBE test dns denied
EQUIPO-PROBE test keychain denied
-EQUIPO-PROBE test token denied
+EQUIPO-PROBE test tokenfile denied
+EQUIPO-PROBE test tokenlink denied
+EQUIPO-PROBE test tokenenv denied
+EQUIPO-PROBE test tokenargs denied
+EQUIPO-PROBE test tokenlaunchd denied
+EQUIPO-PROBE test tokenfd denied
** TEST EXECUTE SUCCEEDED **
EQUIPO-PHASE test-run 0
diff --git a/internal/runner/mac/p2token_test.go b/internal/runner/mac/p2token_test.go
index fccd5eac..77fa3b49 100644
--- a/internal/runner/mac/p2token_test.go
+++ b/internal/runner/mac/p2token_test.go
@@ -11,13 +11,16 @@ import (
"amadan.net/oficina/equipo/internal/wire"
)
-// P2 gains F3's token sources (slice F task 14): every hostile place
-// tries the token where a connection keeps it, the environment, its own
-// processes' environments, the CLI's and launchd's, and says whether a
-// token came back. P2 is denied only when each place's token attempt is
-// denied, the sentinel token was really planted (a control, as DNS and
-// the Keychain have), and the line is there (a missing line is not a
-// denial).
+// The token sources each hostile place tries (P2 and F5; slice F task
+// 14, fix round 1 #4), one attempt per source so a collector that could
+// not run is a missing line, never a denial: the token file by path, a
+// hard link of it, the environment, KERN_PROCARGS2 of every own process
+// (the shell through the runner's direct reader), launchd's environment,
+// and every open descriptor.
+var tokenSources = []string{"tokenfile", "tokenlink", "tokenenv", "tokenargs", "tokenlaunchd", "tokenfd"}
+
+// P2 is denied only when every place's every token source says denied,
+// the sentinel token was planted (the control), and no line is missing.
func TestP2TriesTheToken(t *testing.T) {
got := ParseAttempts(allLines("denied")["script"] + allLines("denied")["plugin"] + allLines("denied")["test"])
facts := P2Facts{Home: true, DNS: true, Keychain: true, Token: true, Accepted: map[string]bool{}}
@@ -25,35 +28,58 @@ func TestP2TriesTheToken(t *testing.T) {
t.Fatalf("all denied: %s %v", v, g)
}
facts.Token = false
- if v, g := JudgeP2(got, facts); v != wire.ProbeFailed || len(g["unknown"]) != 3 || !strings.HasSuffix(g["unknown"][0], ".token") {
+ if v, g := JudgeP2(got, facts); v != wire.ProbeFailed || len(g["unknown"]) != 3*len(tokenSources) {
t.Fatalf("the sentinel token was not planted, so denied proves nothing: %s %v", v, g)
}
facts.Token = true
- delete(got, "plugin.token")
- if v, g := JudgeP2(got, facts); v != wire.ProbeFailed || len(g["unknown"]) != 1 || g["unknown"][0] != "plugin.token" {
- t.Fatalf("a missing token line: %s %v", v, g)
+ for _, src := range tokenSources {
+ delete(got, "plugin."+src)
+ if v, g := JudgeP2(got, facts); v != wire.ProbeFailed || len(g["unknown"]) != 1 || g["unknown"][0] != "plugin."+src {
+ t.Fatalf("a source not collected (%s): %s %v", src, v, g)
+ }
+ got["plugin."+src] = "denied"
}
// The run: the test place reads the token file the probe planted in
// the accounts root (outside any sandbox here) and says so.
f := newProbeFixture(t, allLines("denied"), "FAKE_READ_TOKEN=1")
caps := Capabilities(context.Background(), f.h.Exec, f.h.Tools)
- if p, _, _ := probeP2(context.Background(), f.h, caps); p.Verdict != wire.ProbeFailed || !strings.Contains(p.Detail, "allowed: test.token") {
+ if p, _, _ := probeP2(context.Background(), f.h, caps); p.Verdict != wire.ProbeFailed || !strings.Contains(p.Detail, "allowed: test.tokenfile") {
t.Fatalf("token read: %+v", p)
}
if left, _ := filepath.Glob(filepath.Join(f.h.Paths.AccountsRoot, "*")); len(left) != 0 {
t.Fatalf("the sentinel token was left: %v", left)
}
- // Without an accounts root nothing is planted, and nothing is
- // written anywhere else: denied lines prove nothing.
f = newProbeFixture(t, allLines("denied"))
f.h.Paths.AccountsRoot = ""
- if p, _, _ := probeP2(context.Background(), f.h, caps); p.Verdict != wire.ProbeFailed || !strings.Contains(p.Detail, "not shown denied: script.token plugin.token test.token") {
+ if p, _, _ := probeP2(context.Background(), f.h, caps); p.Verdict != wire.ProbeFailed || !strings.Contains(p.Detail, "not shown denied") {
t.Fatalf("no accounts root: %+v", p)
}
+ // The targets name the runner's binary, the direct reader.
+ f = newProbeFixture(t, allLines("denied"))
+ f.h.Scratch, f.h.Runner = filepath.Join(f.dir, "scratch"), "/opt/equipo-runner"
+ targets := ""
+ f.h.Gate = func(sandboxed bool) *Gate {
+ g := &Gate{Env: []string{"PATH=/usr/bin:/bin"}, Lines: 200, Sandbox: wire.SandboxNone}
+ g.Watch = func(string) {}
+ return g
+ }
+ inner := f.h.Exec
+ f.h.Exec = func(ctx context.Context, name string, args ...string) (string, error) {
+ if m, _ := filepath.Glob(filepath.Join(f.h.Scratch, "probe-*", "hostile", "equipo-targets.txt")); len(m) == 1 && targets == "" {
+ raw, _ := os.ReadFile(m[0])
+ targets = string(raw)
+ }
+ return inner(ctx, name, args...)
+ }
+ probeP2(context.Background(), f.h, caps)
+ if !strings.Contains(targets, "helper=/opt/equipo-runner\n") {
+ t.Fatalf("targets %q", targets)
+ }
- // The shipped script phase really tries the sources: run as it is,
- // outside any sandbox (Linux), it finds the planted token by path.
+ // The shipped script phase really tries each source: run as it is,
+ // outside any sandbox (Linux), with a stand-in for the runner's
+ // reader. A source whose collector cannot run says nothing.
bash, err := exec.LookPath("bash")
if err != nil {
t.Skip("no bash")
@@ -62,41 +88,72 @@ func TestP2TriesTheToken(t *testing.T) {
if err != nil {
t.Fatal(err)
}
- accounts := t.TempDir()
+ dir := t.TempDir()
token := "sk-ant-oat01-probe-0123456789abcdef"
- if err := os.WriteFile(filepath.Join(accounts, ".oauth-token"), []byte(token), 0600); err != nil {
+ if err := os.WriteFile(filepath.Join(dir, ".oauth-token"), []byte(token), 0600); err != nil {
t.Fatal(err)
}
- run := func(targets string) string {
+ helper := filepath.Join(dir, "helper")
+ // The stand-in reads only the hostile shell (its caller's parent, past
+ // the command substitution): this box's other processes are not ours.
+ if err := os.WriteFile(helper, []byte("#!/bin/bash\nmode=$2; shift 2\ncase \"$mode\" in procargs) pp=$(ps -o ppid= -p $PPID | tr -d ' '); for p in \"$@\"; do echo \"procargs-start $p\"; if { [ \"$p\" = \"$PPID\" ] || [ \"$p\" = \"$pp\" ]; } && tr '\\0' '\\n' < /proc/$p/environ; then echo \"procargs-end $p ok\"; else echo \"procargs-end $p refused\"; fi; done ;; fds) for f in /proc/self/fd/*; do echo \"fd ${f##*/} file\"; done; echo fds-done ;; *) exit 2 ;; esac\n"), 0700); err != nil {
+ t.Fatal(err)
+ }
+ run := func(targets string, env ...string) map[string]string {
t.Helper()
if err := os.WriteFile(filepath.Join(root, "equipo-targets.txt"), []byte(targets), 0600); err != nil {
t.Fatal(err)
}
cmd := exec.Command(bash, filepath.Join(root, "project", "hostile.sh"))
- cmd.Env = []string{"PATH=/usr/bin:/bin", "SRCROOT=" + filepath.Join(root, "project")}
+ cmd.Env = append([]string{"PATH=/usr/bin:/bin", "SRCROOT=" + filepath.Join(root, "project"), "TMPDIR=" + t.TempDir()}, env...)
out, _ := cmd.CombinedOutput()
if strings.Contains(string(out), token) {
t.Fatalf("the script printed the token: %s", out)
}
- return string(out)
+ return ParseAttempts(string(out))
}
- base := "state=/nonexistent\ndns=example.invalid\nkeychain=io.amadan.equipo.probe.x\nport_script=1\n"
- if out := run(base + "token=" + token + "\ntoken_file=" + filepath.Join(accounts, ".oauth-token") + "\n"); ParseAttempts(out)["script.token"] != "allowed" {
- t.Fatalf("the script did not find the token it could read: %s", out)
+ base := "state=/nonexistent\ndns=example.invalid\nkeychain=io.amadan.equipo.probe.x\nport_script=1\ntoken=" + token + "\n"
+ got = run(base + "token_file=" + filepath.Join(dir, ".oauth-token") + "\nhelper=" + helper + "\n")
+ for src, want := range map[string]string{"tokenfile": "allowed", "tokenlink": "allowed", "tokenenv": "denied", "tokenargs": "denied", "tokenfd": "denied"} {
+ if got["script."+src] != want {
+ t.Fatalf("%s: %q, want %s (%v)", src, got["script."+src], want, got)
+ }
}
- if out := run(base + "token=" + token + "\ntoken_file=" + filepath.Join(accounts, "missing") + "\n"); ParseAttempts(out)["script.token"] != "denied" {
- t.Fatalf("the script found a token it could not read: %s", out)
+ if _, ok := got["script.tokenlaunchd"]; ok {
+ t.Fatalf("launchctl is not here, so launchd's environment cannot be shown: %v", got)
}
- // Every hostile part tries the token.
+ if got = run(base+"token_file="+filepath.Join(dir, ".oauth-token")+"\nhelper="+helper+"\n", "CLAUDE_CODE_OAUTH_TOKEN="+token); got["script.tokenenv"] != "allowed" || got["script.tokenargs"] != "allowed" {
+ t.Fatalf("the token in the environment: %v", got)
+ }
+ got = run(base + "token_file=" + filepath.Join(dir, "missing") + "\nhelper=" + filepath.Join(dir, "no-helper") + "\n")
+ if got["script.tokenfile"] != "denied" || got["script.tokenlink"] != "denied" {
+ t.Fatalf("a token file it could not read: %v", got)
+ }
+ for _, src := range []string{"tokenargs", "tokenfd"} {
+ if _, ok := got["script."+src]; ok {
+ t.Fatalf("%s said without its reader: %v", src, got)
+ }
+ }
+ // A reader the kernel refused for the shell itself (its control)
+ // shows no process's environment: no line.
+ refusing := filepath.Join(dir, "refusing")
+ if err := os.WriteFile(refusing, []byte("#!/bin/bash\nmode=$2; shift 2\ncase \"$mode\" in procargs) for p in \"$@\"; do echo \"procargs-start $p\"; echo \"procargs-end $p refused\"; done; exit 1 ;; fds) echo fds-done ;; esac\n"), 0700); err != nil {
+ t.Fatal(err)
+ }
+ if got = run(base + "token_file=" + filepath.Join(dir, ".oauth-token") + "\nhelper=" + refusing + "\n"); got["script.tokenargs"] != "" {
+ t.Fatalf("tokenargs said though the reader read nothing: %v", got)
+ }
+ // Every hostile part tries every source, the Swift parts by
+ // KERN_PROCARGS2 and posix_spawn (no Process on iOS).
for _, file := range []string{"package/Plugins/HostilePlugin/HostilePlugin.swift", "package/Tests/HostileTests/HostileTests.swift", "project/hostile.sh"} {
raw, _ := os.ReadFile(filepath.Join(root, file))
- for _, source := range []string{"token_file", "launchctl", "-wwE", "KERN_PROCARGS2"} {
- if file == "project/hostile.sh" && source == "KERN_PROCARGS2" {
- continue // the shell reads it through ps -wwE
- }
- if !strings.Contains(string(raw), source) {
- t.Fatalf("%s does not try %s", file, source)
+ for _, src := range tokenSources {
+ if !strings.Contains(string(raw), `"`+src+`"`) && !strings.Contains(string(raw), "say "+src) && !strings.Contains(string(raw), "src "+src) {
+ t.Fatalf("%s does not try %s", file, src)
}
}
+ if strings.HasSuffix(file, ".swift") && (!strings.Contains(string(raw), "KERN_PROCARGS2") || !strings.Contains(string(raw), "posix_spawn") || strings.Contains(string(raw), "#if os(macOS)\n sources")) {
+ t.Fatalf("%s: the reader and launchctl on every platform", file)
+ }
}
}
diff --git a/internal/runner/mac/p2why_test.go b/internal/runner/mac/p2why_test.go
index 1665986a..4a47d46b 100644
--- a/internal/runner/mac/p2why_test.go
+++ b/internal/runner/mac/p2why_test.go
@@ -83,7 +83,7 @@ func TestP2SaysWhichStepFailed(t *testing.T) {
var w warned
f.h.Warn = w.warn
p, _, _ := probeP2(context.Background(), f.h, Capabilities(context.Background(), f.h.Exec, f.h.Tools))
- if p.Detail != "not shown denied: all 18 attempts; xcodebuild did not run in srt: srt start exit 1: Error: Refusing to run with the built-in defaults" || w.attr(0, "phase") != "srt start" {
+ if p.Detail != "not shown denied: all 33 attempts; xcodebuild did not run in srt: srt start exit 1: Error: Refusing to run with the built-in defaults" || w.attr(0, "phase") != "srt start" {
t.Fatalf("srt did not start: %+v %v", p, w.calls)
}
}
diff --git a/internal/runner/mac/probe.go b/internal/runner/mac/probe.go
index fcfd108c..2ea39a8b 100644
--- a/internal/runner/mac/probe.go
+++ b/internal/runner/mac/probe.go
@@ -37,11 +37,11 @@ type ProbeHost struct {
Exec Exec
Tools Tools
Paths Paths
- // Scratch holds the fixture copies (never the state dir: the
- // checks profile denies it, and the fixture is the tree).
- Scratch string
- UID int
- Version string
+ // Scratch holds the fixture copies (never the state dir, which the
+ // checks profile denies); Runner is the runner's binary (its reader).
+ Scratch, Runner string
+ UID int
+ Version string
// Gate is the gate the fixture runs under: sandboxed, srt with the
// checks profile; or bare.
Gate func(sandboxed bool) *Gate
@@ -258,16 +258,13 @@ func (h ProbeHost) said(tool string) string {
// noXcode and noSimulator say why a probe that needs Xcode or a
// simulator cannot run: a query that did not answer, or none found.
-func (h ProbeHost) noXcode() string {
- if why := h.said("xcodebuild"); why != "" {
- return "Xcode unavailable: " + why
- }
- return "no Xcode"
-}
+func (h ProbeHost) noXcode() string { return firstNonEmpty(h.gone("Xcode", "xcodebuild"), "no Xcode") }
+func (h ProbeHost) noSimulator() string { return h.gone("simulator", "simctl") }
-func (h ProbeHost) noSimulator() string {
- if why := h.said("simctl"); why != "" {
- return "simulator unavailable: " + why
+// gone is "<what> unavailable: <why>" when tool did not answer.
+func (h ProbeHost) gone(what, tool string) string {
+ if why := h.said(tool); why != "" {
+ return what + " unavailable: " + why
}
return ""
}
@@ -314,8 +311,8 @@ func ComputerName(ctx context.Context, x Exec) string {
// The places and attempts of the hostile fixture.
var (
probePlaces = []string{"script", "plugin", "test"}
- probeAttempts = []string{"state", "home", "tcp", "dns", "keychain", "token"}
- attemptLine = regexp.MustCompile(`EQUIPO-PROBE (script|plugin|test) (state|home|tcp|dns|keychain|token) (allowed|denied)\b`)
+ probeAttempts = []string{"state", "home", "tcp", "dns", "keychain", "tokenfile", "tokenlink", "tokenenv", "tokenargs", "tokenlaunchd", "tokenfd"}
+ attemptLine = regexp.MustCompile(`EQUIPO-PROBE (script|plugin|test) (state|home|tcp|dns|keychain|token(?:file|link|env|args|launchd|fd)) (allowed|denied)\b`)
)
// ParseAttempts reads the fixture's report lines: "place.attempt" to
@@ -361,7 +358,7 @@ func JudgeP2(got map[string]string, f P2Facts) (verdict string, groups map[strin
r = "allowed"
case r == "":
r = "unknown"
- case r == "denied" && what == "dns" && !f.DNS, r == "denied" && what == "keychain" && !f.Keychain, r == "denied" && what == "token" && !f.Token:
+ case r == "denied" && what == "dns" && !f.DNS, r == "denied" && what == "keychain" && !f.Keychain, r == "denied" && strings.HasPrefix(what, "token") && !f.Token:
r = "unknown"
case r == "denied" && what == "home" && f.HomeUnix:
r = "unix"
@@ -377,19 +374,22 @@ func JudgeP2(got map[string]string, f P2Facts) (verdict string, groups map[strin
return verdict, groups
}
-// p2Detail says what P2 found and whether the run's end was proven; why
-// is the short form of a failed srt run, last, so the capability
-// string's limit cuts it before the rest.
+// p2Detail says what P2 found (a place all of whose attempts are alike as
+// place.*) and whether the run's end was proven; why, a failed srt run's
+// short form, is last, so the capability string's limit cuts it first.
func p2Detail(groups map[string][]string, total int, srtRan, ended bool, why string) string {
var parts []string
for _, g := range []struct{ key, label string }{{"allowed", "allowed"}, {"unknown", "not shown denied"}, {"unix", "Unix permissions only"}} {
switch n := len(groups[g.key]); {
case n > 0 && n == total && n > len(probePlaces):
- // Every attempt alike (none reported, say): the count, which
- // leaves room for why.
+ // Every attempt alike: the count, which leaves room for why.
parts = append(parts, fmt.Sprintf("%s: all %d attempts", g.label, n))
case n > 0:
- parts = append(parts, g.label+": "+strings.Join(groups[g.key], " "))
+ list := " " + strings.Join(groups[g.key], " ") + " "
+ for _, p := range probePlaces {
+ list = strings.Replace(list, " "+p+"."+strings.Join(probeAttempts, " "+p+".")+" ", " "+p+".* ", 1)
+ }
+ parts = append(parts, g.label+":"+strings.TrimRight(list, " "))
}
}
if len(parts) == 0 {
@@ -480,7 +480,7 @@ func probeP2(ctx context.Context, h ProbeHost, caps wire.Capabilities) (wire.Pro
defer os.RemoveAll(tok)
facts.Token = os.MkdirAll(tok, 0700) == nil && os.WriteFile(filepath.Join(tok, ".oauth-token"), []byte("sk-ant-oat01-probe-"+secret), 0600) == nil
}
- targets = append(targets, "state="+sentinel, "token=sk-ant-oat01-probe-"+secret, "token_file="+filepath.Join(tok, ".oauth-token"))
+ targets = append(targets, "state="+sentinel, "token=sk-ant-oat01-probe-"+secret, "token_file="+filepath.Join(tok, ".oauth-token"), "helper="+h.Runner)
if home := otherHome(h.Paths.OtherHomes); home != "" {
facts.Home, facts.HomeUnix = true, !h.Exposed(home)
targets = append(targets, "home="+home)
diff --git a/internal/runner/mac/probe_test.go b/internal/runner/mac/probe_test.go
index 29e825e1..9c07e7d9 100644
--- a/internal/runner/mac/probe_test.go
+++ b/internal/runner/mac/probe_test.go
@@ -56,7 +56,7 @@ case "$*" in
[ -n "$FAKE_RUN_FAIL" ] && { echo "xcodebuild: error: Failed to establish communication with the test runner."; echo "** TEST EXECUTE FAILED **"; exit 65; }
t=../equipo-targets.txt
if [ -n "$FAKE_READ_STATE" ] && cat "$(sed -n 's/^state=//p' $t)" >/dev/null 2>&1; then echo "EQUIPO-PROBE test state allowed"; fi
- if [ -n "$FAKE_READ_TOKEN" ] && [ "$(cat "$(sed -n 's/^token_file=//p' $t)")" = "$(sed -n 's/^token=//p' $t)" ]; then echo "EQUIPO-PROBE test token allowed"; fi
+ if [ -n "$FAKE_READ_TOKEN" ] && [ "$(cat "$(sed -n 's/^token_file=//p' $t)")" = "$(sed -n 's/^token=//p' $t)" ]; then echo "EQUIPO-PROBE test tokenfile allowed"; fi
if [ -n "$FAKE_CONNECT" ]; then exec 3<>"/dev/tcp/127.0.0.1/$(sed -n 's/^port_test=//p' $t)"; fi
cat "$FAKE_DIR/test.out"; noise; echo "** TEST EXECUTE SUCCEEDED **"; exit 0 ;;
*testWait*) echo "EQUIPO-PROBE wait started"; exec sleep 600 ;;
@@ -75,7 +75,7 @@ func allLines(result string) map[string]string {
out := map[string]string{}
for _, place := range []string{"script", "plugin", "test"} {
var b strings.Builder
- for _, what := range []string{"state", "home", "tcp", "dns", "keychain", "token"} {
+ for _, what := range []string{"state", "home", "tcp", "dns", "keychain", "tokenfile", "tokenlink", "tokenenv", "tokenargs", "tokenlaunchd", "tokenfd"} {
b.WriteString("warning: EQUIPO-PROBE " + place + " " + what + " " + result + "\n")
}
out[place] = b.String()
@@ -243,7 +243,7 @@ func TestP2IsDeniedOnlyWhenEverythingIs(t *testing.T) {
func TestJudgeP2(t *testing.T) {
got := ParseAttempts(allLines("denied")["script"] + allLines("denied")["plugin"] + allLines("denied")["test"] + "EQUIPO-PROBE test dns allowed\n")
- if got["test.dns"] != "denied" || len(got) != 18 {
+ if got["test.dns"] != "denied" || len(got) != 33 {
t.Fatalf("the first line for an attempt counts: %v", got)
}
facts := P2Facts{Home: true, DNS: true, Keychain: true, Token: true, Accepted: map[string]bool{}}
diff --git a/internal/runner/thin/engineer.go b/internal/runner/thin/engineer.go
index d468a94d..706fe572 100644
--- a/internal/runner/thin/engineer.go
+++ b/internal/runner/thin/engineer.go
@@ -833,8 +833,13 @@ type specialistRun struct {
limit time.Duration
noLog bool
// probe is a shipped probe launch (mac_fprobe.go): it runs before the
- // Mac is ready, which it is there to prove.
- probe bool
+ // Mac is ready, which it is there to prove. Its scratch is the
+ // probe's (kept for the probe to read); copied sees the runtime copy
+ // before the CLI starts; tap sees each frame of the CLI's stream.
+ probe bool
+ scratch string
+ copied func(dir string) error
+ tap func(frame []byte)
// record keeps the namespace the run started in, against its own
// attempt (a step's, or a question's); nil records the step's.
record func(ctx context.Context, nsID string) error
diff --git a/internal/runner/thin/mac.go b/internal/runner/thin/mac.go
index 28ad83ec..17b903be 100644
--- a/internal/runner/thin/mac.go
+++ b/internal/runner/thin/mac.go
@@ -802,7 +802,12 @@ func (h *macHost) engineering() *WorkerEngineering {
return &WorkerEngineering{XcodeExec: &mac.Executor{Turns: h.turns, UserTemp: h.paths.UserTemp, QuietSimulators: h.quietSimulators}, DeveloperDir: dev, Leaks: h.leaks,
Xcode: func() bool {
r, ok := h.probes.trusted()
- return ok && r.Sandboxed() && h.eng.xcode() && h.paths.UserTemp != "" && !h.taint.Tainted()
+ if !ok || !r.Sandboxed() || h.paths.UserTemp == "" || h.taint.Tainted() {
+ return false
+ }
+ ctx, cancel := context.WithTimeout(context.Background(), 2*mac.QueryLimit)
+ defer cancel()
+ return h.eng.xcodeNow(ctx)
}}
}
diff --git a/internal/runner/thin/mac_fprobe.go b/internal/runner/thin/mac_fprobe.go
index 93a9a32c..72b89025 100644
--- a/internal/runner/thin/mac_fprobe.go
+++ b/internal/runner/thin/mac_fprobe.go
@@ -5,6 +5,7 @@ import (
"encoding/json"
"net"
"path/filepath"
+ "strconv"
"strings"
"sync"
"sync/atomic"
@@ -36,6 +37,67 @@ type macEngineering struct {
conns *Conns
caps func(context.Context) wire.Capabilities
last []wire.Probe
+ // live reads the capability report afresh; now is the clock.
+ live func(context.Context) wire.Capabilities
+ now func() time.Time
+}
+
+// readNow is the capability report read afresh, with the guards' status
+// and Unproven as credentialCaps says them now (never the hour-old report).
+func (e *macEngineering) readNow(ctx context.Context) wire.Capabilities {
+ live := e.live
+ if live == nil {
+ live = func(ctx context.Context) wire.Capabilities { return mac.Capabilities(ctx, e.h.run, e.h.tools) }
+ }
+ c := live(ctx)
+ if e.h.creds != nil {
+ e.h.credentialCaps(ctx, &c)
+ }
+ return c
+}
+
+func (e *macEngineering) clock() time.Time {
+ if e.now != nil {
+ return e.now()
+ }
+ return time.Now()
+}
+
+// statusNow is the Engineering status decided now, at each use (an
+// admission, every launch): the inputs read afresh and the results' age
+// now. WorkerEngineering.Status on a Mac.
+func (e *macEngineering) statusNow(ctx context.Context) *wire.EngineeringStatus {
+ c := e.readNow(ctx)
+ st, _ := e.decide(&c)
+ return &st
+}
+
+// xcodeNow is whether sandboxed Xcode access holds now: F5 denied for the
+// inputs read afresh and under a day old.
+func (e *macEngineering) xcodeNow(ctx context.Context) bool {
+ c := e.readNow(ctx)
+ _, probes := e.decide(&c)
+ return fprobe.XcodeAllowed(probes)
+}
+
+// probePermission is the probe launch's permission tool: the Engineering
+// rules (inner) and then the probe's own (Spec.Permit: Bash only as the
+// hashed script with this run's nonce, no native write outside the tree);
+// ask hears every answer.
+func probePermission(inner func(json.RawMessage, provider.Policy) json.RawMessage, s fprobe.Spec, ask func(fprobe.Ask)) func(json.RawMessage, provider.Policy) json.RawMessage {
+ return func(raw json.RawMessage, p provider.Policy) json.RawMessage {
+ out := inner(raw, p)
+ var q struct {
+ Tool string `json:"tool_name"`
+ ToolUseID string `json:"tool_use_id"`
+ Input json.RawMessage `json:"input"`
+ }
+ if json.Unmarshal(raw, &q) != nil || !denied(out) && !s.Permit(q.Tool, q.Input) {
+ out, _ = json.Marshal(map[string]string{"behavior": "deny", "message": "a probe launch runs only its own script"})
+ }
+ ask(fprobe.Ask{Tool: q.Tool, ToolUseID: q.ToolUseID, Input: q.Input, Allowed: !denied(out)})
+ return out
+ }
}
// fprobeEvery is how often the loop looks whether a launch is due.
@@ -93,10 +155,7 @@ func (e *macEngineering) compose(caps *wire.Capabilities) {
if e == nil {
return
}
- verified := caps.Harness.Claude != ""
- probes := e.store.Probes(fprobe.NewInputs(e.h.version, verified, caps.Xcode, caps.Simulators), time.Now(), e.p2())
- conn, why := e.conn(caps)
- st := fprobe.Status(fprobe.State{Guards: caps.Engineering, CLI: verified, Probes: probes, Conn: conn, ConnReason: why})
+ st, probes := e.decide(caps)
caps.Probes, caps.Engineering = append(caps.Probes, probes...), &st
if st.State == wire.EngineeringReady {
caps.Tags = append(caps.Tags, wire.TagClaude)
@@ -106,6 +165,15 @@ func (e *macEngineering) compose(caps *wire.Capabilities) {
e.mu.Unlock()
}
+// decide is the status and F1 to F7 for caps (its inputs, its guards'
+// status, its Unproven) and the connections, now.
+func (e *macEngineering) decide(caps *wire.Capabilities) (wire.EngineeringStatus, []wire.Probe) {
+ verified := caps.Harness.Claude != ""
+ probes := e.store.Probes(fprobe.NewInputs(e.h.version, verified, caps.Xcode, caps.Simulators), e.clock(), e.p2())
+ conn, why := e.conn(caps)
+ return fprobe.Status(fprobe.State{Guards: caps.Engineering, CLI: verified, Probes: probes, Conn: conn, ConnReason: why}), probes
+}
+
// xcode: F5 is denied as the newest capability report says it.
func (e *macEngineering) xcode() bool {
if e == nil {
@@ -170,8 +238,12 @@ func (e *macEngineering) host(ctx context.Context) (fprobe.Host, bool) {
}
}
return fprobe.Host{
- Inputs: fprobe.NewInputs(h.version, caps.Harness.Claude != "", caps.Xcode, caps.Simulators),
- Paths: h.paths, RuntimeRoot: filepath.Join(cfg.ScratchRoot, "homes"), TokenFiles: tokens,
+ // The inputs each launch runs under, read afresh (not the report).
+ Live: func(ctx context.Context) fprobe.Inputs {
+ c := e.readNow(ctx)
+ return fprobe.NewInputs(h.version, c.Harness.Claude != "", c.Xcode, c.Simulators)
+ },
+ Paths: h.paths, RuntimeRoot: filepath.Join(cfg.ScratchRoot, "homes"), TokenFiles: tokens, Runner: cfg.Executable,
Tools: h.tools, Simulators: caps.Simulators, Scratch: filepath.Join(h.scratch, "fprobe"), P2Denied: e.p2(),
Secrets: func(ctx context.Context) ([][]byte, error) {
s, err := w.Eng.Secrets(ctx)
@@ -184,6 +256,7 @@ func (e *macEngineering) host(ctx context.Context) (fprobe.Host, bool) {
return err == nil && len(addrs) > 0
},
Exposed: mac.Exposed, Exec: h.run, Lookup: proc.Platform.Lookup,
+ Alive: func(id proc.ID) (bool, bool) { return proc.Alive(proc.Platform, id) },
}, true
}
@@ -196,9 +269,11 @@ var probeNote func(fprobe.Spec) string
// at its real path, the token by descriptor, the Keychain watch, the
// proven stop), on the Mac's first usable Claude connection and its
// small model, with no step log and no kept session, before the Mac is
-// ready. ask hears every answer of the runner's permission tool. Only
-// the CLI's start (its group on record) counts as started.
-func (w *Worker) probeLaunch(ctx context.Context, s fprobe.Spec, ask func(fprobe.Ask)) fprobe.Outcome {
+// ready. Its permission tool is probePermission; its scratch (TMPDIR) is
+// the probe's, where only the script writes; obs sees the runtime copy
+// before the CLI starts, the CLI's pid once its group is on record (only
+// that counts as started) and every frame of its stream.
+func (w *Worker) probeLaunch(ctx context.Context, s fprobe.Spec, obs fprobe.Observer) fprobe.Outcome {
e := w.Engine
for _, c := range e.Conns.bindings() {
if c.Provider != wire.ProviderClaude || c.Kind != wire.KindToken || !e.Conns.Usable(c.ID) {
@@ -214,21 +289,20 @@ func (w *Worker) probeLaunch(ctx context.Context, s fprobe.Spec, ask func(fprobe
if s.Xcode {
r.XcodeAccess = wire.XcodeAccessSandboxed
}
- perm := func(raw json.RawMessage, p provider.Policy) json.RawMessage {
- out := claude.StepPermission(raw, p)
- var q struct {
- Tool string `json:"tool_name"`
- Input json.RawMessage `json:"input"`
+ perm := probePermission(claude.StepPermission, s, func(q fprobe.Ask) {
+ if obs.Ask != nil {
+ obs.Ask(q)
}
- _ = json.Unmarshal(raw, &q)
- ask(fprobe.Ask{Tool: q.Tool, Input: q.Input, Allowed: !denied(out)})
- return out
- }
+ })
spec := specialistRun{action: "implement", binding: c, tools: stepTools, names: []string{"submit_candidate", "ask_person", "submit_render"}, permission: perm,
call: func(context.Context, string, string, json.RawMessage) (string, bool) { return stepToolText, false }, prompt: prompt, limit: s.Limit, noLog: true, probe: true,
+ scratch: s.Scratch, copied: obs.Copy, tap: obs.Event,
record: func(_ context.Context, id string) error {
- if !strings.HasPrefix(id, mac.RecordID(0, "")) {
- started.Store(true)
+ // pg:<pid>:<marker>: the CLI leads its own group.
+ if f := strings.SplitN(id, ":", 3); len(f) == 3 && f[1] != "0" && started.CompareAndSwap(false, true) && obs.Started != nil {
+ if pid, err := strconv.Atoi(f[1]); err == nil {
+ obs.Started(pid)
+ }
}
return nil
}}
diff --git a/internal/runner/thin/mac_fprobe_test.go b/internal/runner/thin/mac_fprobe_test.go
index 9d440a53..d62f8b34 100644
--- a/internal/runner/thin/mac_fprobe_test.go
+++ b/internal/runner/thin/mac_fprobe_test.go
@@ -4,18 +4,20 @@ package thin
import (
"context"
+ "crypto/sha256"
"encoding/base64"
+ "encoding/hex"
"encoding/json"
"net"
"os"
"path/filepath"
- "regexp"
"slices"
"strings"
"sync"
"testing"
"time"
+ "amadan.net/oficina/equipo/internal/runner/mac"
"amadan.net/oficina/equipo/internal/runner/mac/fprobe"
"amadan.net/oficina/equipo/internal/runner/mac/proc"
"amadan.net/oficina/equipo/internal/runner/provider"
@@ -67,28 +69,32 @@ func TestProbeTurnVerdictIgnoresModelText(t *testing.T) {
if s.Launch != fprobe.LaunchA {
return "\nsay:" + claim + "\n"
}
- script, _ := os.ReadFile(filepath.Join(s.Tree, "probe.sh"))
- ctl := regexp.MustCompile(`'(EQUIPO-NONCE-[0-9a-f]+)' > "\$o/control"`).FindSubmatch(script)
sentinels, _ := filepath.Glob(filepath.Join(d.m.paths.StateDir, "equipo-fprobe-*"))
- if ctl == nil || len(sentinels) != 1 {
- t.Errorf("no control in the script or no sentinel planted: %v", sentinels)
+ if len(sentinels) != 1 {
+ t.Errorf("no sentinel planted: %v", sentinels)
return ""
}
nonce, _ := os.ReadFile(sentinels[0])
- return "\nbytes:out/control|" + b64(string(ctl[1])+"\n") + "\nbytes:out/f2.state|" + b64(string(nonce)) + "\ncopy:" + sentinels[0] + "|out/f6-copy\nsay:" + claim + "\n"
+ // The model knows this run's nonce (it is in the command it is
+ // asked to run) and forges the records with it, in the tree, the
+ // one place it can write: they are not the script's.
+ forged := "begin " + s.Nonce + "\n"
+ return "\nbytes:out/begin|" + b64(forged) + "\nbytes:out/f1|" + b64("tcp 1\nhttps 1\nhttps_local 1\ndns 1\n") + "\nbytes:out/f2.state|" + b64(string(nonce)) + "\ncopy:" + sentinels[0] + "|out/f6-copy\nsay:" + claim + "\n"
}
t.Cleanup(func() { probeNote = nil })
h := probeHost(x)
var mu sync.Mutex
var outcomes []fprobe.Outcome
var asks []fprobe.Ask
- h.Launch = func(ctx context.Context, s fprobe.Spec, ask func(fprobe.Ask)) fprobe.Outcome {
- o := x.w.probeLaunch(ctx, s, func(q fprobe.Ask) {
+ h.Launch = func(ctx context.Context, s fprobe.Spec, obs fprobe.Observer) fprobe.Outcome {
+ ask := obs.Ask
+ obs.Ask = func(q fprobe.Ask) {
mu.Lock()
asks = append(asks, q)
mu.Unlock()
ask(q)
- })
+ }
+ o := x.w.probeLaunch(ctx, s, obs)
mu.Lock()
outcomes = append(outcomes, o)
mu.Unlock()
@@ -119,8 +125,8 @@ func TestProbeTurnVerdictIgnoresModelText(t *testing.T) {
if p := byID("F2"); p.Verdict != wire.ProbeFailed || !strings.Contains(p.Detail, "reached the tree: state") {
t.Fatalf("F2: %+v", p)
}
- if p := byID("F1"); p.Verdict != wire.ProbeFailed || strings.Contains(p.Detail, "control did not appear") || !strings.Contains(p.Detail, "not shown denied: tcp https https_local dns") {
- t.Fatalf("F1 (the control is there, no record is): %+v", p)
+ if p := byID("F1"); p.Verdict != wire.ProbeFailed || !strings.HasPrefix(p.Detail, "the probe script was not shown run") || !strings.Contains(p.Detail, "not shown denied: tcp https https_local dns") {
+ t.Fatalf("F1 (the forged records in the tree are not the script's): %+v", p)
}
// The fake CLI runs no Bash: the runner's tool never saw a script run.
if p := byID("F4"); p.Verdict != wire.ProbeFailed || p.Detail != "the probe script was not shown run; the child was not shown started" {
@@ -238,3 +244,143 @@ func TestMacEngineeringStatusInCaps(t *testing.T) {
t.Fatalf("below 37: %+v", hello.Capabilities)
}
}
+
+// The probe launch's permission tool (fix round 1, #1): beyond the
+// Engineering rules, Bash is the probe script exactly (its bytes as the
+// runner wrote them, this run's nonce), and no native write lands
+// outside the tree; every answer is heard by the probe.
+func TestProbePermission(t *testing.T) {
+ dir := t.TempDir()
+ script := filepath.Join(dir, "bin", "probe.sh")
+ if err := os.MkdirAll(filepath.Dir(script), 0o700); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(script, []byte("echo probe\n"), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ sum := sha256.Sum256([]byte("echo probe\n"))
+ s := fprobe.Spec{Tree: filepath.Join(dir, "tree"), Scratch: filepath.Join(dir, "run"), Script: script, ScriptSHA256: hex.EncodeToString(sum[:]), Nonce: "EQUIPO-NONCE-1"}
+ var heard []fprobe.Ask
+ allowAll := func(json.RawMessage, provider.Policy) json.RawMessage {
+ return json.RawMessage(`{"behavior":"allow","updatedInput":{}}`)
+ }
+ perm := probePermission(allowAll, s, func(q fprobe.Ask) { heard = append(heard, q) })
+ ask := func(tool string, input map[string]string) bool {
+ raw, _ := json.Marshal(map[string]any{"tool_name": tool, "tool_use_id": "u1", "input": input})
+ return !denied(perm(raw, provider.Policy{}))
+ }
+ if !ask("Bash", map[string]string{"command": s.Command()}) || !ask("Write", map[string]string{"file_path": filepath.Join(s.Tree, "x")}) {
+ t.Fatal("the script and a write in the tree are refused")
+ }
+ for _, c := range []struct {
+ tool string
+ input map[string]string
+ }{
+ {"Bash", map[string]string{"command": "echo dns 1 >> " + filepath.Join(s.Scratch, "out", "f1")}},
+ {"Bash", map[string]string{"command": s.Command() + " && true"}},
+ {"Write", map[string]string{"file_path": filepath.Join(s.Scratch, "out", "f1")}},
+ {"Edit", map[string]string{"file_path": script}},
+ } {
+ if ask(c.tool, c.input) {
+ t.Fatalf("allowed %+v", c)
+ }
+ }
+ if len(heard) != 6 || heard[0].ToolUseID != "u1" || !heard[0].Allowed || heard[2].Allowed {
+ t.Fatalf("heard %+v", heard)
+ }
+ // The Engineering rules still decide first.
+ refuseAll := func(json.RawMessage, provider.Policy) json.RawMessage {
+ return json.RawMessage(`{"behavior":"deny","message":"no"}`)
+ }
+ if raw, _ := json.Marshal(map[string]any{"tool_name": "Bash", "input": map[string]string{"command": s.Command()}}); !denied(probePermission(refuseAll, s, func(fprobe.Ask) {})(raw, provider.Policy{})) {
+ t.Fatal("the probe allowed what the Engineering rules refused")
+ }
+}
+
+// Readiness and Xcode access are decided afresh at each use (fix round
+// 1, #9): the inputs read now (not the hour-old report) and the time now.
+func TestMacEngineeringRevalidates(t *testing.T) {
+ x := newEngRig(t)
+ h := &macHost{version: "v-test", probes: newMacProbes("v-test", "", nil, func() bool { return true }), creds: x.m, taint: x.m.taint, turns: x.m.turns}
+ h.eng = newMacEngineering(h)
+ sims := []wire.Simulator{{Name: "iPhone 17 Pro", Runtime: "iOS 27.2", UDID: "ABCDEF01-2345-6789-ABCD-EF0123456789", State: "Shutdown"}}
+ live := wire.Capabilities{Tags: []string{wire.TagMacOS}, Simulators: sims, Xcode: wire.Xcode{Version: "27.2", Build: "27B52"}, Harness: wire.Harness{Claude: provider.ClaudeVersion}}
+ h.eng.live = func(context.Context) wire.Capabilities { return live }
+ now := time.Now()
+ h.eng.now = func() time.Time { return now }
+ in := fprobe.NewInputs("v-test", true, live.Xcode, sims)
+ for _, l := range fprobe.Launches {
+ r := fprobe.Result{Launch: l, Inputs: in, At: now}
+ for _, id := range wire.EngineeringProbeIDs {
+ if fprobe.LaunchOf(id) == l {
+ r.Probes = append(r.Probes, wire.Probe{ID: id, Verdict: wire.EngineeringProbeSuccess(id)})
+ }
+ }
+ h.eng.store.Put(r)
+ }
+ h.eng.bind(x.w, x.conns, nil)
+ ctx := context.Background()
+ if st := h.eng.statusNow(ctx); st == nil || st.State != wire.EngineeringReady {
+ t.Fatalf("ready now: %+v", st)
+ }
+ // P2 trusted denied, so F5 counts; the report composed now says it.
+ h.probes.last = mac.Report{Version: "v-test", Profile: mac.ProfileDigest(), At: now, SRT: srtPinned, Probes: []wire.Probe{{ID: "P2", Verdict: wire.ProbeDenied}}}
+ report := live
+ h.eng.compose(&report)
+ if !h.eng.xcode() || !h.eng.xcodeNow(ctx) {
+ t.Fatal("Xcode access with P2 and F5 denied")
+ }
+ live.Xcode.Build = "27B53"
+ if st := h.eng.statusNow(ctx); st == nil || st.State != wire.EngineeringProbesPending {
+ t.Fatalf("Xcode changed since the report: %+v", st)
+ }
+ live.Xcode.Build = "27B52"
+ now = now.Add(25 * time.Hour)
+ if st := h.eng.statusNow(ctx); st == nil || st.State != wire.EngineeringProbesPending {
+ t.Fatalf("a day later: %+v", st)
+ }
+ if h.eng.xcodeNow(ctx) {
+ t.Fatal("Xcode access a day later")
+ }
+ x.m.taint.Set()
+ if st := h.eng.statusNow(ctx); st == nil || st.State != wire.EngineeringTainted {
+ t.Fatalf("tainted now: %+v", st)
+ }
+}
+
+// Below protocol 37 a Mac's hello says no claude tag (fix round 1, #10):
+// an older instance would place Engineering on it.
+func TestMacClaudeTagBelow37(t *testing.T) {
+ caps := wire.Capabilities{Tags: []string{wire.TagMacOS, wire.TagXcode, wire.TagClaude}, Simulators: []wire.Simulator{}, Engineering: &wire.EngineeringStatus{State: wire.EngineeringReady}}
+ hello := wire.Hello{Repos: []string{}, CreateIn: []string{}, Catalog: []wire.RepoInfo{}, Connections: []wire.HeldConnection{}, Platform: &wire.Platform{OS: "darwin", Arch: "arm64"}, Capabilities: &caps}
+ f, err := wire.NewFrame("h1", wire.FrameHello, hello)
+ if err != nil {
+ t.Fatal(err)
+ }
+ tags := func(p int) []string {
+ enc, err := wire.Encode(f, p)
+ if err != nil {
+ t.Fatal(err)
+ }
+ raw, _ := json.Marshal(enc)
+ _, body, err := wire.ParseFrame(raw)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return body.(*wire.Hello).Capabilities.Tags
+ }
+ if got := tags(36); slices.Contains(got, wire.TagClaude) || !slices.Contains(got, wire.TagMacOS) {
+ t.Fatalf("at 36: %v", got)
+ }
+ if got := tags(37); !slices.Contains(got, wire.TagClaude) {
+ t.Fatalf("at 37: %v", got)
+ }
+ // A Linux runner's claude tag is not the Mac's to strip.
+ hello.Platform, hello.Capabilities = &wire.Platform{OS: "linux", Arch: "amd64"}, &wire.Capabilities{Tags: []string{wire.TagLinux, wire.TagClaude}, Simulators: []wire.Simulator{}}
+ if f, err = wire.NewFrame("h2", wire.FrameHello, hello); err != nil {
+ t.Fatal(err)
+ }
+ if got := tags(36); !slices.Contains(got, wire.TagClaude) {
+ t.Fatalf("linux at 36: %v", got)
+ }
+}
diff --git a/internal/runner/thin/run.go b/internal/runner/thin/run.go
index 7e778ba0..0f8d4daf 100644
--- a/internal/runner/thin/run.go
+++ b/internal/runner/thin/run.go
@@ -810,6 +810,11 @@ func runWorker(ctx context.Context, c runner.Config, o Options, platform wire.Pl
// The status the capability report says now: until every part of
// it is ready (task 14 composes it), no Engineering runs here.
eng.Status = func(ctx context.Context) *wire.EngineeringStatus { return caps.Get(ctx).Engineering }
+ if w.fprobes != nil {
+ // A Mac decides afresh at each use: the inputs now, the
+ // results' age now (never the hour-old report).
+ eng.Status = w.fprobes.statusNow
+ }
eng.Secrets = func(context.Context) ([]string, error) { return workerSecrets(c, creds.Bearer.Token) }
worker.Eng = &eng
if w.fprobes != nil {
diff --git a/internal/runner/thin/worker_launch.go b/internal/runner/thin/worker_launch.go
index 60fe9138..5eef3f90 100644
--- a/internal/runner/thin/worker_launch.go
+++ b/internal/runner/thin/worker_launch.go
@@ -73,11 +73,13 @@ func (w *Worker) launch(ctx context.Context, r stepRow, tree workspace.TaskTree,
}
defer lease.Close()
binding := lease.Binding()
- scratch, err := os.MkdirTemp(o.Runner.ScratchRoot, "policy-")
- if err != nil {
- return done("provider_failed")
+ scratch := spec.scratch
+ if scratch == "" {
+ if scratch, err = os.MkdirTemp(o.Runner.ScratchRoot, "policy-"); err != nil {
+ return done("provider_failed")
+ }
+ defer os.RemoveAll(scratch)
}
- defer os.RemoveAll(scratch)
var policy provider.Policy
var refused atomic.Int64
permission := countRefusals(spec.permission, &refused)
@@ -124,6 +126,9 @@ func (w *Worker) launch(ctx context.Context, r stepRow, tree workspace.TaskTree,
if err = lease.CheckCopy(ctx); err != nil {
return done(reasonFor(err))
}
+ if spec.copied != nil && spec.copied(binding.Home) != nil {
+ return done(wire.ReasonEngineeringUnavailable)
+ }
limit := e.maxStep()
if spec.limit > 0 {
limit = spec.limit
@@ -184,6 +189,9 @@ func (w *Worker) launch(ctx context.Context, r stepRow, tree workspace.TaskTree,
scan.Buffer(make([]byte, 0, 64<<10), stepFrameLimit)
for scan.Scan() {
if line := scan.Bytes(); len(line) > 0 {
+ if spec.tap != nil {
+ spec.tap(line)
+ }
frames <- append([]byte(nil), line...)
}
}
diff --git a/internal/wire/mac_engineering.go b/internal/wire/mac_engineering.go
index f88da4a1..3467d685 100644
--- a/internal/wire/mac_engineering.go
+++ b/internal/wire/mac_engineering.go
@@ -253,7 +253,7 @@ const (
)
// WithoutMacEngineering drops a hello's Engineering status, Unproven, the
-// credential hold, the inventory mark and F probes
+// credential hold, the inventory mark, F probes and a Mac's claude tag
// (in new values; the caller's are untouched). The runner's first hello
// on a connection goes out before the welcome names the protocol, and an
// older instance's ValidCapabilities refuses an F probe; the runner sends
@@ -266,11 +266,17 @@ func WithoutMacEngineering(h *Hello) bool {
return inventory
}
isF := func(p Probe) bool { _, ok := engineeringProbeSuccess[p.ID]; return ok }
- if c.Engineering == nil && c.Unproven == "" && !c.ModelHold && c.HoldingItems == nil && !slices.ContainsFunc(c.Probes, isF) {
+ // A slice F Mac (it says its Engineering status) says claude only at
+ // 37: an older instance would take it for a Mac that can run Claude.
+ macClaude := h.Platform != nil && h.Platform.OS == "darwin" && c.Engineering != nil && slices.Contains(c.Tags, TagClaude)
+ if c.Engineering == nil && c.Unproven == "" && !c.ModelHold && c.HoldingItems == nil && !slices.ContainsFunc(c.Probes, isF) && !macClaude {
return inventory
}
out := *c
out.Engineering, out.Unproven, out.ModelHold, out.HoldingItems = nil, "", false, nil
+ if macClaude {
+ out.Tags = slices.DeleteFunc(slices.Clone(c.Tags), func(t string) bool { return t == TagClaude })
+ }
if slices.ContainsFunc(c.Probes, isF) {
out.Probes = slices.DeleteFunc(slices.Clone(c.Probes), isF)
}