oficina / equipo Public

Darwin review: P2 on the simulator, verdicts this process made

Astra round 1, findings 1 and 2:
- P2's hostile test runs on the newest iOS simulator, as checks do
  (no simulator: P2 unavailable); from there it tries the host's login
  keychain file, since a simulator's Keychain API is its own. Denied
  needs the hostile build and test completed under srt and the end
  proven. P6's test hashes and writes files until it is killed.
- The probe verdict lives only in the worker's memory. Nothing on disk
  is read back as one; `equipo-runner probe` only asks the worker to
  probe again. A report is trusted while it is this version's, for this
  profile, made with the srt, Node and ripgrep on disk now (their
  fingerprint), and under a day old; otherwise checks run as not
  verified, labelled outside the sandbox, and the probes run again.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev 5dd0da42c770af4bb4b32a9be93044871b1a40dc parent e02aafb
7 files changed, +352 −134
  • internal/runner/mac/fixtures/hostile/package/Plugins/HostilePlugin/HostilePlugin.swift +6 −0
  • internal/runner/mac/fixtures/hostile/package/Tests/HostileTests/HostileTests.swift +20 −1
  • internal/runner/mac/gate_test.go +6 −4
  • internal/runner/mac/probe.go +24 −41
  • internal/runner/mac/probe_test.go +42 −2
  • internal/runner/thin/mac.go +138 −47
  • internal/runner/thin/mac_test.go +116 −39
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 552bf6c9..e019bed6 100644
--- a/internal/runner/mac/fixtures/hostile/package/Plugins/HostilePlugin/HostilePlugin.swift
+++ b/internal/runner/mac/fixtures/hostile/package/Plugins/HostilePlugin/HostilePlugin.swift
@@ -40,7 +40,13 @@ enum Attempts {
}
report("tcp", tcp(port: UInt16(t["port_" + place] ?? "") ?? 0))
report("dns", resolve(t["dns"] ?? ""))
+ #if os(iOS)
+ // A simulator's Keychain API is its own: try the host's login
+ // keychain file instead.
+ report("keychain", FileManager.default.contents(atPath: t["keychain_file"] ?? "") != nil)
+ #else
report("keychain", keychain(t["keychain"] ?? ""))
+ #endif
return lines
}
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 6a878fe8..2807b126 100644
--- a/internal/runner/mac/fixtures/hostile/package/Tests/HostileTests/HostileTests.swift
+++ b/internal/runner/mac/fixtures/hostile/package/Tests/HostileTests/HostileTests.swift
@@ -15,9 +15,22 @@ final class HostileTests: XCTestCase {
}
}
+ // Real work until it is killed: hashing and writing files in the
+ // test's temporary directory, so the simulator, its test runner and
+ // their files are busy when P6 kills the group.
func testWait() {
print("EQUIPO-PROBE wait started")
- Thread.sleep(forTimeInterval: 600)
+ let dir = FileManager.default.temporaryDirectory.appendingPathComponent("equipo-p6")
+ try? FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)
+ var value = Data(repeating: 1, count: 1 << 20)
+ let end = Date().addingTimeInterval(600)
+ var n = 0
+ while Date() < end {
+ for i in stride(from: 0, to: value.count, by: 4096) { value[i] = value[i] &+ UInt8(truncatingIfNeeded: n) }
+ try? value.write(to: dir.appendingPathComponent("chunk-\(n % 64)"))
+ n += 1
+ if n % 100 == 0 { print("EQUIPO-PROBE wait working \(n)") }
+ }
}
}
@@ -45,7 +58,13 @@ enum Attempts {
}
report("tcp", tcp(port: UInt16(t["port_" + place] ?? "") ?? 0))
report("dns", resolve(t["dns"] ?? ""))
+ #if os(iOS)
+ // A simulator's Keychain API is its own: try the host's login
+ // keychain file instead.
+ report("keychain", FileManager.default.contents(atPath: t["keychain_file"] ?? "") != nil)
+ #else
report("keychain", keychain(t["keychain"] ?? ""))
+ #endif
return lines
}
diff --git a/internal/runner/mac/gate_test.go b/internal/runner/mac/gate_test.go
index cbb47a03..e5fac5c9 100644
--- a/internal/runner/mac/gate_test.go
+++ b/internal/runner/mac/gate_test.go
@@ -159,10 +159,12 @@ func TestGateShutsDownWhatItBooted(t *testing.T) {
booted, down := []string{"A"}, []string{}
g.Booted = func(context.Context) []string { mu.Lock(); defer mu.Unlock(); return slices.Clone(booted) }
g.Shutdown = func(_ context.Context, u string) { mu.Lock(); down = append(down, u); mu.Unlock() }
- res := g.Run(context.Background(), "checks-e-1", dir, []string{"/bin/sh", "-c", "true"}, time.Minute, func(string) error {
- mu.Lock()
- booted = append(booted, "B")
- mu.Unlock()
+ res := g.Run(context.Background(), "checks-e-1", dir, []string{"/bin/sh", "-c", "true"}, time.Minute, func(id string) error {
+ if !strings.HasPrefix(id, "pg:0:") {
+ mu.Lock()
+ booted = append(booted, "B")
+ mu.Unlock()
+ }
return nil
})
if res.Code != 0 || !slices.Equal(down, []string{"B"}) {
diff --git a/internal/runner/mac/probe.go b/internal/runner/mac/probe.go
index eb73dee6..a122a1f6 100644
--- a/internal/runner/mac/probe.go
+++ b/internal/runner/mac/probe.go
@@ -64,6 +64,9 @@ type Report struct {
// SRTRanXcode: the fixture built and tested under srt with the checks
// profile, so srt can confine checks even when P2 is not denied.
SRTRanXcode bool `json:"srt_ran_xcode"`
+ // SRT fingerprints the srt, Node and ripgrep the probes ran with
+ // (set by the worker that made the report).
+ SRT string `json:"srt"`
}
// Probe is the result of one probe ("" verdict when it did not run).
@@ -80,12 +83,6 @@ func (r Report) Probe(id string) wire.Probe {
// say so (seatbelt).
func (r Report) Sandboxed() bool { return r.Probe("P2").Verdict == wire.ProbeDenied }
-// Current reports whether r was made by this runner version with this
-// checks profile; otherwise the probes run again.
-func (r Report) Current(version string) bool {
- return r.Version == version && r.Profile == ProfileDigest() && len(r.Probes) == len(wire.ProbeIDs)
-}
-
// ProfileDigest names the checks profile the probes judged: the
// settings over fixed paths, the Mach list and the fixture.
func ProfileDigest() string {
@@ -103,38 +100,6 @@ func ProfileDigest() string {
return hex.EncodeToString(h.Sum(nil))[:16]
}
-// LoadReport reads a saved report; SaveReport replaces it atomically.
-func LoadReport(file string) (Report, error) {
- var r Report
- raw, err := os.ReadFile(file)
- if err == nil {
- err = json.Unmarshal(raw, &r)
- }
- return r, err
-}
-
-func SaveReport(file string, r Report) error {
- raw, err := json.MarshalIndent(r, "", " ")
- if err != nil {
- return err
- }
- tmp, err := os.CreateTemp(filepath.Dir(file), ".probes-")
- if err != nil {
- return err
- }
- defer os.Remove(tmp.Name())
- if _, err = tmp.Write(raw); err == nil {
- err = tmp.Sync()
- }
- if cerr := tmp.Close(); err == nil {
- err = cerr
- }
- if err != nil {
- return err
- }
- return os.Rename(tmp.Name(), file)
-}
-
// RunProbes runs P1 to P7 (spec §6) and reports each. None needs a
// person: P3 and P5 say what they could not do and why.
func RunProbes(ctx context.Context, h ProbeHost) Report {
@@ -274,6 +239,12 @@ func probeP2(ctx context.Context, h ProbeHost, caps wire.Capabilities) (wire.Pro
if caps.Xcode.Version == "" {
return fail(wire.ProbeUnavailable, "no Xcode")
}
+ // The hostile test runs where production checks run: on an iOS
+ // simulator, through CoreSimulator and the test services.
+ sim, ok := NewestIPhone(caps.Simulators)
+ if !ok {
+ return fail(wire.ProbeUnavailable, "no iOS simulator")
+ }
root, err := copyFixture(h.Scratch)
if err != nil {
return fail(wire.ProbeUnavailable, "the fixture could not be copied")
@@ -323,19 +294,27 @@ func probeP2(ctx context.Context, h ProbeHost, caps wire.Capabilities) (wire.Pro
_, _ = h.Exec(context.WithoutCancel(ctx), "/usr/bin/security", "delete-generic-password", "-a", "equipo-probe", "-s", service)
}()
}
- targets = append(targets, "keychain="+service)
+ // On a simulator the Keychain API is the simulator's own: the test
+ // there tries the runner user's login keychain file instead.
+ targets = append(targets, "keychain="+service, "keychain_file="+filepath.Join(h.Paths.Home, "Library", "Keychains", "login.keychain-db"))
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 'platform=macOS' -only-testing:HostileTests/HostileTests/testHostile -derivedDataPath "$TMPDIR/dd" -skipPackagePluginValidation`
+` + 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 })
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)
+ // 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.
+ if !srtRan || !res.Terminated {
+ verdict = wire.ProbeFailed
+ }
keychain := "denied"
for _, list := range groups {
for _, k := range list {
@@ -348,7 +327,11 @@ cd ../package && s=Hostile-Package; ` + xb + ` -list 2>/dev/null | grep -q Hosti
if !facts.Home {
total -= len(probePlaces)
}
- return wire.Probe{ID: "P2", Verdict: verdict, Detail: p2Detail(groups, total, srtRan)}, srtRan, keychain
+ detail := p2Detail(groups, total, srtRan)
+ if !res.Terminated {
+ detail = clean(detail + "; end not proven")
+ }
+ return wire.Probe{ID: "P2", Verdict: verdict, Detail: detail}, srtRan, keychain
}
// otherHome is the home P2 tries: a person's, not /Users/Shared.
diff --git a/internal/runner/mac/probe_test.go b/internal/runner/mac/probe_test.go
index 1ef82e9a..b8ccfafd 100644
--- a/internal/runner/mac/probe_test.go
+++ b/internal/runner/mac/probe_test.go
@@ -25,8 +25,10 @@ case "$*" in
*HostileScript*)
[ -r ../equipo-targets.txt ] || { echo "no targets"; exit 3; }
[ -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 ;;
*testHostile*)
+ case "$*" in *"platform=iOS Simulator,id="*) ;; *) echo "testHostile not on an iOS simulator"; exit 70 ;; esac
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
@@ -136,7 +138,7 @@ func TestRunProbesAllDenied(t *testing.T) {
if !slices.Equal(ids, wire.ProbeIDs) {
t.Fatalf("probes %v", ids)
}
- if !r.Sandboxed() || !r.SRTRanXcode || !r.Current("abc1234") {
+ if !r.Sandboxed() || !r.SRTRanXcode || r.Version != "abc1234" || r.Profile != ProfileDigest() {
t.Fatalf("P2 %+v srt=%v", r.Probe("P2"), r.SRTRanXcode)
}
if p := r.Probe("P2"); p.Detail != "Unix permissions only: script.home plugin.home test.home; xcodebuild ran in srt" {
@@ -272,7 +274,12 @@ func TestFixtureShips(t *testing.T) {
if strings.Count(string(pbx), "ENABLE_USER_SCRIPT_SANDBOXING = NO;") != 2 {
t.Fatal("the script phase must turn Xcode's own script sandbox off, as a hostile repository would")
}
- if info, _ := os.Stat(filepath.Join(root, "project/hostile.sh")); info.Mode().Perm() != 0700 {
+ tests, _ := os.ReadFile(filepath.Join(root, "package/Tests/HostileTests/HostileTests.swift"))
+ wait := string(tests[strings.Index(string(tests), "func testWait"):])
+ if strings.Contains(wait, "Thread.sleep") || !strings.Contains(wait, "write(to:") || !strings.Contains(string(tests), "keychain_file") {
+ t.Fatal("P6's test must work while it is killed, and P2's must try the host keychain file from the simulator")
+ }
+ if info, _ := os.Stat(filepath.Join(root, "project/hostile.sh")); info.Mode().Perm() != 0700 {
t.Fatal("hostile.sh not executable")
}
for _, f := range []string{"package/Plugins/HostilePlugin/HostilePlugin.swift", "package/Tests/HostileTests/HostileTests.swift", "project/hostile.sh"} {
@@ -284,3 +291,36 @@ func TestFixtureShips(t *testing.T) {
}
}
}
+
+// P2 runs its hostile test on an iOS simulator, as checks do (the fake
+// xcodebuild fails it anywhere else), and is denied only for a run whose
+// end was proven: a marked process left makes it failed, whatever the
+// lines say. Without an iOS simulator P2 cannot say.
+func TestP2NeedsTheSimulatorAndAProvenEnd(t *testing.T) {
+ f := newProbeFixture(t, allLines("denied"))
+ caps := Capabilities(context.Background(), f.h.Exec, f.h.Tools)
+ if p, ran, _ := probeP2(context.Background(), f.h, caps); p.Verdict != wire.ProbeDenied || !ran {
+ t.Fatalf("on the simulator: %+v", p)
+ }
+ gate := f.h.Gate
+ f.h.Gate = func(sandboxed bool) *Gate {
+ g := gate(sandboxed)
+ g.Settle = 300 * time.Millisecond
+ g.find = func(string) ([]Proc, error) { return []Proc{{PID: 1 << 30, PGID: 1 << 30}}, nil }
+ return g
+ }
+ if p, _, _ := probeP2(context.Background(), f.h, caps); p.Verdict != wire.ProbeFailed || !strings.Contains(p.Detail, "end not proven") {
+ t.Fatalf("end not proven: %+v", p)
+ }
+ f.h.Gate = gate
+ // Every line says denied, but the hostile build did not complete:
+ // not a pass.
+ f = newProbeFixture(t, allLines("denied"), "FAKE_LINES_THEN_FAIL=1")
+ if p, ran, _ := probeP2(context.Background(), f.h, caps); p.Verdict != wire.ProbeFailed || ran {
+ t.Fatalf("incomplete run: %+v", p)
+ }
+ caps.Simulators = nil
+ if p, _, _ := probeP2(context.Background(), f.h, caps); p.Verdict != wire.ProbeUnavailable || p.Detail != "no iOS simulator" {
+ t.Fatalf("no simulator: %+v", p)
+ }
+}
diff --git a/internal/runner/thin/mac.go b/internal/runner/thin/mac.go
index 8cd063b9..c793b0f7 100644
--- a/internal/runner/thin/mac.go
+++ b/internal/runner/thin/mac.go
@@ -7,6 +7,7 @@ import (
"encoding/json"
"errors"
"io"
+ "io/fs"
"net"
"net/http"
"os"
@@ -39,10 +40,11 @@ func (m macGate) Run(ctx context.Context, attempt, dir string, argv []string, li
func (m macGate) Verify(id string) bool { return m.g.Verify(id) }
-// macChecks chooses each attempt's gate from the newest probe report:
-// srt and seatbelt when P2 denied; srt still, labelled none, when the
-// fixture at least built under srt (the boundary is unproven, not
-// absent); otherwise no sandbox, labelled none.
+// macChecks chooses each attempt's gate from the probe report this
+// process made and still trusts (macProbes.trusted): srt and seatbelt
+// when P2 denied; srt still, labelled none, when the fixture at least
+// built under srt (the boundary is unproven, not absent); otherwise no
+// sandbox, labelled none.
type macChecks struct {
probes *macProbes
srt string
@@ -50,11 +52,13 @@ type macChecks struct {
}
func (m *macChecks) pick() *mac.Gate {
- r := m.probes.report()
+ r, ok := m.probes.trusted()
switch {
- case m.srt != "" && r.Sandboxed():
+ case !ok || m.srt == "":
+ return m.bare
+ case r.Sandboxed():
return m.sandboxed
- case m.srt != "" && r.SRTRanXcode:
+ case r.SRTRanXcode:
return m.unproven
}
return m.bare
@@ -69,69 +73,106 @@ func (m *macChecks) Run(ctx context.Context, attempt, dir string, argv []string,
// Verify settles a recorded attempt the same way whatever confined it.
func (m *macChecks) Verify(id string) bool { return m.bare.Verify(id) }
-// macProbes keeps the probe report (probes.json in the state dir, where
-// `equipo-runner probe` writes too) and runs the probes when it is
-// missing or was made by another version or profile.
+// probeTrust is how long a probe report is trusted.
+const probeTrust = 24 * time.Hour
+
+// macProbes holds the probe report in this process's memory only.
+// Nothing on disk is ever read back as a verdict: a gate that ran
+// outside the sandbox runs as this user and could write any file this
+// process could. A report is trusted while it is this runner version's,
+// for this checks profile, made with the srt, Node and ripgrep that are
+// on disk now (fingerprint), and less than a day old; otherwise checks
+// run as not verified and the probes run again. `equipo-runner probe`
+// only asks for that (request): a forged request costs a probe run and
+// never upgrades trust.
type macProbes struct {
- file, version string
- run func(context.Context) mac.Report
+ version string
+ run func(context.Context) mac.Report
+ fingerprint func() string
+ request string
+ now func() time.Time
mu sync.Mutex
last mac.Report
- mtime time.Time
ready chan struct{}
+ again chan struct{}
}
-func newMacProbes(file, version string, run func(context.Context) mac.Report) *macProbes {
- return &macProbes{file: file, version: version, run: run, ready: make(chan struct{})}
+func newMacProbes(version, request string, run func(context.Context) mac.Report, fingerprint func() string) *macProbes {
+ return &macProbes{version: version, request: request, run: run, fingerprint: fingerprint, now: time.Now, ready: make(chan struct{}), again: make(chan struct{}, 1)}
}
-// report is the newest report, re-read when the file changed.
+// report is the newest report, for the instance to show.
func (p *macProbes) report() mac.Report {
p.mu.Lock()
defer p.mu.Unlock()
- if info, err := os.Stat(p.file); err == nil && !info.ModTime().Equal(p.mtime) {
- if r, err := mac.LoadReport(p.file); err == nil {
- p.last, p.mtime = r, info.ModTime()
- }
- }
return p.last
}
-// start runs the probes now unless the saved report is current; ready
-// closes when there is a current report. refresh tells the instance.
-func (p *macProbes) start(ctx context.Context, refresh func()) {
- if p.report().Current(p.version) {
- close(p.ready)
- return
+// trusted is the newest report and whether it may decide a gate now.
+func (p *macProbes) trusted() (mac.Report, bool) {
+ r := p.report()
+ ok := r.Version == p.version && r.Profile == mac.ProfileDigest() && r.SRT != "" && r.SRT == p.fingerprint() && !r.At.IsZero() && p.now().Sub(r.At) < probeTrust && p.now().Sub(r.At) >= -time.Minute
+ if !ok && !r.At.IsZero() {
+ p.probeSoon()
}
+ return r, ok
+}
+
+func (p *macProbes) probeSoon() {
+ select {
+ case p.again <- struct{}{}:
+ default:
+ }
+}
+
+// start probes now and again whenever asked (a stale report, a
+// request), or a day after the last run. ready closes after the first
+// run; refresh tells the instance.
+func (p *macProbes) start(ctx context.Context, refresh func()) {
go func() {
- r := p.run(ctx)
- if ctx.Err() != nil {
- return
- }
- if err := mac.SaveReport(p.file, r); err == nil {
+ first := true
+ for {
+ srt := p.fingerprint()
+ r := p.run(ctx)
+ if ctx.Err() != nil {
+ return
+ }
+ r.SRT = srt
p.mu.Lock()
- p.last, p.mtime = r, time.Time{}
+ p.last = r
p.mu.Unlock()
+ if first {
+ close(p.ready)
+ first = false
+ }
+ refresh()
+ select {
+ case <-ctx.Done():
+ return
+ case <-p.again:
+ case <-time.After(probeTrust - time.Hour):
+ }
}
- close(p.ready)
- refresh()
}()
}
-// watch tells the instance when someone ran `equipo-runner probe`.
-func (p *macProbes) watch(ctx context.Context, refresh func()) {
- seen := p.report().At
+// watch turns `equipo-runner probe` (it touches the request file) into a
+// new probe run.
+func (p *macProbes) watch(ctx context.Context) {
+ var seen time.Time
+ if info, err := os.Stat(p.request); err == nil {
+ seen = info.ModTime()
+ }
for {
select {
case <-ctx.Done():
return
case <-time.After(30 * time.Second):
}
- if at := p.report().At; !at.Equal(seen) {
- seen = at
- refresh()
+ if info, err := os.Stat(p.request); err == nil && !info.ModTime().Equal(seen) {
+ seen = info.ModTime()
+ p.probeSoon()
}
}
}
@@ -145,6 +186,47 @@ func (p *macProbes) wait(ctx context.Context) error {
}
}
+// srtFingerprint names the sandbox's own files as they are on disk: the
+// srt package, Node and ripgrep. A gate that ran outside the sandbox
+// could have changed them; a report made with others is not trusted.
+func srtFingerprint(t mac.Tools) string {
+ if t.SRT == "" {
+ return ""
+ }
+ cli, err := filepath.EvalSymlinks(t.SRT)
+ if err != nil {
+ return ""
+ }
+ h := sha256.New()
+ pkg := filepath.Dir(filepath.Dir(cli))
+ err = filepath.WalkDir(pkg, func(path string, d fs.DirEntry, err error) error {
+ if err != nil || d.IsDir() {
+ return err
+ }
+ return hashFile(h, path)
+ })
+ for _, f := range []string{t.Node, t.RG} {
+ if err == nil {
+ err = hashFile(h, f)
+ }
+ }
+ if err != nil {
+ return ""
+ }
+ return hex.EncodeToString(h.Sum(nil))
+}
+
+func hashFile(h io.Writer, path string) error {
+ f, err := os.Open(path)
+ if err != nil {
+ return err
+ }
+ defer f.Close()
+ _, _ = io.WriteString(h, path+"\x00")
+ _, err = io.Copy(h, f)
+ return err
+}
+
// macHost is the Mac worker's setup: its tools, paths and gates.
type macHost struct {
// scratch is the runner's scratch root: the probes' fixture copies
@@ -255,9 +337,9 @@ func newMacHost(c runner.Config, o Options, getenv func(string) string) (*macHos
}
return g
}
- h.probes = newMacProbes(filepath.Join(c.StateDir, "probes.json"), o.Version, func(ctx context.Context) mac.Report {
+ h.probes = newMacProbes(o.Version, ProbeRequest(c), func(ctx context.Context) mac.Report {
return mac.RunProbes(ctx, h.probeHost(o.Version, gate))
- })
+ }, func() string { return srtFingerprint(h.tools) })
h.checks = &macChecks{probes: h.probes, srt: h.tools.SRT, sandboxed: gate(h.tools.SRT, wire.SandboxSeatbelt), unproven: gate(h.tools.SRT, wire.SandboxNone), bare: gate("", wire.SandboxNone)}
h.caps = func(ctx context.Context) wire.Capabilities {
caps := mac.Capabilities(ctx, execTool, h.tools)
@@ -325,15 +407,20 @@ func runMac(ctx context.Context, c runner.Config, o Options) error {
return runWorker(ctx, c, o, hostPlatform(), workerSetup{probe: h.caps, gate: h.checks, find: h.find, ready: h.probes.wait,
started: func(ctx context.Context, refresh func()) {
h.probes.start(ctx, refresh)
- go h.probes.watch(ctx, refresh)
+ go h.probes.watch(ctx)
},
welcomed: func(w wire.Welcome, worker *Worker, stop context.CancelCauseFunc) {
up.offer(w, func() func() { worker.mu.Lock(); return worker.mu.Unlock }, func() { stop(ErrUpdated) }, o.Logger)
}})
}
-// RunProbes runs the Mac probes now and saves the report where the
-// running worker reads it (`equipo-runner probe`).
+// ProbeRequest is the file `equipo-runner probe` touches to ask the
+// running worker to probe again.
+func ProbeRequest(c runner.Config) string { return filepath.Join(c.StateDir, "probe-request") }
+
+// RunProbes runs the Mac probes now in this process, for the person
+// asking, and asks the running worker to run its own: only a worker's
+// own run decides how it confines checks.
func RunProbes(ctx context.Context, c runner.Config, o Options) (mac.Report, error) {
h, err := newMacHost(c, o, os.Getenv)
if err != nil {
@@ -344,7 +431,11 @@ func RunProbes(ctx context.Context, c runner.Config, o Options) (mac.Report, err
if err := ctx.Err(); err != nil {
return r, err
}
- return r, mac.SaveReport(h.probes.file, r)
+ now := time.Now()
+ if f, err := os.OpenFile(ProbeRequest(c), os.O_CREATE|os.O_WRONLY, 0600); err == nil {
+ f.Close()
+ }
+ return r, os.Chtimes(ProbeRequest(c), now, now)
}
// macUpdater replaces the worker's binary with the release its instance
diff --git a/internal/runner/thin/mac_test.go b/internal/runner/thin/mac_test.go
index 9fbb04f6..3faabfc8 100644
--- a/internal/runner/thin/mac_test.go
+++ b/internal/runner/thin/mac_test.go
@@ -46,30 +46,53 @@ func TestWorkerMacReports(t *testing.T) {
}
}
-func saveReport(t *testing.T, file string, r mac.Report) {
+// probeRig is a macProbes whose run, fingerprint and clock a test sets.
+type probeRig struct {
+ p *macProbes
+ runs atomic.Int32
+ verdict string
+ srt string
+ now time.Time
+}
+
+func newProbeRig(t *testing.T) *probeRig {
+ x := &probeRig{verdict: wire.ProbeDenied, srt: "fp1", now: time.Now()}
+ x.p = newMacProbes("v1", filepath.Join(t.TempDir(), "probe-request"), func(context.Context) mac.Report {
+ x.runs.Add(1)
+ return mac.Report{Version: "v1", Profile: mac.ProfileDigest(), At: x.now, Probes: probesAll(x.verdict), SRTRanXcode: true}
+ }, func() string { return x.srt })
+ x.p.now = func() time.Time { return x.now }
+ return x
+}
+
+func (x *probeRig) started(t *testing.T) {
t.Helper()
- if err := mac.SaveReport(file, r); err != nil {
+ x.p.start(t.Context(), func() {})
+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
+ defer cancel()
+ if err := x.p.wait(ctx); err != nil {
t.Fatal(err)
}
}
-// Each attempt's gate follows the newest probe report: srt and seatbelt
-// only when P2 denied; srt labelled none when the fixture built under
-// srt; otherwise outside the sandbox, labelled none. No srt, no
-// sandbox, whatever the report says.
+// Each attempt's gate follows the report this process made and still
+// trusts: srt and seatbelt only when P2 denied; srt labelled none when
+// the fixture built under srt; otherwise outside the sandbox, labelled
+// none. No srt, no sandbox, whatever the report says.
func TestMacChecksPick(t *testing.T) {
- file := filepath.Join(t.TempDir(), "probes.json")
- p := newMacProbes(file, "v1", nil)
- m := &macChecks{probes: p, srt: "/x/srt", sandboxed: &mac.Gate{Sandbox: wire.SandboxSeatbelt}, unproven: &mac.Gate{SRT: "/x/srt", Sandbox: wire.SandboxNone}, bare: &mac.Gate{Sandbox: wire.SandboxNone}}
+ x := newProbeRig(t)
+ m := &macChecks{probes: x.p, srt: "/x/srt", sandboxed: &mac.Gate{Sandbox: wire.SandboxSeatbelt}, unproven: &mac.Gate{SRT: "/x/srt", Sandbox: wire.SandboxNone}, bare: &mac.Gate{Sandbox: wire.SandboxNone}}
if m.pick() != m.bare {
t.Fatal("no report: not bare")
}
- saveReport(t, file, mac.Report{Probes: []wire.Probe{{ID: "P2", Verdict: wire.ProbeFailed}}, SRTRanXcode: true})
+ x.verdict = wire.ProbeFailed
+ x.started(t)
if m.pick() != m.unproven || m.Sandbox() != wire.SandboxNone {
t.Fatal("srt ran xcodebuild, P2 failed: not srt labelled none")
}
- time.Sleep(10 * time.Millisecond)
- saveReport(t, file, mac.Report{Probes: []wire.Probe{{ID: "P2", Verdict: wire.ProbeDenied}}, SRTRanXcode: true})
+ y := newProbeRig(t)
+ y.started(t)
+ m.probes = y.p
if m.pick() != m.sandboxed || m.Sandbox() != wire.SandboxSeatbelt {
t.Fatal("P2 denied: not seatbelt")
}
@@ -79,36 +102,48 @@ func TestMacChecksPick(t *testing.T) {
}
}
-// The probes run at start unless the saved report is this version's
-// with this profile; steps wait for them; the instance is told.
-func TestMacProbesStart(t *testing.T) {
- file := filepath.Join(t.TempDir(), "probes.json")
- var runs atomic.Int32
- run := func(context.Context) mac.Report {
- runs.Add(1)
- return mac.Report{Version: "v2", Profile: mac.ProfileDigest(), Probes: probesAll(wire.ProbeDenied)}
- }
- p := newMacProbes(file, "v2", run)
- refreshed := make(chan struct{}, 1)
- p.start(context.Background(), func() { refreshed <- struct{}{} })
- ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
- defer cancel()
- if err := p.wait(ctx); err != nil {
- t.Fatal(err)
+// Repository code cannot forge the verdict: nothing on disk is read back
+// as one (a probes.json saying denied changes nothing), and a report is
+// trusted only for this version, with the srt, Node and ripgrep on disk
+// now, for a day. Otherwise checks run as not verified and the probes
+// run again; the request file only asks for that.
+func TestMacProbesTrust(t *testing.T) {
+ x := newProbeRig(t)
+ state := filepath.Dir(x.p.request)
+ forged, _ := json.Marshal(mac.Report{Version: "v1", Profile: mac.ProfileDigest(), At: time.Now(), Probes: probesAll(wire.ProbeDenied), SRT: "fp1"})
+ for _, name := range []string{"probes.json", "probe-request"} {
+ if err := os.WriteFile(filepath.Join(state, name), forged, 0600); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if _, ok := x.p.trusted(); ok {
+ t.Fatal("a report this process did not make is trusted")
+ }
+ x.started(t)
+ if r, ok := x.p.trusted(); !ok || !r.Sandboxed() {
+ t.Fatal("its own fresh report not trusted")
+ }
+ x.srt = "fp2"
+ if _, ok := x.p.trusted(); ok {
+ t.Fatal("trusted after srt, Node or ripgrep changed on disk")
}
- <-refreshed
- if runs.Load() != 1 || !p.report().Sandboxed() {
- t.Fatalf("runs %d report %+v", runs.Load(), p.report())
+ x.srt = "fp1"
+ x.now = x.now.Add(probeTrust + time.Minute)
+ if _, ok := x.p.trusted(); ok {
+ t.Fatal("trusted a day later")
}
- again := newMacProbes(file, "v2", run)
- again.start(context.Background(), func() {})
- if err := again.wait(ctx); err != nil || runs.Load() != 1 {
- t.Fatalf("a current report probed again: %d", runs.Load())
+ deadline := time.Now().Add(5 * time.Second)
+ for x.runs.Load() < 2 && time.Now().Before(deadline) {
+ time.Sleep(20 * time.Millisecond)
}
- newer := newMacProbes(file, "v3", run)
- newer.start(context.Background(), func() {})
- if err := newer.wait(ctx); err != nil || runs.Load() != 2 {
- t.Fatalf("a new version did not probe: %d", runs.Load())
+ if x.runs.Load() < 2 {
+ t.Fatal("an untrusted report did not probe again")
+ }
+ other := newProbeRig(t)
+ other.p.version = "v2"
+ other.started(t)
+ if _, ok := other.p.trusted(); ok {
+ t.Fatal("another version's report trusted")
}
}
@@ -297,3 +332,45 @@ func (g *recordingGate) Run(ctx context.Context, a, dir string, argv []string, l
g.before()
return g.stubGate.Run(ctx, a, dir, argv, l, record)
}
+
+// The fingerprint covers the srt package, Node and ripgrep as they are
+// on disk: changing any of them changes it; a missing one leaves none.
+func TestSRTFingerprint(t *testing.T) {
+ root := t.TempDir()
+ files := map[string]string{"srt/node_modules/@anthropic-ai/sandbox-runtime/dist/cli.js": "cli", "srt/node_modules/@anthropic-ai/sandbox-runtime/dist/sandbox/macos.js": "profile", "node": "node", "rg": "rg"}
+ for p, body := range files {
+ if err := os.MkdirAll(filepath.Dir(filepath.Join(root, p)), 0700); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(filepath.Join(root, p), []byte(body), 0700); err != nil {
+ t.Fatal(err)
+ }
+ }
+ bin := filepath.Join(root, "srt/node_modules/.bin")
+ if err := os.MkdirAll(bin, 0700); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.Symlink("../@anthropic-ai/sandbox-runtime/dist/cli.js", filepath.Join(bin, "srt")); err != nil {
+ t.Fatal(err)
+ }
+ tools := mac.Tools{SRT: filepath.Join(bin, "srt"), Node: filepath.Join(root, "node"), RG: filepath.Join(root, "rg")}
+ first := srtFingerprint(tools)
+ if first == "" || srtFingerprint(tools) != first {
+ t.Fatal("no stable fingerprint")
+ }
+ for _, p := range []string{"srt/node_modules/@anthropic-ai/sandbox-runtime/dist/sandbox/macos.js", "node", "rg"} {
+ if err := os.WriteFile(filepath.Join(root, p), []byte("changed"), 0700); err != nil {
+ t.Fatal(err)
+ }
+ if srtFingerprint(tools) == first {
+ t.Fatalf("%s changed, fingerprint did not", p)
+ }
+ if err := os.WriteFile(filepath.Join(root, p), []byte(files[p]), 0700); err != nil {
+ t.Fatal(err)
+ }
+ }
+ tools.RG = filepath.Join(root, "missing")
+ if srtFingerprint(tools) != "" {
+ t.Fatal("fingerprint without ripgrep")
+ }
+}