oficina / equipo Public

Clone
git clone https://amadan.net/oficina/equipo

Plain git — no account needed to clone.

Download

Download this file

1//go:build testbuild
2
3package thin
4
5import (
6 "context"
7 "crypto/sha256"
8 "encoding/hex"
9 "errors"
10 "fmt"
11 "io"
12 "os"
13 "os/exec"
14 "path/filepath"
15 "regexp"
16 "slices"
17 "strings"
18
19 "amadan.net/oficina/equipo/internal/runner"
20 "amadan.net/oficina/equipo/internal/runner/mac"
21 "amadan.net/oficina/equipo/internal/runner/mac/creds"
22 "amadan.net/oficina/equipo/internal/runner/mac/proc"
23 "amadan.net/oficina/equipo/internal/wire"
24)
25
26// fakeWorkerMarker is in every test build and in no release build:
27// TestReleaseRunnerHasNoFakeWorker looks for it in a release binary.
28const fakeWorkerMarker = "equipo-fake-worker-unsandboxed-process-group"
29
30// The test build's fake Mac worker (Mac runners spec §6): the real thin
31// runner started with EQUIPO_FAKE_PLATFORM=darwin/arm64 reports a Mac's
32// capabilities (a fixture until probe P1 records tito-studio's) and runs
33// checks with the Mac's process-group gate WITHOUT a sandbox. It exists
34// only under the testbuild tag, so no release binary can run checks
35// unsandboxed on Linux.
36//
37// Since slice F (task 16) it also makes changes, as a Mac does: Engineering
38// through the darwin launch of a pinned stand-in for Claude Code (a
39// script that runs the fake CLI, pinned by its own digest: the release
40// pin is the official binary's, which no fake can match), package mac's
41// turns and process-group executor without a sandbox, the Mac's
42// credential operations with no Keychain, its own Claude connections,
43// and the pinned gitleaks of its tools before anything leaves.
44func init() {
45 fake = &fakeWorker{}
46}
47
48type fakeWorker struct{}
49
50func (fakeWorker) marker() string { return fakeWorkerMarker }
51
52func (fakeWorker) platform(spec string) (wire.Platform, bool) {
53 osName, arch, ok := strings.Cut(spec, "/")
54 if !ok || osName != "darwin" || arch == "" {
55 return wire.Platform{}, false
56 }
57 return wire.Platform{OS: osName, Arch: arch}, true
58}
59
60// fakeProbeDetail is the detail of every probe the fixture reports.
61const fakeProbeDetail = "all_denied:33"
62
63// probe is the fixture report of a Mac with Xcode and one iPhone
64// simulator, whose probes all came out as a Mac that can make changes
65// reports them (task 14's "ready" fixture): P1 to P7, P2 denied when its
66// checks are seatbelt, F1 to F7 at their success verdicts (F5 skipped
67// while P2 is not denied), and its Engineering status ready.
68func (fakeWorker) probe(sandbox string) func(context.Context) wire.Capabilities {
69 return func(context.Context) wire.Capabilities {
70 p2, f5, f5Detail := wire.ProbeFailed, wire.ProbeSkipped, "f5_skipped"
71 if sandbox == wire.SandboxSeatbelt {
72 p2, f5, f5Detail = wire.ProbeDenied, wire.ProbeDenied, fakeProbeDetail
73 }
74 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}}
75 for _, id := range wire.EngineeringProbeIDs {
76 p := wire.Probe{ID: id, Verdict: wire.EngineeringProbeSuccess(id), Detail: fakeProbeDetail}
77 if id == "F5" {
78 p.Verdict, p.Detail = f5, f5Detail
79 }
80 probes = append(probes, p)
81 }
82 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}}
83 }
84}
85
86// gate runs checks in a process group with an environment from scratch:
87// HOME and TMPDIR the attempt's scratch, CI=1, a fixed PATH (bin first:
88// the fake xcodebuild). Its label is none (it has no sandbox) unless the
89// scenario plays a Mac whose probe P2 denied (sandbox seatbelt).
90func (fakeWorker) gate(bin, sandbox string) GateRunner {
91 label := wire.SandboxNone
92 if sandbox == wire.SandboxSeatbelt {
93 label = wire.SandboxSeatbelt
94 }
95 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}}
96}
97
98// fakeCLIScript is the pinned stand-in for Claude Code: it runs the fake
99// CLI (the test binary started as claude, at %[2]s) with the launch's
100// argv, its environment the launch's plus the fake's scope entry
101// (%[1]s), so the CLI and what it starts are in the fake's process
102// table. Its digest is the pin, so every launch hashes it exactly as a
103// Mac hashes the official binary (ClaudeCLI.Launch).
104const fakeCLIScript = "#!/bin/sh\nexport %[1]s\nexec '%[2]s' \"$@\"\n"
105
106// fakeScope is the EQUIPO_TEST_SCOPE value a fake worker's processes
107// carry: one per fake worker, the same across its restarts.
108var fakeScope = regexp.MustCompile(`^[A-Za-z0-9]{8,64}$`)
109
110// fakeUserTemp is the Mac-shaped DARWIN_USER_TEMP_DIR the fake names in
111// a sandboxed Xcode policy (its writes). It is a policy literal only:
112// nothing is made there, and the fake's executor cleans no T (a Mac's
113// XcodeExec does).
114const fakeUserTemp = mac.UserTempPrefix + "/eq/fake-worker/T"
115
116// setup is the fake Mac worker: the fixture report, composed as a Mac
117// composes its own with what its guards and records say now; the gate
118// (checksGate); and the Mac's credential operations and Engineering
119// pieces (engineering).
120func (f fakeWorker) setup(ctx context.Context, c *runner.Config, o Options) (workerSetup, error) {
121 m, eng, err := f.engineering(ctx, c, o)
122 if err != nil {
123 return workerSetup{}, err
124 }
125 fixture := f.probe(o.FakeSandbox)
126 probe := func(ctx context.Context) wire.Capabilities {
127 caps := fixture(ctx)
128 if left, err := m.keychain.Unproven(); err != nil || len(left) > 0 {
129 caps.Unproven = wire.UnprovenCredential
130 } else if code, n := m.turns.Unproven(); code != "" {
131 caps.Unproven, caps.UnprovenCount = code, n
132 }
133 // The guards first, then a credential launch whose end is not
134 // proven (task 14's order); else the fixture's ready.
135 status := m.status()
136 if status == nil && caps.Unproven == wire.UnprovenCredential {
137 status = &wire.EngineeringStatus{State: wire.EngineeringNoConnection, Reason: wire.UnprovenCredential}
138 }
139 if status != nil {
140 caps.Engineering = status
141 caps.Tags = slices.DeleteFunc(caps.Tags, func(t string) bool { return t == wire.TagClaude })
142 }
143 return caps
144 }
145 gate, err := f.checksGate(m.paths.InstallDir, o.FakeBin, o.FakeSandbox, m.turns, proc.ScopeEnv+"="+os.Getenv(proc.ScopeEnv))
146 if err != nil {
147 return workerSetup{}, err
148 }
149 return workerSetup{probe: probe, gate: gate, creds: m, engineering: eng}, nil
150}
151
152// fakeSRT is the test build's stand-in for srt, for a fake that plays a
153// Mac whose probe P2 denied: it takes srt's own arguments (--settings
154// <file> --) and runs the command, so the gate runs it as a seatbelt
155// Mac's runs it under srt, and its turn is a sandboxed one.
156const fakeSRT = "#!/bin/sh\nwhile [ \"$#\" -gt 0 ] && [ \"$1\" != \"--\" ]; do shift; done\nshift\nexec \"$@\"\n"
157
158// checksGate is the fake's checks gate (gate) as a Mac's is: over the
159// Mac's turns, its processes in the fake's scope (entry). Playing a
160// seatbelt Mac, it runs under the srt stand-in written in dir, so a
161// check killed mid-run is cleared as a seatbelt Mac's is (the idle
162// read); otherwise without a sandbox, which only a reboot clears (task
163// 9).
164func (f fakeWorker) checksGate(dir, bin, sandbox string, turns *mac.Turns, entry string) (GateRunner, error) {
165 g := f.gate(bin, sandbox).(macGate)
166 g.g.Env, g.g.Turns = append(g.g.Env, entry), turns
167 if sandbox == wire.SandboxSeatbelt {
168 srt := filepath.Join(dir, "srt")
169 if err := os.WriteFile(srt, []byte(fakeSRT), 0o700); err != nil {
170 return nil, err
171 }
172 g.g.SRT = srt
173 g.g.Settings = func(string, string) ([]byte, error) { return []byte("{}"), nil }
174 }
175 return g, nil
176}
177
178// engineering is the fake Mac's credential operations and Engineering
179// pieces. Its home is the directory above its state dir (the runner
180// user's home on a Mac); the stand-in is provisioned into the install
181// dir there and pinned (mac.PinnedForTest: test build only); this
182// process launches as a Mac does; it lists no Keychain (Linux has none)
183// and its home guard reads plain modes. It needs its own accounts root
184// and bindings, never a person's real ones, and the fake CLI at
185// c.ClaudePath, which a Mac has no use for afterwards (cleared).
186func (fakeWorker) engineering(ctx context.Context, c *runner.Config, o Options) (*macCreds, *WorkerEngineering, error) {
187 cli, scope := c.ClaudePath, os.Getenv(proc.ScopeEnv)
188 if o.AccountsRoot == "" || c.AccountBindingsPath == "" || !filepath.IsAbs(cli) || strings.ContainsAny(cli, "'\n") {
189 return nil, nil, errors.New("the fake Mac worker needs its own accounts root and bindings, and the fake CLI")
190 }
191 if !fakeScope.MatchString(scope) {
192 // Linux is shared: only a table scoped to this fake's own
193 // processes may sweep, and only such a table lets an idle read
194 // prove a turn a crash left incomplete (task 9).
195 return nil, nil, errors.New("the fake Mac worker needs " + proc.ScopeEnv + " (8 to 64 letters and digits) on its process")
196 }
197 entry := proc.ScopeEnv + "=" + scope
198 c.ClaudePath = ""
199 darwinLaunch = true
200 home := filepath.Dir(c.StateDir)
201 install := filepath.Join(home, "lib")
202 if err := os.MkdirAll(install, 0o700); err != nil {
203 return nil, nil, err
204 }
205 script := fmt.Sprintf(fakeCLIScript, entry, cli)
206 sum := sha256.Sum256([]byte(script))
207 pinned := mac.PinnedForTest(mac.NewClaudeCLI(home, install), hex.EncodeToString(sum[:]))
208 if err := pinned.Provision(ctx, func(context.Context, string) (io.ReadCloser, error) {
209 return io.NopCloser(strings.NewReader(script)), nil
210 }); err != nil {
211 return nil, nil, err
212 }
213 out, err := exec.Command("/usr/bin/id", "-un").Output()
214 if err != nil {
215 return nil, nil, err
216 }
217 user := strings.TrimSpace(string(out))
218 // The Mac's turns sweep the runner user's processes; here, this
219 // fake's own (the runner, the CLI through the stand-in, what those
220 // start), as a Mac's runner user is the runner's alone.
221 turns := mac.NewTurns(filepath.Join(c.StateDir, "mac-gate.lock")).Sweep(proc.Scoped(entry))
222 m := &macCreds{turns: turns, exec: &mac.Executor{Turns: turns}, cli: pinned,
223 paths: mac.Paths{Home: home, StateDir: c.StateDir, AccountsRoot: o.AccountsRoot, SessionRoot: SessionRoot(*c), InstallDir: install, UserTemp: fakeUserTemp},
224 configDir: macConfigDir(*c, home), runner: firstNonEmpty(c.ToolProxyPath, c.Executable), scratch: c.ScratchRoot, taint: loadTaint(filepath.Join(c.StateDir, "tainted")),
225 user: user, uid: os.Getuid(), log: o.Logger}
226 m.fact = func(p string) (creds.Fact, error) { return creds.Read(p, nil) }
227 m.keychain = &creds.Keychain{Dir: filepath.Join(c.StateDir, "keychain"), Login: filepath.Join(home, "Library", "Keychains", "login.keychain-db"), User: user,
228 List: func(context.Context, string) ([]creds.Item, error) { return nil, nil },
229 Delete: func(context.Context, creds.Item) error { return errKeychain }}
230 // The pinned gitleaks beside the fake's tools, pinned to what is
231 // there at start (a Mac's is pinned at build time).
232 scanner, pin := filepath.Join(o.FakeBin, "gitleaks"), ""
233 if raw, err := os.ReadFile(scanner); err == nil {
234 s := sha256.Sum256(raw)
235 pin = hex.EncodeToString(s[:])
236 }
237 scan := &Engineer{O: ClaudeOptions{Runner: *c}}
238 eng := &WorkerEngineering{
239 // Sandboxed Xcode access as a Mac whose P2 and F5 are denied.
240 Xcode: func() bool { return o.FakeSandbox == wire.SandboxSeatbelt && !m.taint.Tainted() },
241 Leaks: func(ctx context.Context, dir, _ string, _ func(string) error) (bool, error) {
242 return scan.gitleaksAt(ctx, scanner, pin, dir, workerSecretRules())
243 }}
244 return m, eng, nil
245}
246