Merge branch 'mac-p2-why' into main
Merge mac-p2-why: P2 says why srt could not run Xcode When the hostile build or test under srt does not fully succeed, P2 records the phase, exit code, timeout and a bounded, scrubbed excerpt, and logs a WARN once per run. TMPDIR's allowance moves; no denial is loosened. Hosted CI passed on 23915cf.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
10 files changed,
+640
−37
.rastrillo/budgets.txt+1 −1internal/runner/mac/gate.go+10 −1internal/runner/mac/gate_test.go+16 −2internal/runner/mac/p2why.go+285 −0internal/runner/mac/p2why_test.go+208 −0internal/runner/mac/probe.go+63 −15internal/runner/mac/probe_test.go+35 −16internal/runner/thin/mac.go+8 −0internal/runner/thin/startup_logs_test.go+12 −0scripts/runner-reference-allowlist.json+2 −2
CI passed — run details
diff --git a/.rastrillo/budgets.txt b/.rastrillo/budgets.txt| index e2f52c20..f6d8de3e 100644 |
| --- a/.rastrillo/budgets.txt |
| +++ b/.rastrillo/budgets.txt |
| @@ -34,7 +34,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; niced serial reruns measured 5.773s and 5.750s. The added coordinator mount check has no repeated launches to remove; 15s leaves 38 percent headroom for namespace, process-exit and recovery assertions. |
| -size internal/runner/thin 16846 8399 Mac probe deadlines bound the booted simctl list, move the worker's wait for the probes out of its lock (hold) and warn when a probe run reaches its limit (about 24 lines); their tests (mac_stall_test.go: a fake xcrun that never answers, probes stalled while an update applies, about 270 lines) beside the Mac host they drive: measured 16846/8399. Release slice 1 merged onto main: measured 16822/8130. Release slice 1 (hosted checks) adds the hub's hosted CI verdict for checks: the deferred one-read poll with its persisted deadline, the one-snapshot verdict, the failing units and the restart case (judge_hosted.go, about 200 lines) and the forge's CI reads (forge.go, about 40); measured 16821. Its tests (judge_hosted_test.go, about 270 lines) take the package's tests to 8113, beside the step engine they drive. The leftover helper's debug line adds 3 lines: measured 16572. The Mac host's hang fix and probe pacing add the process group and its kill (procgroup_unix.go, procgroup_other.go), the bounded wait for a command's output, and the untrusted report's rerun decision with its tool fingerprint (about 165 lines); measured 16569. Runner startup logs add the info lines a silent start is pinned to a phase by (startup phases, the Mac host's xcode-select and capability commands, slow-command warnings, the probes, and the link's connecting, hello and welcome lines: startPhase, openRunner, watchSlow and logged, about 155 lines); measured 16405. Merge authority thin v1 adds the review's measured change facts (facts.go: raw and numstat listings, modes, signing lines, the revert tree check, about 230 lines), the merge_request confirmation and the merge's provenance; measured 16196 with spend-1 merged. Spend 1 resumes a fix round in Engineering's kept session on its healthy connection (fixSession, fixPlan, fixPrompt, keptCommit, about 90 lines); measured 15873. Claude's sign-in by a link's review round 1 contains its setup-token in a recorded namespace (the contained terminal, its proven stop and the start's recovery before a home goes, about 130 lines); measured 15787. Claude's sign-in by a link adds the runner's own setup-token attempt, the code's sealed delivery with its crash boundaries and the shared token commit (signin.go, about 300 lines, less the removed terminal watcher); measured 15655. Claude setup tokens add sealed delivery, the token check, Check again and recovery (token.go, tokencheck.go, about 700 lines) beside the composer and Mac lines; measured 15239. Astra round 2 moves the attachment quota to admission: arriving files counted by declared size, admissions protecting a file until its message names it, room made from the oldest unprotected files, refusal as runner_storage_full, and a sweep that stops when protection cannot be read (about 150 lines); measured 12191. Mac runners slices A and B add protocol negotiation (link.go), the capability report, the start authorization, the pack relay (relay.go), the primary's publication, the worker executor (worker.go) and the test-build fake worker, about 2700 lines on the same step engine. Composer attachments add the chunked receipt with exactly-once writes, the read-only desk delivery and its checks (files.go, about 230 lines), image blocks and localImage inputs, the attachment read through read_file; measured 11736. Connections slice 1 Astra round 1 adds the Codex step path (codexstep.go: Engineering and Review on the pinned app-server in the implement and inspect containment, about 300 lines); measured 11345. Connections slice 1 (after Astra round 1) also keeps a durable ledger of each turn's write tools so a later attempt never repeats one (effects.go), the waiting state between attempts and usage rows per attempt, about 500 lines more; measured 10590 before gate 1d. Connections slice 1 adds the Codex coordinator beside the Claude one (codex.go: the pinned app-server over JSON-RPC in the converse containment, sharing the coordinator base, desk, tool socket and session table), the connection registry over the bindings with health and provider limits (conns.go), in-app sign-in attempts (connector.go) and turn failover and holding (failover.go), about 1500 lines; the pure parts (the choice function, limit parsing, the app-server client, the sign-in flows) live in internal/runner/connect. Measured 10097. Thin v1 UX1 adds step activity lines from the specialist's stream, the repository head and checks gate in the index and project-tagged notes (about 120 lines); measured 8615 with slice 4c's review fixes. Thin v1 slice 4c adds the merge step (mergestep.go, about 190 lines) and the rebase round beside the slice 4b ask fixes. Thin v1 slice 3 adds Engineering steps beside the coordinator: the durable step state and engine (step.go) and the executor that checks out the task tree, runs the CLI in the implement containment, commits and pushes (engineer.go), about 800 lines sharing the coordinator's launch, tool socket and account selection. Measured 5686 source lines. Splitting would export the launch internals; revisit at the slice 7 sweep. Slice 4 adds checks and review on a candidate (judge.go) and the merge watch (merge.go), about 800 lines, sharing the Engineer launch path; measured 6808, 7035 after review round 1 (branch head watch, deadlines, streamed outputs). Slice 4b keeps Engineering and Review sessions and answers the creator's questions from them (ask.go: kept-session and ask state, read-only git tools, the answer stream), about 700 lines on the same launch path. The paste box house rule merged onto the runner logs: measured 16573. The leftover helper's debug line adds 3 lines: measured 16572. The Mac host's hang fix and probe pacing add the process group and its kill (procgroup_unix.go, procgroup_other.go), the bounded wait for a command's output, and the untrusted report's rerun decision with its tool fingerprint (about 165 lines); measured 16569. Runner startup logs add the info lines a silent start is pinned to a phase by (startup phases, the Mac host's xcode-select and capability commands, slow-command warnings, the probes, and the link's connecting, hello and welcome lines: startPhase, openRunner, watchSlow and logged, about 155 lines); measured 16405. Merge authority thin v1 adds the review's measured change facts (facts.go: raw and numstat listings, modes, signing lines, the revert tree check, about 230 lines), the merge_request confirmation and the merge's provenance; measured 16196 with spend-1 merged. Spend 1 resumes a fix round in Engineering's kept session on its healthy connection (fixSession, fixPlan, fixPrompt, keptCommit, about 90 lines); measured 15873. Claude's sign-in by a link's review round 1 contains its setup-token in a recorded namespace (the contained terminal, its proven stop and the start's recovery before a home goes, about 130 lines); measured 15787. Claude's sign-in by a link adds the runner's own setup-token attempt, the code's sealed delivery with its crash boundaries and the shared token commit (signin.go, about 300 lines, less the removed terminal watcher); measured 15655. Claude setup tokens add sealed delivery, the token check, Check again and recovery (token.go, tokencheck.go, about 700 lines) beside the composer and Mac lines; measured 15239. Astra round 2 moves the attachment quota to admission: arriving files counted by declared size, admissions protecting a file until its message names it, room made from the oldest unprotected files, refusal as runner_storage_full, and a sweep that stops when protection cannot be read (about 150 lines); measured 12191. Mac runners slices A and B add protocol negotiation (link.go), the capability report, the start authorization, the pack relay (relay.go), the primary's publication, the worker executor (worker.go) and the test-build fake worker, about 2700 lines on the same step engine. Composer attachments add the chunked receipt with exactly-once writes, the read-only desk delivery and its checks (files.go, about 230 lines), image blocks and localImage inputs, the attachment read through read_file; measured 11736. Connections slice 1 Astra round 1 adds the Codex step path (codexstep.go: Engineering and Review on the pinned app-server in the implement and inspect containment, about 300 lines); measured 11345. Connections slice 1 (after Astra round 1) also keeps a durable ledger of each turn's write tools so a later attempt never repeats one (effects.go), the waiting state between attempts and usage rows per attempt, about 500 lines more; measured 10590 before gate 1d. Connections slice 1 adds the Codex coordinator beside the Claude one (codex.go: the pinned app-server over JSON-RPC in the converse containment, sharing the coordinator base, desk, tool socket and session table), the connection registry over the bindings with health and provider limits (conns.go), in-app sign-in attempts (connector.go) and turn failover and holding (failover.go), about 1500 lines; the pure parts (the choice function, limit parsing, the app-server client, the sign-in flows) live in internal/runner/connect. Measured 10097. Thin v1 UX1 adds step activity lines from the specialist's stream, the repository head and checks gate in the index and project-tagged notes (about 120 lines); measured 8615 with slice 4c's review fixes. Thin v1 slice 4c adds the merge step (mergestep.go, about 190 lines) and the rebase round beside the slice 4b ask fixes. Thin v1 slice 3 adds Engineering steps beside the coordinator: the durable step state and engine (step.go) and the executor that checks out the task tree, runs the CLI in the implement containment, commits and pushes (engineer.go), about 800 lines sharing the coordinator's launch, tool socket and account selection. Measured 5686 source lines. Splitting would export the launch internals; revisit at the slice 7 sweep. Slice 4 adds checks and review on a candidate (judge.go) and the merge watch (merge.go), about 800 lines, sharing the Engineer launch path; measured 6808, 7035 after review round 1 (branch head watch, deadlines, streamed outputs). Slice 4b keeps Engineering and Review sessions and answers the creator's questions from them (ask.go: kept-session and ask state, read-only git tools, the answer stream), about 700 lines on the same launch path. |
| +size internal/runner/thin 16854 8411 Mac P2 diagnostics hand the probes' host runner.log's WARN (macHost.warn, 8 lines) and pin it with a test (12 lines): measured 16854/8411. Mac probe deadlines bound the booted simctl list, move the worker's wait for the probes out of its lock (hold) and warn when a probe run reaches its limit (about 24 lines); their tests (mac_stall_test.go: a fake xcrun that never answers, probes stalled while an update applies, about 270 lines) beside the Mac host they drive: measured 16846/8399. Release slice 1 merged onto main: measured 16822/8130. Release slice 1 (hosted checks) adds the hub's hosted CI verdict for checks: the deferred one-read poll with its persisted deadline, the one-snapshot verdict, the failing units and the restart case (judge_hosted.go, about 200 lines) and the forge's CI reads (forge.go, about 40); measured 16821. Its tests (judge_hosted_test.go, about 270 lines) take the package's tests to 8113, beside the step engine they drive. The leftover helper's debug line adds 3 lines: measured 16572. The Mac host's hang fix and probe pacing add the process group and its kill (procgroup_unix.go, procgroup_other.go), the bounded wait for a command's output, and the untrusted report's rerun decision with its tool fingerprint (about 165 lines); measured 16569. Runner startup logs add the info lines a silent start is pinned to a phase by (startup phases, the Mac host's xcode-select and capability commands, slow-command warnings, the probes, and the link's connecting, hello and welcome lines: startPhase, openRunner, watchSlow and logged, about 155 lines); measured 16405. Merge authority thin v1 adds the review's measured change facts (facts.go: raw and numstat listings, modes, signing lines, the revert tree check, about 230 lines), the merge_request confirmation and the merge's provenance; measured 16196 with spend-1 merged. Spend 1 resumes a fix round in Engineering's kept session on its healthy connection (fixSession, fixPlan, fixPrompt, keptCommit, about 90 lines); measured 15873. Claude's sign-in by a link's review round 1 contains its setup-token in a recorded namespace (the contained terminal, its proven stop and the start's recovery before a home goes, about 130 lines); measured 15787. Claude's sign-in by a link adds the runner's own setup-token attempt, the code's sealed delivery with its crash boundaries and the shared token commit (signin.go, about 300 lines, less the removed terminal watcher); measured 15655. Claude setup tokens add sealed delivery, the token check, Check again and recovery (token.go, tokencheck.go, about 700 lines) beside the composer and Mac lines; measured 15239. Astra round 2 moves the attachment quota to admission: arriving files counted by declared size, admissions protecting a file until its message names it, room made from the oldest unprotected files, refusal as runner_storage_full, and a sweep that stops when protection cannot be read (about 150 lines); measured 12191. Mac runners slices A and B add protocol negotiation (link.go), the capability report, the start authorization, the pack relay (relay.go), the primary's publication, the worker executor (worker.go) and the test-build fake worker, about 2700 lines on the same step engine. Composer attachments add the chunked receipt with exactly-once writes, the read-only desk delivery and its checks (files.go, about 230 lines), image blocks and localImage inputs, the attachment read through read_file; measured 11736. Connections slice 1 Astra round 1 adds the Codex step path (codexstep.go: Engineering and Review on the pinned app-server in the implement and inspect containment, about 300 lines); measured 11345. Connections slice 1 (after Astra round 1) also keeps a durable ledger of each turn's write tools so a later attempt never repeats one (effects.go), the waiting state between attempts and usage rows per attempt, about 500 lines more; measured 10590 before gate 1d. Connections slice 1 adds the Codex coordinator beside the Claude one (codex.go: the pinned app-server over JSON-RPC in the converse containment, sharing the coordinator base, desk, tool socket and session table), the connection registry over the bindings with health and provider limits (conns.go), in-app sign-in attempts (connector.go) and turn failover and holding (failover.go), about 1500 lines; the pure parts (the choice function, limit parsing, the app-server client, the sign-in flows) live in internal/runner/connect. Measured 10097. Thin v1 UX1 adds step activity lines from the specialist's stream, the repository head and checks gate in the index and project-tagged notes (about 120 lines); measured 8615 with slice 4c's review fixes. Thin v1 slice 4c adds the merge step (mergestep.go, about 190 lines) and the rebase round beside the slice 4b ask fixes. Thin v1 slice 3 adds Engineering steps beside the coordinator: the durable step state and engine (step.go) and the executor that checks out the task tree, runs the CLI in the implement containment, commits and pushes (engineer.go), about 800 lines sharing the coordinator's launch, tool socket and account selection. Measured 5686 source lines. Splitting would export the launch internals; revisit at the slice 7 sweep. Slice 4 adds checks and review on a candidate (judge.go) and the merge watch (merge.go), about 800 lines, sharing the Engineer launch path; measured 6808, 7035 after review round 1 (branch head watch, deadlines, streamed outputs). Slice 4b keeps Engineering and Review sessions and answers the creator's questions from them (ask.go: kept-session and ask state, read-only git tools, the answer stream), about 700 lines on the same launch path. The paste box house rule merged onto the runner logs: measured 16573. The leftover helper's debug line adds 3 lines: measured 16572. The Mac host's hang fix and probe pacing add the process group and its kill (procgroup_unix.go, procgroup_other.go), the bounded wait for a command's output, and the untrusted report's rerun decision with its tool fingerprint (about 165 lines); measured 16569. Runner startup logs add the info lines a silent start is pinned to a phase by (startup phases, the Mac host's xcode-select and capability commands, slow-command warnings, the probes, and the link's connecting, hello and welcome lines: startPhase, openRunner, watchSlow and logged, about 155 lines); measured 16405. Merge authority thin v1 adds the review's measured change facts (facts.go: raw and numstat listings, modes, signing lines, the revert tree check, about 230 lines), the merge_request confirmation and the merge's provenance; measured 16196 with spend-1 merged. Spend 1 resumes a fix round in Engineering's kept session on its healthy connection (fixSession, fixPlan, fixPrompt, keptCommit, about 90 lines); measured 15873. Claude's sign-in by a link's review round 1 contains its setup-token in a recorded namespace (the contained terminal, its proven stop and the start's recovery before a home goes, about 130 lines); measured 15787. Claude's sign-in by a link adds the runner's own setup-token attempt, the code's sealed delivery with its crash boundaries and the shared token commit (signin.go, about 300 lines, less the removed terminal watcher); measured 15655. Claude setup tokens add sealed delivery, the token check, Check again and recovery (token.go, tokencheck.go, about 700 lines) beside the composer and Mac lines; measured 15239. Astra round 2 moves the attachment quota to admission: arriving files counted by declared size, admissions protecting a file until its message names it, room made from the oldest unprotected files, refusal as runner_storage_full, and a sweep that stops when protection cannot be read (about 150 lines); measured 12191. Mac runners slices A and B add protocol negotiation (link.go), the capability report, the start authorization, the pack relay (relay.go), the primary's publication, the worker executor (worker.go) and the test-build fake worker, about 2700 lines on the same step engine. Composer attachments add the chunked receipt with exactly-once writes, the read-only desk delivery and its checks (files.go, about 230 lines), image blocks and localImage inputs, the attachment read through read_file; measured 11736. Connections slice 1 Astra round 1 adds the Codex step path (codexstep.go: Engineering and Review on the pinned app-server in the implement and inspect containment, about 300 lines); measured 11345. Connections slice 1 (after Astra round 1) also keeps a durable ledger of each turn's write tools so a later attempt never repeats one (effects.go), the waiting state between attempts and usage rows per attempt, about 500 lines more; measured 10590 before gate 1d. Connections slice 1 adds the Codex coordinator beside the Claude one (codex.go: the pinned app-server over JSON-RPC in the converse containment, sharing the coordinator base, desk, tool socket and session table), the connection registry over the bindings with health and provider limits (conns.go), in-app sign-in attempts (connector.go) and turn failover and holding (failover.go), about 1500 lines; the pure parts (the choice function, limit parsing, the app-server client, the sign-in flows) live in internal/runner/connect. Measured 10097. Thin v1 UX1 adds step activity lines from the specialist's stream, the repository head and checks gate in the index and project-tagged notes (about 120 lines); measured 8615 with slice 4c's review fixes. Thin v1 slice 4c adds the merge step (mergestep.go, about 190 lines) and the rebase round beside the slice 4b ask fixes. Thin v1 slice 3 adds Engineering steps beside the coordinator: the durable step state and engine (step.go) and the executor that checks out the task tree, runs the CLI in the implement containment, commits and pushes (engineer.go), about 800 lines sharing the coordinator's launch, tool socket and account selection. Measured 5686 source lines. Splitting would export the launch internals; revisit at the slice 7 sweep. Slice 4 adds checks and review on a candidate (judge.go) and the merge watch (merge.go), about 800 lines, sharing the Engineer launch path; measured 6808, 7035 after review round 1 (branch head watch, deadlines, streamed outputs). Slice 4b keeps Engineering and Review sessions and answers the creator's questions from them (ask.go: kept-session and ask state, read-only git tools, the answer stream), about 700 lines on the same launch path. |
| time internal/thintest 180s Mac runners slices A and B add role, scoping, migration, placement, withdrawal, transfer and publication contracts, and Astra round 1 eight transition contracts (about 15s; the package measured 126s locally under load). Housekeeping slice 1 adds six contract tests (combine, Undo round trips and the race, Pause, auto-disable, quiet hours, restart while claimed; about 6s); the package measured 67.7s beside other packages locally, so 75s. Thin v1 slice 4c adds the merge, adoption, cancel and retention contract tests (CI measured 35.7s). Thin v1 contract tests: a real instance and a scripted runner per test, fixtures replayed against every request, frame and event. Slice 3 adds the task, step-sync and grant contracts; CI measured 14.805s. 30s keeps room for the slice 4 review contracts. UX1 adds step activity, task source and duplicates, coordinator merging and project facts (four contracts, about 6s); the package measured 34s locally under load, so 40s. UX1's inner screens gallery (two owners, seven tasks, every page) adds about 3s; measured 40.9s locally under load, so 60s. |
| time internal/runner/mac 30s Mac runners (Darwin worker): real process groups killed after a grace and proven gone (SIGTERM, SIGKILL, the marker sweep), and the probes run end to end with fake srt and xcodebuild, P6 killing a waiting test two seconds after it starts. About 6s alone; loaded CI measured 12.5s. |
| 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). Measured 17.8s locally under load. Slice 4b review adds a 16 MiB git output bound, an injected index-pack failure and stall (3s deadline) and held-answer tests; measured 30.3s locally under load. 45s keeps 33 percent headroom. |
diff --git a/internal/runner/mac/gate.go b/internal/runner/mac/gate.go| index 3d4f3026..7545f8c8 100644 |
| --- a/internal/runner/mac/gate.go |
| +++ b/internal/runner/mac/gate.go |
| @@ -37,7 +37,8 @@ type Gate struct { |
| // Settings writes the attempt's srt settings for a tree and scratch. |
| Settings func(tree, attempt string) ([]byte, error) |
| // Env is the gate's whole environment but TMPDIR, EQUIPO_ATTEMPT and |
| - // EQUIPO_GATE_STATUS, which the run adds. |
| + // EQUIPO_GATE_STATUS (and under srt CLAUDE_CODE_TMPDIR), which the |
| + // run adds. |
| Env []string |
| // Caffeinate keeps the Mac awake while a gate runs |
| // (/usr/bin/caffeinate); "" does not. |
| @@ -109,6 +110,14 @@ func (g *Gate) Run(ctx context.Context, attempt, dir string, argv []string, limi |
| cmd := exec.Command(cmdline[0], cmdline[1:]...) |
| cmd.Dir = dir |
| cmd.Env = append(append([]string{}, g.Env...), "TMPDIR="+scratch, "EQUIPO_ATTEMPT="+attempt, "EQUIPO_GATE_STATUS="+status) |
| + if g.SRT != "" { |
| + // srt 0.0.81 sets the command's TMPDIR to CLAUDE_CODE_TMPDIR, else |
| + // to its own /tmp/claude (generateProxyEnvVars in sandbox-utils), |
| + // a directory every srt user on the Mac shares and none cleans: |
| + // keep it this attempt's scratch, which the profile already lets |
| + // the gate write and the run removes. |
| + cmd.Env = append(cmd.Env, "CLAUDE_CODE_TMPDIR="+scratch) |
| + } |
| if g.ScratchHome { |
| cmd.Env = append(cmd.Env, "HOME="+scratch) |
| } |
diff --git a/internal/runner/mac/gate_test.go b/internal/runner/mac/gate_test.go| index e37a68fe..51075be4 100644 |
| --- a/internal/runner/mac/gate_test.go |
| +++ b/internal/runner/mac/gate_test.go |
| @@ -17,13 +17,16 @@ import ( |
| ) |
| // fakeSRT stands in for srt on Linux: it needs --settings <file> -- and a |
| -// readable JSON file, runs the command through a shell as srt does, and |
| -// exits 0 when the command dies of SIGTERM, as srt's cli does. |
| +// readable JSON file, runs the command through a shell as srt does, |
| +// sets its TMPDIR as srt 0.0.81 does (CLAUDE_CODE_TMPDIR, else |
| +// CLAUDE_TMPDIR, else /tmp/claude), and exits 0 when the command dies of |
| +// SIGTERM, as srt's cli does. |
| const fakeSRT = `#!/bin/bash |
| [ "$1" = --settings ] && [ "$3" = -- ] || exit 97 |
| python3 -c 'import json,sys; json.load(open(sys.argv[1]))' "$2" || exit 98 |
| cp "$2" "$FAKE_SRT_SEEN" |
| shift 3 |
| +export TMPDIR="${CLAUDE_CODE_TMPDIR:-${CLAUDE_TMPDIR:-/tmp/claude}}" |
| "$@" |
| s=$? |
| [ "$s" = 143 ] && exit 0 |
| @@ -119,6 +122,17 @@ func TestGateEnvironmentFromScratch(t *testing.T) { |
| } |
| } |
| +// Under srt TMPDIR is still the attempt's own scratch, not srt's shared |
| +// /tmp/claude: what a check leaves there goes with the attempt, and no |
| +// other user's /tmp/claude decides whether it can write. |
| +func TestGateKeepsTMPDIRUnderSRT(t *testing.T) { |
| + g, dir := gateFixture(t, true) |
| + res, _ := run(g, dir, "checks-c-2", time.Minute, `echo "$TMPDIR"`) |
| + if res.Code != 0 || !strings.HasPrefix(res.Output, filepath.Dir(dir)+"/attempt-") { |
| + t.Fatalf("TMPDIR under srt: %+v", res) |
| + } |
| +} |
| + |
| // Cancel and timeout: SIGTERM to the group, SIGKILL after the grace, a |
| // sweep of marked processes (a child that ignores SIGTERM and one that |
| // left the group but kept its marker), and the proof: the group gone |
diff --git a/internal/runner/mac/p2why.go b/internal/runner/mac/p2why.go| new file mode 100644 |
| index 00000000..e23de64d |
| --- /dev/null |
| +++ b/internal/runner/mac/p2why.go |
| @@ -0,0 +1,285 @@ |
| +package mac |
| + |
| +import ( |
| + "path" |
| + "regexp" |
| + "sort" |
| + "strconv" |
| + "strings" |
| + "sync" |
| + "unicode/utf8" |
| +) |
| + |
| +// Why P2's srt run did not fully succeed: the step that failed, its |
| +// exit, whether the run timed out, and the first error lines, bounded |
| +// and with nothing secret in them. The probe's detail carries the short |
| +// form; runner.log the excerpt, once per probe run. |
| + |
| +// p2Phases are the steps of P2's srt run in the order they run. The |
| +// script build stands alone; each package step needs the one before. |
| +var p2Phases = []struct{ key, label string }{ |
| + {"script-build", "script build"}, |
| + {"package-resolve", "package resolve"}, |
| + {"test-build", "test build"}, |
| + {"simulator-boot", "simulator boot"}, |
| + {"test-run", "test run"}, |
| +} |
| + |
| +// p2Succeeded are xcodebuild's own last lines for its three steps that |
| +// build or test (build, build-for-testing, test-without-building). |
| +var p2Succeeded = []string{"** BUILD SUCCEEDED **", "** TEST BUILD SUCCEEDED **", "** TEST EXECUTE SUCCEEDED **"} |
| + |
| +const ( |
| + // p2AttemptLines bounds the report lines kept (15 are expected; the |
| + // first for each attempt counts). |
| + p2AttemptLines = 64 |
| + // p2ErrorLines and p2ExcerptBytes bound the excerpt; p2ShortBytes its |
| + // first line in the probe's detail. |
| + p2ErrorLines = 5 |
| + p2ExcerptBytes = 400 |
| + p2ShortBytes = 120 |
| +) |
| + |
| +var ( |
| + phaseLine = regexp.MustCompile(`^EQUIPO-PHASE (script-build|package-resolve|test-build|simulator-boot|test-run) ([0-9]{1,3})$`) |
| + // failureLine: xcodebuild's and the compilers' error lines, srt's own |
| + // ("Error: ...", a refused settings file), a nested sandbox that |
| + // could not be applied, a denial a tool printed, a write Unix |
| + // permissions refused, and the fixture finding no targets. |
| + failureLine = regexp.MustCompile(`(?i)\berror:|^refusing to run|^failed to execute|sandbox_apply|sandbox-exec:|\bdeny\(\d+\)|operation not permitted|permission denied|^EQUIPO-PROBE \w+ targets missing`) |
| + ansiEscape = regexp.MustCompile("\x1b\\[[0-9;?]*[ -/]*[@-~]") |
| +) |
| + |
| +// p2Watch reads the whole of P2's output as it comes, so what decides P2 |
| +// does not depend on the gate's last 200 lines: a full build and test |
| +// prints more than that, and the script build's lines come first. |
| +type p2Watch struct { |
| + mu sync.Mutex |
| + attempts []string |
| + phases map[string]int |
| + succeeded map[string]bool |
| + errors []string |
| +} |
| + |
| +func newP2Watch() *p2Watch { |
| + return &p2Watch{phases: map[string]int{}, succeeded: map[string]bool{}} |
| +} |
| + |
| +func (w *p2Watch) line(l string) { |
| + t := strings.TrimSpace(l) |
| + w.mu.Lock() |
| + defer w.mu.Unlock() |
| + if attemptLine.MatchString(t) { |
| + if len(w.attempts) < p2AttemptLines { |
| + w.attempts = append(w.attempts, t) |
| + } |
| + return |
| + } |
| + if m := phaseLine.FindStringSubmatch(t); m != nil { |
| + if _, seen := w.phases[m[1]]; !seen { |
| + w.phases[m[1]], _ = strconv.Atoi(m[2]) |
| + } |
| + return |
| + } |
| + for _, s := range p2Succeeded { |
| + if t == s { |
| + w.succeeded[s] = true |
| + } |
| + } |
| + if len(w.errors) < p2ErrorLines && failureLine.MatchString(t) { |
| + for _, e := range w.errors { |
| + if e == t { |
| + return |
| + } |
| + } |
| + w.errors = append(w.errors, t) |
| + } |
| +} |
| + |
| +// attemptsSeen is the report lines, one per line, for ParseAttempts. |
| +func (w *p2Watch) attemptsSeen() string { |
| + w.mu.Lock() |
| + defer w.mu.Unlock() |
| + return strings.Join(w.attempts, "\n") |
| +} |
| + |
| +// ran: the run exited 0, every step said it exited 0, and xcodebuild |
| +// said each build and test succeeded. |
| +func (w *p2Watch) ran(res Result) bool { |
| + w.mu.Lock() |
| + defer w.mu.Unlock() |
| + if res.Code != 0 { |
| + return false |
| + } |
| + for _, p := range p2Phases { |
| + if c, ok := w.phases[p.key]; !ok || c != 0 { |
| + return false |
| + } |
| + } |
| + for _, s := range p2Succeeded { |
| + if !w.succeeded[s] { |
| + return false |
| + } |
| + } |
| + return true |
| +} |
| + |
| +// p2Failure is why the srt run did not fully succeed. |
| +type p2Failure struct { |
| + // Phase is the first step that failed, else the first that did not |
| + // finish: "srt start" when no step reported, "gate start" when the |
| + // gate could not start, "run end" when every step exited 0 and the |
| + // run still did not succeed. Failed is every step that failed, with |
| + // its exit ("script build exit 65"); Unfinished the step the run was |
| + // stopped in ("test build timed out"). |
| + Phase string |
| + Failed []string |
| + Unfinished string |
| + Exit int |
| + TimedOut bool |
| + // Excerpt is up to p2ErrorLines redacted lines, at most |
| + // p2ExcerptBytes; First the first of them, at most p2ShortBytes. |
| + Excerpt, First string |
| +} |
| + |
| +// failure says why a run that did not fully succeed failed. |
| +func (w *p2Watch) failure(res Result, r redactor) p2Failure { |
| + w.mu.Lock() |
| + defer w.mu.Unlock() |
| + f := p2Failure{Exit: res.Code, TimedOut: res.Reason == "checks_timeout"} |
| + stopped := f.TimedOut || res.Reason == "cancelled" |
| + missing := "" |
| + for _, p := range p2Phases { |
| + c, ok := w.phases[p.key] |
| + if ok && c != 0 { |
| + f.Failed = append(f.Failed, p.label+" exit "+strconv.Itoa(c)) |
| + if f.Phase == "" { |
| + f.Phase, f.Exit = p.label, c |
| + } |
| + } |
| + if !ok && missing == "" { |
| + missing = p.label |
| + } |
| + } |
| + switch { |
| + case len(w.phases) == 0 && res.Reason == "checks_unavailable": |
| + missing = "gate start" |
| + case len(w.phases) == 0 && !stopped: |
| + missing = "srt start" |
| + } |
| + if stopped && missing != "" { |
| + f.Unfinished = missing + map[bool]string{true: " timed out", false: " stopped"}[f.TimedOut] |
| + } |
| + if f.Phase == "" { |
| + f.Phase = firstNonEmpty(missing, "run end") |
| + } |
| + var lines []string |
| + size := 0 |
| + for _, e := range w.errors { |
| + if e = cut(r.line(e), p2ExcerptBytes-size); e == "" { |
| + continue |
| + } |
| + lines = append(lines, e) |
| + if size += len(e) + len(" | "); size >= p2ExcerptBytes { |
| + break |
| + } |
| + } |
| + f.Excerpt = cut(strings.Join(lines, " | "), p2ExcerptBytes) |
| + if len(lines) > 0 { |
| + f.First = cut(lines[0], p2ShortBytes) |
| + } |
| + return f |
| +} |
| + |
| +// short is the failure for the probe's detail ("test build exit 65: |
| +// error: ..."); clean then keeps it inside the capability string rules. |
| +func (f p2Failure) short() string { |
| + parts := append([]string{}, f.Failed...) |
| + if f.Unfinished != "" { |
| + parts = append(parts, f.Unfinished) |
| + } |
| + if len(parts) == 0 { |
| + if f.Exit < 0 { |
| + parts = append(parts, f.Phase+" failed") |
| + } else { |
| + parts = append(parts, f.Phase+" exit "+strconv.Itoa(f.Exit)) |
| + } |
| + } |
| + s := strings.Join(parts, ", ") |
| + if f.First != "" { |
| + s += ": " + f.First |
| + } |
| + return s |
| +} |
| + |
| +// redactor takes out of an output line what must never leave the Mac: |
| +// the secrets it is given (the sentinel secret and its prefixes, the |
| +// Keychain service, the targets file's lines and values) and every path |
| +// under a home, kept as its last element only. |
| +type redactor struct { |
| + secrets []string |
| + homes *regexp.Regexp |
| +} |
| + |
| +func newRedactor(secrets, homes []string) redactor { |
| + var s []string |
| + for _, x := range secrets { |
| + if x != "" { |
| + s = append(s, x) |
| + } |
| + } |
| + // Longest first: a prefix must not leave the rest of a longer one. |
| + sort.SliceStable(s, func(i, j int) bool { return len(s[i]) > len(s[j]) }) |
| + h := []string{regexp.QuoteMeta("/Users/")} |
| + for _, x := range homes { |
| + if x = strings.TrimRight(x, "/"); x != "" { |
| + h = append(h, regexp.QuoteMeta(x)) |
| + } |
| + } |
| + sort.SliceStable(h, func(i, j int) bool { return len(h[i]) > len(h[j]) }) |
| + return redactor{secrets: s, homes: regexp.MustCompile("(?:/private)?(?:" + strings.Join(h, "|") + ")[^\\s'\"`:,;()<>\\[\\]]*")} |
| +} |
| + |
| +func (r redactor) line(s string) string { |
| + s = strings.ToValidUTF8(s, "") |
| + s = ansiEscape.ReplaceAllString(s, "") |
| + s = strings.Map(func(c rune) rune { |
| + if c < 0x20 || c == 0x7f || c >= 0x80 && c < 0xa0 { |
| + return ' ' |
| + } |
| + return c |
| + }, s) |
| + s = r.redact(s) |
| + s = r.homes.ReplaceAllStringFunc(s, func(p string) string { |
| + base := path.Base(strings.TrimRight(p, "/")) |
| + if base == "." || base == "/" || base == "Users" { |
| + return "[home]" |
| + } |
| + return "[home]..." + base |
| + }) |
| + // Again after the paths: a last element keeps no part of a secret. |
| + s = r.redact(s) |
| + return strings.Join(strings.Fields(s), " ") |
| +} |
| + |
| +func (r redactor) redact(s string) string { |
| + for _, x := range r.secrets { |
| + s = strings.ReplaceAll(s, x, "[redacted]") |
| + } |
| + return s |
| +} |
| + |
| +// cut keeps at most n bytes of s, whole runes only. |
| +func cut(s string, n int) string { |
| + if n <= 0 { |
| + return "" |
| + } |
| + if len(s) <= n { |
| + return s |
| + } |
| + s = s[:n] |
| + for len(s) > 0 && !utf8.ValidString(s) { |
| + s = s[:len(s)-1] |
| + } |
| + return s |
| +} |
diff --git a/internal/runner/mac/p2why_test.go b/internal/runner/mac/p2why_test.go| new file mode 100644 |
| index 00000000..ad291225 |
| --- /dev/null |
| +++ b/internal/runner/mac/p2why_test.go |
| @@ -0,0 +1,208 @@ |
| +package mac |
| + |
| +import ( |
| + "context" |
| + "fmt" |
| + "os" |
| + "strings" |
| + "sync" |
| + "testing" |
| + |
| + "amadan.net/oficina/equipo/internal/wire" |
| +) |
| + |
| +// warned records what P2 said to runner.log. |
| +type warned struct { |
| + mu sync.Mutex |
| + calls [][]any |
| +} |
| + |
| +func (w *warned) warn(msg string, args ...any) { |
| + w.mu.Lock() |
| + defer w.mu.Unlock() |
| + w.calls = append(w.calls, append([]any{msg}, args...)) |
| +} |
| + |
| +func (w *warned) attr(i int, key string) string { |
| + w.mu.Lock() |
| + defer w.mu.Unlock() |
| + c := w.calls[i] |
| + for j := 1; j+1 < len(c); j += 2 { |
| + if c[j] == key { |
| + return fmt.Sprint(c[j+1]) |
| + } |
| + } |
| + return "" |
| +} |
| + |
| +// A real build and test prints far more than the gate keeps (its last |
| +// 200 lines), the script build's report lines and success line first: |
| +// P2 reads the whole output as it comes, so a full run is still judged. |
| +func TestP2ReadsTheWholeOutput(t *testing.T) { |
| + f := newProbeFixture(t, allLines("denied"), "FAKE_NOISE=1") |
| + var w warned |
| + f.h.Warn = w.warn |
| + p, ran, _ := probeP2(context.Background(), f.h, Capabilities(context.Background(), f.h.Exec, f.h.Tools)) |
| + if p.Verdict != wire.ProbeDenied || !ran || len(w.calls) != 0 { |
| + t.Fatalf("a long, complete run: %+v ran=%v warned=%v", p, ran, w.calls) |
| + } |
| +} |
| + |
| +// Each step of the srt run that fails is named in P2's detail with its |
| +// exit and first error line, and once in runner.log with the bounded |
| +// excerpt; P2 is never denied for it. |
| +func TestP2SaysWhichStepFailed(t *testing.T) { |
| + for _, c := range []struct{ env, phase, detail string }{ |
| + {"FAKE_BUILD_FAIL=1", "script build", "xcodebuild did not run in srt: script build exit 65: Sandbox: deny(1) mach-lookup com.apple.dt.example"}, |
| + {"FAKE_RESOLVE_FAIL=1", "package resolve", "xcodebuild did not run in srt: package resolve exit 74: xcodebuild: error: Could not resolve package dependencies:"}, |
| + {"FAKE_TEST_BUILD_FAIL=error: no such module 'XCTest'", "test build", "xcodebuild did not run in srt: test build exit 65: error: no such module 'XCTest'"}, |
| + {"FAKE_BOOT_FAIL=1", "simulator boot", "xcodebuild did not run in srt: simulator boot exit 149: Unable to boot device: error: launchd_sim failed"}, |
| + {"FAKE_RUN_FAIL=1", "test run", "xcodebuild did not run in srt: test run exit 65: xcodebuild: error: Failed to establish communication with the test runner."}, |
| + } { |
| + f := newProbeFixture(t, allLines("denied"), c.env) |
| + var w warned |
| + f.h.Warn = w.warn |
| + p, ran, _ := probeP2(context.Background(), f.h, Capabilities(context.Background(), f.h.Exec, f.h.Tools)) |
| + if ran || p.Verdict != wire.ProbeFailed || !strings.HasSuffix(p.Detail, c.detail) { |
| + t.Fatalf("%s: %+v ran=%v", c.phase, p, ran) |
| + } |
| + if err := wire.ValidCapabilities(wire.Capabilities{Probes: []wire.Probe{p}}); err != nil { |
| + t.Fatalf("%s: detail outside the capability rules: %v", c.phase, err) |
| + } |
| + if len(w.calls) != 1 || w.calls[0][0] != "p2 srt run failed" || w.attr(0, "phase") != c.phase || w.attr(0, "excerpt") == "" || w.attr(0, "timed_out") != "false" { |
| + t.Fatalf("%s: warned %v", c.phase, w.calls) |
| + } |
| + } |
| + // No step reported at all: srt itself did not start the command. |
| + f := newProbeFixture(t, allLines("denied")) |
| + if err := os.WriteFile(f.h.Tools.SRT, []byte("#!/bin/bash\necho 'Error: Refusing to run with the built-in defaults' >&2\nexit 1\n"), 0700); err != nil { |
| + t.Fatal(err) |
| + } |
| + 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 15 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) |
| + } |
| +} |
| + |
| +// What P2 says about a failure never carries the sentinel secret, the |
| +// Keychain service, the targets file's contents or a path under a home, |
| +// even when the failing tool prints all of them. |
| +func TestP2FailureIsRedacted(t *testing.T) { |
| + leak := `t=../equipo-targets.txt; echo "error: cannot read $(sed -n 's/^state=//p' $t)"; echo "error: no item $(sed -n 's/^keychain=//p' $t) in $(sed -n 's/^keychain_file=//p' $t)"; echo "error: $(tr '\n' ' ' < $t)"; printf 'error: \033[31mred\033[0m and \001bell\n'` |
| + f := newProbeFixture(t, allLines("denied")) |
| + xb, _ := os.ReadFile(f.h.Tools.Xcodebuild) |
| + patched := strings.Replace(string(xb), `[ -n "$FAKE_TEST_BUILD_FAIL" ] &&`, `{ `+leak+`; exit 65; }; [ -n "$FAKE_TEST_BUILD_FAIL" ] &&`, 1) |
| + if err := os.WriteFile(f.h.Tools.Xcodebuild, []byte(patched), 0700); err != nil { |
| + t.Fatal(err) |
| + } |
| + var w warned |
| + f.h.Warn = w.warn |
| + f.h.Paths.OtherHomes = []string{"/Users/paul"} |
| + p, _, _ := probeP2(context.Background(), f.h, Capabilities(context.Background(), f.h.Exec, f.h.Tools)) |
| + if len(w.calls) != 1 || w.attr(0, "phase") != "test build" { |
| + t.Fatalf("warned %v", w.calls) |
| + } |
| + excerpt := w.attr(0, "excerpt") |
| + said := p.Detail + "\n" + fmt.Sprint(w.calls) |
| + for _, bad := range []string{f.dir, "/Users/paul", "io.amadan.equipo.probe.", "probe-sentinel-", "login.keychain", "port_", "keychain=", "example.com", "\x1b", "\x01"} { |
| + if strings.Contains(said, bad) { |
| + t.Fatalf("%q left in %q", bad, said) |
| + } |
| + } |
| + if !strings.Contains(excerpt, "error: cannot read [redacted] | error: no item [redacted] in [redacted]") || !strings.Contains(excerpt, "red and bell") || len(excerpt) > p2ExcerptBytes { |
| + t.Fatalf("excerpt %q", excerpt) |
| + } |
| +} |
| + |
| +// The judge of a failure from recorded gate outputs: the step a timeout |
| +// stopped, srt or the gate not starting, every step passing yet no |
| +// success line, and the excerpt's bounds (five lines, 400 bytes, no |
| +// control characters). |
| +func TestP2FailureFromGateOutput(t *testing.T) { |
| + red := newRedactor([]string{"0123456789abcdef"}, []string{"/Users/equipo-paul"}) |
| + feed := func(lines ...string) *p2Watch { |
| + w := newP2Watch() |
| + for _, l := range lines { |
| + w.line(l) |
| + } |
| + return w |
| + } |
| + for name, c := range map[string]struct { |
| + w *p2Watch |
| + res Result |
| + phase string |
| + short string |
| + timeup bool |
| + }{ |
| + "timed out in the test build": {feed("EQUIPO-PHASE script-build 0", "EQUIPO-PHASE package-resolve 0"), Result{Code: -1, Reason: "checks_timeout"}, "test build", "test build timed out", true}, |
| + "a failure, then a timeout": {feed("EQUIPO-PHASE script-build 65", "EQUIPO-PHASE package-resolve 0"), Result{Code: -1, Reason: "checks_timeout"}, "script build", "script build exit 65, test build timed out", true}, |
| + "stopped by the run's limit": {feed(), Result{Code: -1, Reason: "cancelled"}, "script build", "script build stopped", false}, |
| + "srt refused its settings": {feed("Error: /Users/equipo-paul/.local/s.json does not exist."), Result{Code: 1}, "srt start", "srt start exit 1: Error: [home]...s.json does not exist.", false}, |
| + "the gate could not start": {feed(), Result{Code: -1, Reason: "checks_unavailable"}, "gate start", "gate start failed", false}, |
| + "no success line": {feed("EQUIPO-PHASE script-build 0", "EQUIPO-PHASE package-resolve 0", "EQUIPO-PHASE test-build 0", "EQUIPO-PHASE simulator-boot 0", "EQUIPO-PHASE test-run 0", "** BUILD SUCCEEDED **"), |
| + Result{Code: 0}, "run end", "run end exit 0", false}, |
| + } { |
| + if c.w.ran(c.res) { |
| + t.Fatalf("%s: taken as ran", name) |
| + } |
| + f := c.w.failure(c.res, red) |
| + if f.Phase != c.phase || f.short() != c.short || f.TimedOut != c.timeup { |
| + t.Fatalf("%s: %+v short %q", name, f, f.short()) |
| + } |
| + } |
| + var lines []string |
| + for i := 0; i < 9; i++ { |
| + lines = append(lines, fmt.Sprintf("/Users/equipo-paul/x/f%d.swift:1:2: error: \x1b[1m%s\x07 0123456789abcdef", i, strings.Repeat("é", 60))) |
| + } |
| + lines = append(lines, lines[0]) |
| + f := feed(lines...).failure(Result{Code: 65}, red) |
| + if n := strings.Count(f.Excerpt, " | ") + 1; n > p2ErrorLines || len(f.Excerpt) > p2ExcerptBytes || len(f.First) > p2ShortBytes || !strings.HasPrefix(f.First, "[home]...f0.swift:1:2: error: é") { |
| + t.Fatalf("bounds: %d lines, %d bytes, first %q", n, len(f.Excerpt), f.First) |
| + } |
| + for _, r := range f.Excerpt { |
| + if r < 0x20 || r == 0x7f || r == '�' { |
| + t.Fatalf("control or broken character in %q", f.Excerpt) |
| + } |
| + } |
| + if strings.Contains(f.Excerpt, "0123456789abcdef") || strings.Contains(f.Excerpt, "equipo-paul") { |
| + t.Fatalf("not redacted: %q", f.Excerpt) |
| + } |
| + // A run that did everything, by every account. |
| + all := feed("EQUIPO-PHASE script-build 0", "EQUIPO-PHASE package-resolve 0", "EQUIPO-PHASE test-build 0", "EQUIPO-PHASE simulator-boot 0", "EQUIPO-PHASE test-run 0", "** BUILD SUCCEEDED **", "** TEST BUILD SUCCEEDED **", "** TEST EXECUTE SUCCEEDED **") |
| + if !all.ran(Result{Code: 0}) || all.ran(Result{Code: 1}) { |
| + t.Fatal("ran") |
| + } |
| +} |
| + |
| +// However long the reason, the detail keeps what decides trust (the |
| +// end not proven) and stays a capability string: the reason is cut. |
| +func TestP2DetailKeepsTheEnd(t *testing.T) { |
| + unknown := []string{"script.state", "script.tcp", "script.dns", "script.keychain", "plugin.state", "plugin.tcp", "plugin.dns", "plugin.keychain", "test.state", "test.tcp", "test.dns", "test.keychain"} |
| + d := p2Detail(map[string][]string{"unknown": unknown[:11], "allowed": unknown[11:]}, 12, false, false, "test build exit 65: "+strings.Repeat("error: x ", 60)) |
| + if !strings.Contains(d, "end not proven; xcodebuild did not run in srt: test build exit 65: error") || len(d) > wire.MaxCapabilityString { |
| + t.Fatalf("detail %q", d) |
| + } |
| + if d := p2Detail(map[string][]string{"unknown": unknown}, 12, false, true, ""); d != "not shown denied: all 12 attempts; xcodebuild did not run in srt" { |
| + t.Fatalf("detail %q", d) |
| + } |
| +} |
| + |
| +// P2's script runs every step it names, in order, under the gate's |
| +// TMPDIR, with the package's plugins allowed to run unvalidated and |
| +// nothing that reaches the network. |
| +func TestP2Script(t *testing.T) { |
| + s := p2Script(quote("/usr/bin/xcodebuild"), quote("/usr/bin/xcrun"), "ABCDEF01-2345-6789-ABCD-EF0123456789") |
| + last := -1 |
| + for _, p := range p2Phases { |
| + i := strings.Index(s, "phase "+p.key+" ") |
| + if i < last { |
| + t.Fatalf("%s missing or out of order in %s", p.key, s) |
| + } |
| + last = i |
| + } |
| + if strings.Count(s, "-skipPackagePluginValidation") != 3 || strings.Count(s, `-derivedDataPath "$TMPDIR/dd"`) != 3 || strings.Contains(s, "http") { |
| + t.Fatalf("script %s", s) |
| + } |
| +} |
diff --git a/internal/runner/mac/probe.go b/internal/runner/mac/probe.go| index b49a1e58..68403680 100644 |
| --- a/internal/runner/mac/probe.go |
| +++ b/internal/runner/mac/probe.go |
| @@ -55,6 +55,9 @@ type ProbeHost struct { |
| Wait time.Duration |
| // Limit bounds the whole run (ProbeLimit). |
| Limit time.Duration |
| + // Warn hears why P2's srt run did not fully succeed, once per run, |
| + // redacted (runner.log); nil says nothing. |
| + Warn func(msg string, args ...any) |
| // late notes the queries that did not answer in time (RunProbes). |
| late *queries |
| } |
| @@ -345,24 +348,57 @@ func JudgeP2(got map[string]string, f P2Facts) (verdict string, groups map[strin |
| return verdict, groups |
| } |
| -func p2Detail(groups map[string][]string, total int, srtRan bool) string { |
| +// 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. |
| +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"}} { |
| - if len(groups[g.key]) > 0 { |
| + 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. |
| + 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], " ")) |
| } |
| } |
| if len(parts) == 0 { |
| parts = append(parts, fmt.Sprintf("all %d attempts denied", total)) |
| } |
| - if srtRan { |
| + if !ended { |
| + parts = append(parts, "end not proven") |
| + } |
| + switch { |
| + case srtRan: |
| parts = append(parts, "xcodebuild ran in srt") |
| - } else { |
| + case why != "": |
| + parts = append(parts, "xcodebuild did not run in srt: "+why) |
| + default: |
| parts = append(parts, "xcodebuild did not run in srt") |
| } |
| return clean(strings.Join(parts, "; ")) |
| } |
| +// p2Script is P2's run under srt, one step at a time, each reporting |
| +// its exit (EQUIPO-PHASE <step> <exit>) so a failure names its step: the |
| +// hostile script phase's build, then the package's resolve, test build, |
| +// the simulator's boot and the hostile test on it. |
| +func p2Script(xb, xcrun, udid string) string { |
| + dest := quote("platform=iOS Simulator,id=" + udid) |
| + pkg := ` -scheme "$s" -derivedDataPath "$TMPDIR/dd" -skipPackagePluginValidation` |
| + return `phase() { p=$1; shift; "$@"; c=$?; echo "EQUIPO-PHASE $p $c"; return $c; } |
| +(cd project && phase script-build ` + xb + ` -project Hostile.xcodeproj -target HostileScript -configuration Debug build SYMROOT="$TMPDIR/sym" OBJROOT="$TMPDIR/obj"); a=$? |
| +cd package || exit 1 |
| +s=Hostile-Package; ` + xb + ` -list 2>/dev/null | grep -q Hostile-Package || s=Hostile |
| +phase package-resolve ` + xb + ` -resolvePackageDependencies` + pkg + ` && |
| +phase test-build ` + xb + ` build-for-testing -destination ` + dest + pkg + ` && |
| +phase simulator-boot ` + xcrun + ` simctl bootstatus ` + quote(udid) + ` -b && |
| +phase test-run ` + xb + ` test-without-building -destination ` + dest + ` -only-testing:HostileTests/HostileTests/testHostile` + pkg + ` |
| +b=$? |
| +[ "$a" = 0 ] && [ "$b" = 0 ]` |
| +} |
| + |
| // probeP2 runs the hostile fixture under the checks profile. |
| func probeP2(ctx context.Context, h ProbeHost, caps wire.Capabilities) (wire.Probe, bool, string) { |
| fail := func(verdict, why string) (wire.Probe, bool, string) { |
| @@ -440,15 +476,30 @@ func probeP2(ctx context.Context, h ProbeHost, caps wire.Capabilities) (wire.Pro |
| if err := os.WriteFile(filepath.Join(root, "equipo-targets.txt"), []byte(strings.Join(targets, "\n")+"\n"), 0600); err != nil { |
| return fail(wire.ProbeUnavailable, "the fixture could not be prepared") |
| } |
| - xb := quote(h.Tools.Xcodebuild) |
| - script := `cd project && ` + xb + ` -project Hostile.xcodeproj -target HostileScript -configuration Debug build SYMROOT="$TMPDIR/sym" OBJROOT="$TMPDIR/obj" |
| -cd ../package && s=Hostile-Package; ` + xb + ` -list 2>/dev/null | grep -q Hostile-Package || s=Hostile |
| -` + xb + ` test -scheme "$s" -destination ` + quote("platform=iOS Simulator,id="+sim.UDID) + ` -only-testing:HostileTests/HostileTests/testHostile -derivedDataPath "$TMPDIR/dd" -skipPackagePluginValidation` |
| - res := h.Gate(true).Run(ctx, "probe-p2-"+secret[:8], root, []string{"/bin/bash", "-c", script}, 20*time.Minute, func(string) error { return nil }) |
| + script := p2Script(quote(h.Tools.Xcodebuild), quote(h.Tools.Xcrun), sim.UDID) |
| + g, watch := h.Gate(true), newP2Watch() |
| + g.Watch = watch.line |
| + res := g.Run(ctx, "probe-p2-"+secret[:8], root, []string{"/bin/bash", "-c", script}, 20*time.Minute, func(string) error { return nil }) |
| mu.Lock() |
| defer mu.Unlock() |
| - srtRan := res.Code == 0 && strings.Contains(res.Output, "** BUILD SUCCEEDED **") && strings.Contains(res.Output, "** TEST SUCCEEDED **") |
| - verdict, groups := JudgeP2(ParseAttempts(res.Output), facts) |
| + srtRan := watch.ran(res) |
| + verdict, groups := JudgeP2(ParseAttempts(watch.attemptsSeen()), facts) |
| + why := "" |
| + if !srtRan { |
| + // Never the secret, the service, the targets file's contents or a |
| + // path under a home. |
| + secrets := []string{service, secret, secret[:12], secret[:8]} |
| + for _, t := range targets { |
| + _, v, _ := strings.Cut(t, "=") |
| + secrets = append(secrets, t, v) |
| + } |
| + red := newRedactor(secrets, append([]string{h.Paths.Home, h.Paths.StateDir, h.Scratch}, h.Paths.OtherHomes...)) |
| + f := watch.failure(res, red) |
| + why = f.short() |
| + if h.Warn != nil { |
| + h.Warn("p2 srt run failed", "phase", f.Phase, "failed", strings.Join(f.Failed, ", "), "unfinished", f.Unfinished, "exit", f.Exit, "timed_out", f.TimedOut, "gate_reason", res.Reason, "excerpt", f.Excerpt) |
| + } |
| + } |
| // Denied counts only for a run that did everything and was proven |
| // to end: the hostile build and test completed under srt, and nothing |
| // of them is left. |
| @@ -467,10 +518,7 @@ cd ../package && s=Hostile-Package; ` + xb + ` -list 2>/dev/null | grep -q Hosti |
| if !facts.Home { |
| total -= len(probePlaces) |
| } |
| - detail := p2Detail(groups, total, srtRan) |
| - if !res.Terminated { |
| - detail = clean(detail + "; end not proven") |
| - } |
| + detail := p2Detail(groups, total, srtRan, res.Terminated, why) |
| return wire.Probe{ID: "P2", Verdict: verdict, Detail: detail}, srtRan, keychain |
| } |
diff --git a/internal/runner/mac/probe_test.go b/internal/runner/mac/probe_test.go| index 5643f07d..0bfa13c8 100644 |
| --- a/internal/runner/mac/probe_test.go |
| +++ b/internal/runner/mac/probe_test.go |
| @@ -17,27 +17,46 @@ import ( |
| // fakeXcodebuild plays xcodebuild for the fixture: it really reads the |
| // targets file the probe wrote, prints the report lines a scenario |
| -// gives, and with FAKE_CONNECT connects to the test's loopback port |
| -// while saying "denied" (the probe's listener must catch the lie). |
| +// gives (the plugin's while the test target builds), and with |
| +// FAKE_CONNECT connects to the test's loopback port while saying |
| +// "denied" (the probe's listener must catch the lie). FAKE_NOISE prints |
| +// what a real build does: far more than the gate's last 200 lines. |
| +// FAKE_*_FAIL fails a step the way it fails on a Mac. |
| const fakeXcodebuild = `#!/bin/bash |
| +noise() { [ -n "$FAKE_NOISE" ] && for i in $(seq 1 300); do echo "CompileSwift normal arm64 step $i"; done; true; } |
| case "$*" in |
| *-list*) echo " Schemes:"; echo " Hostile-Package"; exit 0 ;; |
| *HostileScript*) |
| [ -r ../equipo-targets.txt ] || { echo "no targets"; exit 3; } |
| + case "$TMPDIR" in "$FAKE_DIR"/scratch/*) ;; *) echo "error: unable to create directory $TMPDIR/sym (Permission denied)"; echo "** BUILD FAILED **"; exit 65 ;; esac |
| [ -n "$FAKE_BUILD_FAIL" ] && { echo "Sandbox: deny(1) mach-lookup com.apple.dt.example"; echo "** BUILD FAILED **"; exit 65; } |
| [ -n "$FAKE_LINES_THEN_FAIL" ] && { cat "$FAKE_DIR/script.out"; echo "** BUILD FAILED **"; exit 65; } |
| - cat "$FAKE_DIR/script.out"; echo "** BUILD SUCCEEDED **"; exit 0 ;; |
| + cat "$FAKE_DIR/script.out"; noise; echo "** BUILD SUCCEEDED **"; exit 0 ;; |
| +*-resolvePackageDependencies*) |
| + [ -n "$FAKE_RESOLVE_FAIL" ] && { echo "xcodebuild: error: Could not resolve package dependencies:"; echo " sandbox-exec: sandbox_apply: Operation not permitted"; exit 74; } |
| + echo "resolved source packages:"; exit 0 ;; |
| +*build-for-testing*) |
| + [ -n "$FAKE_TEST_BUILD_FAIL" ] && { printf '%s\n' "$FAKE_TEST_BUILD_FAIL"; echo "** TEST BUILD FAILED **"; exit 65; } |
| + cat "$FAKE_DIR/plugin.out"; noise; echo "** TEST BUILD SUCCEEDED **"; exit 0 ;; |
| *testHostile*) |
| - case "$*" in *"platform=iOS Simulator,id="*) ;; *) echo "testHostile not on an iOS simulator"; exit 70 ;; esac |
| + case "$*" in *test-without-building*"platform=iOS Simulator,id="*) ;; *) echo "testHostile not on an iOS simulator"; exit 70 ;; esac |
| + [ -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_CONNECT" ]; then exec 3<>"/dev/tcp/127.0.0.1/$(sed -n 's/^port_test=//p' $t)"; fi |
| - cat "$FAKE_DIR/test.out"; echo "** TEST SUCCEEDED **"; exit 0 ;; |
| + cat "$FAKE_DIR/test.out"; noise; echo "** TEST EXECUTE SUCCEEDED **"; exit 0 ;; |
| *testWait*) echo "EQUIPO-PROBE wait started"; exec sleep 600 ;; |
| esac |
| exit 64 |
| ` |
| +// fakeXcrun plays xcrun simctl bootstatus for P2's simulator boot. |
| +const fakeXcrun = `#!/bin/bash |
| +[ "$1 $2 $4" = "simctl bootstatus -b" ] || exit 64 |
| +[ -n "$FAKE_BOOT_FAIL" ] && { echo "An error was encountered processing the command (domain=com.apple.CoreSimulator.SimError, code=405):"; echo "Unable to boot device: error: launchd_sim failed"; exit 149; } |
| +echo "Device already booted, nothing to do." |
| +` |
| + |
| func allLines(result string) map[string]string { |
| out := map[string]string{} |
| for _, place := range []string{"script", "plugin", "test"} { |
| @@ -62,18 +81,18 @@ func newProbeFixture(t *testing.T, lines map[string]string, env ...string) *prob |
| f := &probeFixture{dir: root} |
| xb := filepath.Join(root, "xcodebuild") |
| srt := filepath.Join(root, "srt") |
| - for p, body := range map[string]string{xb: fakeXcodebuild, srt: fakeSRT} { |
| + xcrun := filepath.Join(root, "xcrun") |
| + for p, body := range map[string]string{xb: fakeXcodebuild, srt: fakeSRT, xcrun: fakeXcrun} { |
| if err := os.WriteFile(p, []byte(body), 0700); err != nil { |
| t.Fatal(err) |
| } |
| } |
| - // The script and plugin places print through the build log; the |
| - // fake prints the plugin's beside the script's. |
| - if err := os.WriteFile(filepath.Join(root, "script.out"), []byte(lines["script"]+lines["plugin"]), 0600); err != nil { |
| - t.Fatal(err) |
| - } |
| - if err := os.WriteFile(filepath.Join(root, "test.out"), []byte(lines["test"]), 0600); err != nil { |
| - t.Fatal(err) |
| + // The script and plugin places print through the build log: the |
| + // script's in the project's build, the plugin's in the test build. |
| + for name, place := range map[string]string{"script.out": "script", "plugin.out": "plugin", "test.out": "test"} { |
| + if err := os.WriteFile(filepath.Join(root, name), []byte(lines[place]), 0600); err != nil { |
| + t.Fatal(err) |
| + } |
| } |
| state := filepath.Join(root, "state") |
| if err := os.MkdirAll(state, 0700); err != nil { |
| @@ -91,7 +110,7 @@ func newProbeFixture(t *testing.T, lines map[string]string, env ...string) *prob |
| key := strings.Join(append([]string{name}, args...), " ") |
| f.execLog = append(f.execLog, key) |
| switch { |
| - case key == "xcrun simctl list -j devices available": |
| + case key == xcrun+" simctl list -j devices available": |
| return string(sims), nil |
| case strings.HasPrefix(key, "/usr/bin/security "): |
| return "", nil |
| @@ -104,7 +123,7 @@ func newProbeFixture(t *testing.T, lines map[string]string, env ...string) *prob |
| return "", errors.New("not recorded: " + key) |
| } |
| base := []string{"PATH=/usr/bin:/bin", "HOME=" + root, "FAKE_DIR=" + root, "FAKE_SRT_SEEN=" + filepath.Join(root, "seen.json")} |
| - f.h = ProbeHost{Exec: exec, Tools: Tools{Xcodebuild: xb, Xcrun: "xcrun", Node: "node", SRT: srt, RG: "rg"}, |
| + f.h = ProbeHost{Exec: exec, Tools: Tools{Xcodebuild: xb, Xcrun: xcrun, Node: "node", SRT: srt, RG: "rg"}, |
| Paths: Paths{Home: root, StateDir: state, OtherHomes: []string{"/Users/Shared", "/Users/paul"}}, |
| Scratch: filepath.Join(root, "scratch"), UID: 501, Version: "abc1234", |
| Gate: func(sandboxed bool) *Gate { |
| @@ -198,7 +217,7 @@ func TestP2IsDeniedOnlyWhenEverythingIs(t *testing.T) { |
| t.Fatalf("DNS control failed outside: %+v", p) |
| } |
| f = newProbeFixture(t, allLines("denied"), "FAKE_BUILD_FAIL=1") |
| - if p, ran, _ := probeP2(context.Background(), f.h, Capabilities(context.Background(), f.h.Exec, f.h.Tools)); ran || p.Verdict != wire.ProbeFailed || !strings.HasSuffix(p.Detail, "xcodebuild did not run in srt") { |
| + if p, ran, _ := probeP2(context.Background(), f.h, Capabilities(context.Background(), f.h.Exec, f.h.Tools)); ran || p.Verdict != wire.ProbeFailed || !strings.HasSuffix(p.Detail, "xcodebuild did not run in srt: script build exit 65: Sandbox: deny(1) mach-lookup com.apple.dt.example") { |
| t.Fatalf("the fixture did not build under srt: %+v ran=%v", p, ran) |
| } |
| f = newProbeFixture(t, allLines("denied")) |
diff --git a/internal/runner/thin/mac.go b/internal/runner/thin/mac.go| index c324c295..9dd25d4b 100644 |
| --- a/internal/runner/thin/mac.go |
| +++ b/internal/runner/thin/mac.go |
| @@ -641,6 +641,14 @@ func (h *macHost) probeHost(version string, gate func(string, string) *mac.Gate) |
| }, |
| Exposed: mac.Exposed, |
| Listen: func() (net.Listener, error) { return net.Listen("tcp", "127.0.0.1:0") }, |
| + Warn: h.warn, |
| + } |
| +} |
| + |
| +// warn is runner.log at WARN, nil when there is no log. |
| +func (h *macHost) warn(msg string, args ...any) { |
| + if h.log != nil { |
| + h.log.Warn(msg, args...) |
| } |
| } |
diff --git a/internal/runner/thin/startup_logs_test.go b/internal/runner/thin/startup_logs_test.go| index f1bfae02..16264388 100644 |
| --- a/internal/runner/thin/startup_logs_test.go |
| +++ b/internal/runner/thin/startup_logs_test.go |
| @@ -202,3 +202,15 @@ func TestMacSlowCommandLogged(t *testing.T) { |
| t.Fatalf("a quick command logged: %v %q", err, quiet.String()) |
| } |
| } |
| + |
| +// Why P2's srt run failed reaches runner.log at WARN through the probes' |
| +// host; a host without a log says nothing and does not fail. |
| +func TestMacP2FailureLogged(t *testing.T) { |
| + logs := &syncBuffer{} |
| + h := &macHost{log: slog.New(slog.NewTextHandler(logs, nil))} |
| + h.probeHost("v1", nil).Warn("p2 srt run failed", "phase", "test build", "exit", 65) |
| + if out := logs.String(); !strings.Contains(out, `level=WARN msg="p2 srt run failed" phase="test build" exit=65`) { |
| + t.Fatalf("runner.log:\n%s", out) |
| + } |
| + (&macHost{}).probeHost("v1", nil).Warn("p2 srt run failed") |
| +} |
diff --git a/scripts/runner-reference-allowlist.json b/scripts/runner-reference-allowlist.json| index 0e5c9420..206b29f8 100644 |
| --- a/scripts/runner-reference-allowlist.json |
| +++ b/scripts/runner-reference-allowlist.json |
| @@ -9087,14 +9087,14 @@ |
| }, |
| { |
| "path": "internal/runner/mac/probe_test.go", |
| - "line_sha256": "44950e069b32e9cac0bd1be01071e463f77784b7352d107830249ae15b225ac1", |
| + "line_sha256": "25ec48979ef44aafe04613b442250cf081684a4edf4ac97eb3ad8ce8ac9e4af1", |
| "match": "Node", |
| "count": 1, |
| "reason": "Mac runner (darwin worker): the runner executable, its launchd agent, install paths, the pinned srt package and Node it needs, and their tests and docs." |
| }, |
| { |
| "path": "internal/runner/mac/probe_test.go", |
| - "line_sha256": "44950e069b32e9cac0bd1be01071e463f77784b7352d107830249ae15b225ac1", |
| + "line_sha256": "25ec48979ef44aafe04613b442250cf081684a4edf4ac97eb3ad8ce8ac9e4af1", |
| "match": "node", |
| "count": 1, |
| "reason": "Mac runner (darwin worker): the runner executable, its launchd agent, install paths, the pinned srt package and Node it needs, and their tests and docs." |