//go:build testbuild package thin import ( "context" "crypto/sha256" "encoding/hex" "errors" "fmt" "io" "os" "os/exec" "path/filepath" "regexp" "slices" "strings" "amadan.net/oficina/equipo/internal/runner" "amadan.net/oficina/equipo/internal/runner/mac" "amadan.net/oficina/equipo/internal/runner/mac/creds" "amadan.net/oficina/equipo/internal/runner/mac/proc" "amadan.net/oficina/equipo/internal/wire" ) // fakeWorkerMarker is in every test build and in no release build: // TestReleaseRunnerHasNoFakeWorker looks for it in a release binary. const fakeWorkerMarker = "equipo-fake-worker-unsandboxed-process-group" // The test build's fake Mac worker (Mac runners spec ยง6): the real thin // runner started with EQUIPO_FAKE_PLATFORM=darwin/arm64 reports a Mac's // capabilities (a fixture until probe P1 records tito-studio's) and runs // checks with the Mac's process-group gate WITHOUT a sandbox. It exists // only under the testbuild tag, so no release binary can run checks // unsandboxed on Linux. // // Since slice F (task 16) it also makes changes, as a Mac does: Engineering // through the darwin launch of a pinned stand-in for Claude Code (a // script that runs the fake CLI, pinned by its own digest: the release // pin is the official binary's, which no fake can match), package mac's // turns and process-group executor without a sandbox, the Mac's // credential operations with no Keychain, its own Claude connections, // and the pinned gitleaks of its tools before anything leaves. func init() { fake = &fakeWorker{} } type fakeWorker struct{} func (fakeWorker) marker() string { return fakeWorkerMarker } func (fakeWorker) platform(spec string) (wire.Platform, bool) { osName, arch, ok := strings.Cut(spec, "/") if !ok || osName != "darwin" || arch == "" { return wire.Platform{}, false } return wire.Platform{OS: osName, Arch: arch}, true } // fakeProbeDetail is the detail of every probe the fixture reports. const fakeProbeDetail = "all_denied:33" // probe is the fixture report of a Mac with Xcode and one iPhone // simulator, whose probes all came out as a Mac that can make changes // reports them (task 14's "ready" fixture): P1 to P7, P2 denied when its // checks are seatbelt, F1 to F7 at their success verdicts (F5 skipped // while P2 is not denied), and its Engineering status ready. func (fakeWorker) probe(sandbox string) func(context.Context) wire.Capabilities { return func(context.Context) wire.Capabilities { p2, f5, f5Detail := wire.ProbeFailed, wire.ProbeSkipped, "f5_skipped" if sandbox == wire.SandboxSeatbelt { p2, f5, f5Detail = wire.ProbeDenied, wire.ProbeDenied, fakeProbeDetail } probes := []wire.Probe{{ID: "P1", Verdict: wire.ProbePassed, Detail: "xcode:16.2,16C5032a;ios_simulators:1;computer:Tito Studio"}, {ID: "P2", Verdict: p2, Detail: fakeProbeDetail}, {ID: "P3", Verdict: wire.ProbeSkipped}, {ID: "P4", Verdict: wire.ProbePassed}, {ID: "P5", Verdict: wire.ProbeSkipped}, {ID: "P6", Verdict: wire.ProbePassed}, {ID: "P7", Verdict: wire.ProbePassed}} for _, id := range wire.EngineeringProbeIDs { p := wire.Probe{ID: id, Verdict: wire.EngineeringProbeSuccess(id), Detail: fakeProbeDetail} if id == "F5" { p.Verdict, p.Detail = f5, f5Detail } probes = append(probes, p) } return wire.Capabilities{Xcode: wire.Xcode{Version: "16.2", Build: "16C5032a"}, Simulators: []wire.Simulator{{Name: "iPhone 16 Pro", Runtime: "iOS 18.2", UDID: "5C0A1E2B-3D4F-4A5B-9C6D-7E8F90A1B2C3", State: "Shutdown"}}, Toolchains: wire.Toolchains{Swift: "6.0.3", Node: "v22.12.0"}, Harness: wire.Harness{Claude: "2.1.312", SRT: "0.0.81"}, Tags: []string{wire.TagMacOS, wire.TagXcode, wire.TagIOSSimulator, wire.TagClaude}, Probes: probes, Engineering: &wire.EngineeringStatus{State: wire.EngineeringReady}} } } // gate runs checks in a process group with an environment from scratch: // HOME and TMPDIR the attempt's scratch, CI=1, a fixed PATH (bin first: // the fake xcodebuild). Its label is none (it has no sandbox) unless the // scenario plays a Mac whose probe P2 denied (sandbox seatbelt). func (fakeWorker) gate(bin, sandbox string) GateRunner { label := wire.SandboxNone if sandbox == wire.SandboxSeatbelt { label = wire.SandboxSeatbelt } return macGate{g: &mac.Gate{Env: []string{"CI=1", "PATH=" + bin + ":/usr/local/bin:/usr/bin:/bin", "LANG=C"}, ScratchHome: true, Lines: wire.MaxChecksLines, Sandbox: label}} } // fakeCLIScript is the pinned stand-in for Claude Code: it runs the fake // CLI (the test binary started as claude, at %[2]s) with the launch's // argv, its environment the launch's plus the fake's scope entry // (%[1]s), so the CLI and what it starts are in the fake's process // table. Its digest is the pin, so every launch hashes it exactly as a // Mac hashes the official binary (ClaudeCLI.Launch). const fakeCLIScript = "#!/bin/sh\nexport %[1]s\nexec '%[2]s' \"$@\"\n" // fakeScope is the EQUIPO_TEST_SCOPE value a fake worker's processes // carry: one per fake worker, the same across its restarts. var fakeScope = regexp.MustCompile(`^[A-Za-z0-9]{8,64}$`) // fakeUserTemp is the Mac-shaped DARWIN_USER_TEMP_DIR the fake names in // a sandboxed Xcode policy (its writes). It is a policy literal only: // nothing is made there, and the fake's executor cleans no T (a Mac's // XcodeExec does). const fakeUserTemp = mac.UserTempPrefix + "/eq/fake-worker/T" // setup is the fake Mac worker: the fixture report, composed as a Mac // composes its own with what its guards and records say now; the gate // (checksGate); and the Mac's credential operations and Engineering // pieces (engineering). func (f fakeWorker) setup(ctx context.Context, c *runner.Config, o Options) (workerSetup, error) { m, eng, err := f.engineering(ctx, c, o) if err != nil { return workerSetup{}, err } fixture := f.probe(o.FakeSandbox) probe := func(ctx context.Context) wire.Capabilities { caps := fixture(ctx) if left, err := m.keychain.Unproven(); err != nil || len(left) > 0 { caps.Unproven = wire.UnprovenCredential } else if code, n := m.turns.Unproven(); code != "" { caps.Unproven, caps.UnprovenCount = code, n } // The guards first, then a credential launch whose end is not // proven (task 14's order); else the fixture's ready. status := m.status() if status == nil && caps.Unproven == wire.UnprovenCredential { status = &wire.EngineeringStatus{State: wire.EngineeringNoConnection, Reason: wire.UnprovenCredential} } if status != nil { caps.Engineering = status caps.Tags = slices.DeleteFunc(caps.Tags, func(t string) bool { return t == wire.TagClaude }) } return caps } gate, err := f.checksGate(m.paths.InstallDir, o.FakeBin, o.FakeSandbox, m.turns, proc.ScopeEnv+"="+os.Getenv(proc.ScopeEnv)) if err != nil { return workerSetup{}, err } return workerSetup{probe: probe, gate: gate, creds: m, engineering: eng}, nil } // fakeSRT is the test build's stand-in for srt, for a fake that plays a // Mac whose probe P2 denied: it takes srt's own arguments (--settings // --) and runs the command, so the gate runs it as a seatbelt // Mac's runs it under srt, and its turn is a sandboxed one. const fakeSRT = "#!/bin/sh\nwhile [ \"$#\" -gt 0 ] && [ \"$1\" != \"--\" ]; do shift; done\nshift\nexec \"$@\"\n" // checksGate is the fake's checks gate (gate) as a Mac's is: over the // Mac's turns, its processes in the fake's scope (entry). Playing a // seatbelt Mac, it runs under the srt stand-in written in dir, so a // check killed mid-run is cleared as a seatbelt Mac's is (the idle // read); otherwise without a sandbox, which only a reboot clears (task // 9). func (f fakeWorker) checksGate(dir, bin, sandbox string, turns *mac.Turns, entry string) (GateRunner, error) { g := f.gate(bin, sandbox).(macGate) g.g.Env, g.g.Turns = append(g.g.Env, entry), turns if sandbox == wire.SandboxSeatbelt { srt := filepath.Join(dir, "srt") if err := os.WriteFile(srt, []byte(fakeSRT), 0o700); err != nil { return nil, err } g.g.SRT = srt g.g.Settings = func(string, string) ([]byte, error) { return []byte("{}"), nil } } return g, nil } // engineering is the fake Mac's credential operations and Engineering // pieces. Its home is the directory above its state dir (the runner // user's home on a Mac); the stand-in is provisioned into the install // dir there and pinned (mac.PinnedForTest: test build only); this // process launches as a Mac does; it lists no Keychain (Linux has none) // and its home guard reads plain modes. It needs its own accounts root // and bindings, never a person's real ones, and the fake CLI at // c.ClaudePath, which a Mac has no use for afterwards (cleared). func (fakeWorker) engineering(ctx context.Context, c *runner.Config, o Options) (*macCreds, *WorkerEngineering, error) { cli, scope := c.ClaudePath, os.Getenv(proc.ScopeEnv) if o.AccountsRoot == "" || c.AccountBindingsPath == "" || !filepath.IsAbs(cli) || strings.ContainsAny(cli, "'\n") { return nil, nil, errors.New("the fake Mac worker needs its own accounts root and bindings, and the fake CLI") } if !fakeScope.MatchString(scope) { // Linux is shared: only a table scoped to this fake's own // processes may sweep, and only such a table lets an idle read // prove a turn a crash left incomplete (task 9). return nil, nil, errors.New("the fake Mac worker needs " + proc.ScopeEnv + " (8 to 64 letters and digits) on its process") } entry := proc.ScopeEnv + "=" + scope c.ClaudePath = "" darwinLaunch = true home := filepath.Dir(c.StateDir) install := filepath.Join(home, "lib") if err := os.MkdirAll(install, 0o700); err != nil { return nil, nil, err } script := fmt.Sprintf(fakeCLIScript, entry, cli) sum := sha256.Sum256([]byte(script)) pinned := mac.PinnedForTest(mac.NewClaudeCLI(home, install), hex.EncodeToString(sum[:])) if err := pinned.Provision(ctx, func(context.Context, string) (io.ReadCloser, error) { return io.NopCloser(strings.NewReader(script)), nil }); err != nil { return nil, nil, err } out, err := exec.Command("/usr/bin/id", "-un").Output() if err != nil { return nil, nil, err } user := strings.TrimSpace(string(out)) // The Mac's turns sweep the runner user's processes; here, this // fake's own (the runner, the CLI through the stand-in, what those // start), as a Mac's runner user is the runner's alone. turns := mac.NewTurns(filepath.Join(c.StateDir, "mac-gate.lock")).Sweep(proc.Scoped(entry)) m := &macCreds{turns: turns, exec: &mac.Executor{Turns: turns}, cli: pinned, paths: mac.Paths{Home: home, StateDir: c.StateDir, AccountsRoot: o.AccountsRoot, SessionRoot: SessionRoot(*c), InstallDir: install, UserTemp: fakeUserTemp}, configDir: macConfigDir(*c, home), runner: firstNonEmpty(c.ToolProxyPath, c.Executable), scratch: c.ScratchRoot, taint: loadTaint(filepath.Join(c.StateDir, "tainted")), user: user, uid: os.Getuid(), log: o.Logger} m.fact = func(p string) (creds.Fact, error) { return creds.Read(p, nil) } m.keychain = &creds.Keychain{Dir: filepath.Join(c.StateDir, "keychain"), Login: filepath.Join(home, "Library", "Keychains", "login.keychain-db"), User: user, List: func(context.Context, string) ([]creds.Item, error) { return nil, nil }, Delete: func(context.Context, creds.Item) error { return errKeychain }} // The pinned gitleaks beside the fake's tools, pinned to what is // there at start (a Mac's is pinned at build time). scanner, pin := filepath.Join(o.FakeBin, "gitleaks"), "" if raw, err := os.ReadFile(scanner); err == nil { s := sha256.Sum256(raw) pin = hex.EncodeToString(s[:]) } scan := &Engineer{O: ClaudeOptions{Runner: *c}} eng := &WorkerEngineering{ // Sandboxed Xcode access as a Mac whose P2 and F5 are denied. Xcode: func() bool { return o.FakeSandbox == wire.SandboxSeatbelt && !m.taint.Tainted() }, Leaks: func(ctx context.Context, dir, _ string, _ func(string) error) (bool, error) { return scan.gitleaksAt(ctx, scanner, pin, dir, workerSecretRules()) }} return m, eng, nil }