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 "bytes"
7 "context"
8 "crypto/sha256"
9 "encoding/base64"
10 "encoding/hex"
11 "encoding/json"
12 "errors"
13 "fmt"
14 "log/slog"
15 "os"
16 "os/exec"
17 "path/filepath"
18 "strings"
19 "sync"
20 "sync/atomic"
21 "syscall"
22 "testing"
23 "time"
24
25 "amadan.net/oficina/equipo/internal/fakeclaude"
26 "amadan.net/oficina/equipo/internal/runner"
27 "amadan.net/oficina/equipo/internal/runner/mac"
28 "amadan.net/oficina/equipo/internal/runner/provider"
29 "amadan.net/oficina/equipo/internal/wire"
30 "github.com/spf13/viper"
31 gitleaksconfig "github.com/zricethezav/gitleaks/v8/config"
32)
33
34// Engineering on a Mac worker (Mac runners slice F, task 12) on Linux:
35// the darwin launch of the pinned stand-in (darwinRig: package mac's
36// executor and turns, the fake CLI, no sandbox), connections pasted
37// through the worker's own connector, and a primary (relayRig) whose
38// remote holds the base, which packs the inbound commits as the instance
39// asks and publishes the worker's candidate from its upload.
40
41// engBearer is the rig's runner credential: its URL base64 differs from
42// its standard base64 (it has '-' or '_').
43const engBearer = "rnr~bearer>?>?~~0123456789abcdefghij"
44
45type engRig struct {
46 *darwinRig
47 pri *relayRig
48 w *Worker
49 relay *Relay
50 r stepRow
51 // tokens are the connections' tokens, in the order they were pasted,
52 // and homes their dedicated homes.
53 tokens, homes []string
54 mu sync.Mutex
55 said []wire.StepReport
56 opened int
57 // noUpload: the instance does not ask for the upload (yet).
58 noUpload bool
59}
60
61func newEngRig(t *testing.T, emails ...string) *engRig { return newEngRigWith(t, nil, emails...) }
62
63// newEngRigWith is the rig whose base also holds the files before.
64func newEngRigWith(t *testing.T, before map[string]string, emails ...string) *engRig {
65 t.Helper()
66 asLaunch(t, true)
67 if len(emails) == 0 {
68 emails = []string{"a@example.com"}
69 }
70 d := newDarwinRig(t)
71 c := d.connector()
72 x := &engRig{darwinRig: d}
73 for i, email := range emails {
74 token := fakeclaude.Token(email)
75 id := fmt.Sprintf("c%d", i+1)
76 home, _ := d.paste(c, id, token)
77 d.healthy(id, home, token, email)
78 x.tokens = append(x.tokens, token)
79 x.homes = append(x.homes, home)
80 }
81 x.pri = newRelayRigFiles(t, before, nil, nil)
82 x.pri.e.Owners = []string{connPerson}
83 // The pinned gitleaks beside the runner binary, as on a Mac.
84 scanner := filepath.Join(filepath.Dir(previewScannerFixture(t)), "gitleaks")
85 if err := os.Link(scanner, filepath.Join(d.dir, "bin", "gitleaks")); err != nil {
86 raw, rerr := os.ReadFile(scanner)
87 if rerr != nil || os.WriteFile(filepath.Join(d.dir, "bin", "gitleaks"), raw, 0o700) != nil {
88 t.Fatal(err)
89 }
90 }
91 e := &Engineer{O: d.opts, Conns: d.conns, Owners: []string{connPerson}, Spoken: func() int { return wire.ProtocolMacEngineering }, MaxStep: time.Minute}
92 e.O.Runner.GitPath = "/usr/bin/git"
93 e.O.SessionRoot = d.m.paths.SessionRoot
94 e.O.Logger = slog.New(slog.NewTextHandler(&d.logs, nil))
95 x.w = &Worker{State: d.state, Engine: e, Gate: &stubGate{}, PackWait: 5 * time.Second, StepRoot: filepath.Join(d.cfg.ScratchRoot, "worker-steps"),
96 Eng: &WorkerEngineering{Creds: d.m,
97 Status: func(context.Context) *wire.EngineeringStatus {
98 return &wire.EngineeringStatus{State: wire.EngineeringReady}
99 },
100 Xcode: func() bool { return false },
101 Secrets: func(context.Context) ([]string, error) { return workerSecrets(d.cfg, engBearer) },
102 Leaks: e.workerLeaks}}
103 x.relay = &Relay{State: d.state, Engine: e, Worker: x.w}
104 x.r = x.dispatch("s1", x.pri.base, "Swipe back")
105 return x
106}
107
108// dispatch is a first Engineering attempt of step on base.
109func (x *engRig) dispatch(step, base, title string) stepRow {
110 d := wire.DispatchCommand{Person: connPerson, TaskID: "tk1", StepID: step, Attempt: 1, Specialist: wire.SpecialistEngineering, Repo: "amadan.net/oficina/sample", Branch: relayBranch, BaseSHA: base, Title: title, Brief: "b", Findings: []wire.Finding{}, Needs: []string{wire.TagMacOS, wire.TagXcode, wire.TagClaude}}
111 return stepRow{DispatchCommand: d, Base: base}
112}
113
114func (x *engRig) note(n string) { x.w.Engine.Note = "\n" + n + "\n" }
115
116// steps counts the CLI's step launches so far (its auth status reads
117// and checks are not steps).
118func (x *engRig) steps() int {
119 n := 0
120 for _, l := range x.launches() {
121 if strings.HasPrefix(l.argv, "-p ") && !strings.Contains(l.argv, "--tools ") {
122 n++
123 }
124 }
125 return n
126}
127
128// inbound relays the attempt's commits from the primary as the
129// instance's Engineering transfer does: the primary packs the header's
130// commits and the worker receives the chunk.
131func (x *engRig) inbound(t *testing.T) wire.TransferHeader {
132 t.Helper()
133 h := wire.TransferHeader{ID: "in-" + x.r.StepID + "-" + itoa(x.r.Attempt), Direction: wire.TransferInbound, Kind: wire.TransferKindEngineering, Repo: x.r.Repo, TaskID: x.r.TaskID, StepID: x.r.StepID, Attempt: x.r.Attempt, BaseSHA: x.r.BaseSHA}
134 if x.r.Rebase {
135 h.OldBaseSHA, h.CandidateSHA = x.r.FromBase, x.r.CandidateSHA
136 }
137 pack, err := x.pri.e.packCommits(context.Background(), h)
138 if err != nil {
139 t.Fatal(err)
140 }
141 sum := sha256.Sum256(pack)
142 if err := x.state.AcceptChunk(context.Background(), "chunk-"+h.ID, wire.Blob{Transfer: h, Index: 0, Total: 1, SHA256: hex.EncodeToString(sum[:]), Data: base64.StdEncoding.EncodeToString(pack)}); err != nil {
143 t.Fatal(err)
144 }
145 return h
146}
147
148// run accepts the dispatch, relays its commits and runs the attempt;
149// its final report is queued as the step engine queues it.
150func (x *engRig) run(t *testing.T) wire.StepReport {
151 t.Helper()
152 if err := x.state.AcceptDispatch(context.Background(), "d-"+x.r.key(), x.r.DispatchCommand); err != nil {
153 t.Fatal(err)
154 }
155 x.inbound(t)
156 rep := x.exec(t, x.r)
157 if wire.StepTerminal(rep.State) {
158 if err := x.state.ReportStep(context.Background(), x.r, rep); err != nil {
159 t.Fatal(err)
160 }
161 }
162 return rep
163}
164
165// exec runs r; a committed report makes the instance open the outbound
166// transfer: send_pack to the worker.
167func (x *engRig) exec(t *testing.T, r stepRow) wire.StepReport {
168 t.Helper()
169 return x.w.Exec(context.Background(), r, func(p wire.StepReport) {
170 x.mu.Lock()
171 x.said = append(x.said, p)
172 x.mu.Unlock()
173 if p.Phase == wire.OutcomeCommitted && p.CandidateSHA != "" && !x.noUpload {
174 x.sendPack(t, p)
175 }
176 })
177}
178
179// sendPack is the instance's send_pack for an outbound transfer of p's
180// candidate; it returns the transfer's id.
181func (x *engRig) sendPack(t *testing.T, p wire.StepReport) string {
182 x.mu.Lock()
183 x.opened++
184 id := fmt.Sprintf("out-%s-%d", p.StepID, x.opened)
185 x.mu.Unlock()
186 h := wire.TransferHeader{ID: id, Direction: wire.TransferOutbound, Repo: x.r.Repo, TaskID: p.TaskID, StepID: p.StepID, Attempt: p.Attempt, BaseSHA: p.BaseSHA, CandidateSHA: p.CandidateSHA}
187 if err := x.state.AcceptUpload(context.Background(), "sp-"+id, wire.SendPackCommand{Transfer: h, Have: []string{}}); err != nil {
188 t.Error(err)
189 }
190 return id
191}
192
193// committed is the newest committed report ("" candidate: none).
194func (x *engRig) committed() wire.StepReport {
195 x.mu.Lock()
196 defer x.mu.Unlock()
197 for i := len(x.said) - 1; i >= 0; i-- {
198 if p := x.said[i]; p.Phase == wire.OutcomeCommitted && p.CandidateSHA != "" {
199 return p
200 }
201 }
202 return wire.StepReport{}
203}
204
205// outbox is every frame the worker has queued, as JSON.
206func (x *engRig) outbox(t *testing.T) []wire.Frame {
207 t.Helper()
208 frames, _, err := x.state.Unacked(context.Background(), 0)
209 if err != nil {
210 t.Fatal(err)
211 }
212 return frames
213}
214
215// uploaded runs the worker's relay and returns the transfer's chunks.
216func (x *engRig) uploaded(t *testing.T, id string) []wire.Blob {
217 t.Helper()
218 x.relay.Once(context.Background())
219 var out []wire.Blob
220 for _, f := range x.outbox(t) {
221 if f.Type != wire.FrameBlob {
222 continue
223 }
224 var b wire.Blob
225 if json.Unmarshal(f.Data, &b) == nil && b.Transfer.ID == id {
226 out = append(out, b)
227 }
228 }
229 return out
230}
231
232// publish gives the uploaded chunks to the primary, which publishes the
233// candidate as it would for the instance's publish command.
234func (x *engRig) publish(t *testing.T, blobs []wire.Blob, cand string) wire.PublishedReport {
235 t.Helper()
236 if len(blobs) == 0 {
237 t.Fatal("nothing was uploaded")
238 }
239 ctx := context.Background()
240 h := blobs[0].Transfer
241 for i, b := range blobs {
242 if err := x.pri.e.O.State.AcceptChunk(ctx, fmt.Sprintf("pc-%s-%d", h.ID, i), b); err != nil {
243 t.Fatal(err)
244 }
245 }
246 pub := "pub-" + h.ID
247 if err := x.pri.e.O.State.AcceptPublish(ctx, pub, wire.PublishCommand{Publication: pub, TaskID: h.TaskID, StepID: h.StepID, Attempt: h.Attempt, Repo: h.Repo, Branch: relayBranch, Person: connPerson, BaseSHA: h.BaseSHA, CandidateSHA: cand, Transfer: h.ID}); err != nil {
248 t.Fatal(err)
249 }
250 x.pri.relay.Once(ctx)
251 for _, p := range x.pri.reports(t) {
252 if p.Publication == pub {
253 return p
254 }
255 }
256 t.Fatal("no published report")
257 return wire.PublishedReport{}
258}
259
260// round runs an attempt to its publication.
261func (x *engRig) round(t *testing.T) wire.StepReport {
262 t.Helper()
263 rep := x.run(t)
264 if rep.State != wire.StepDone || rep.Pushed || rep.CandidateSHA == "" {
265 t.Fatalf("round %s: %+v", x.r.StepID, rep)
266 }
267 c := x.committed()
268 if pub := x.publish(t, x.uploaded(t, fmt.Sprintf("out-%s-%d", c.StepID, x.opened)), rep.CandidateSHA); !pub.Pushed {
269 t.Fatalf("round %s not published: %+v", x.r.StepID, pub)
270 }
271 return rep
272}
273
274// store runs git in the worker's store.
275func (x *engRig) store(t *testing.T, args ...string) (string, error) {
276 t.Helper()
277 out, err := exec.Command("git", append([]string{"--git-dir=" + x.w.objects(x.r.Repo)}, args...)...).CombinedOutput()
278 return strings.TrimSpace(string(out)), err
279}
280
281// remote runs git in the primary's hub remote.
282func (x *engRig) remote(t *testing.T, args ...string) string {
283 t.Helper()
284 out, err := exec.Command("git", append([]string{"--git-dir=" + x.pri.f.dir}, args...)...).CombinedOutput()
285 if err != nil {
286 t.Fatalf("git %v: %v %s", args, err, out)
287 }
288 return strings.TrimSpace(string(out))
289}
290
291// moveMain moves the remote's default branch on with one commit that
292// writes file; it returns the new tip.
293func (x *engRig) moveMain(t *testing.T, file, text string) string {
294 t.Helper()
295 work := filepath.Join(t.TempDir(), "mover")
296 gitOut(t, filepath.Dir(work), "clone", "-q", "-b", "main", x.pri.f.dir, work)
297 os.WriteFile(filepath.Join(work, file), []byte(text), 0644)
298 gitOut(t, work, "add", "-A")
299 gitOut(t, work, "commit", "-q", "-m", "main moves")
300 gitOut(t, work, "push", "-q", "origin", "main")
301 return gitOut(t, work, "rev-parse", "HEAD")
302}
303
304// clean fails if any frame the worker queued, its log, or a step log it
305// keeps on disk (<state>/steps) holds one of words (raw, or in base64).
306func (x *engRig) clean(t *testing.T, words ...string) {
307 t.Helper()
308 var all bytes.Buffer
309 for _, f := range x.outbox(t) {
310 all.Write(f.Data)
311 }
312 all.WriteString(x.logs.String())
313 _ = filepath.WalkDir(x.w.Engine.root(), func(path string, d os.DirEntry, err error) error {
314 if err == nil && !d.IsDir() {
315 raw, _ := os.ReadFile(path)
316 all.Write(raw)
317 }
318 return nil
319 })
320 for _, w := range words {
321 for _, form := range []string{w, base64.StdEncoding.EncodeToString([]byte(w))} {
322 if strings.Contains(all.String(), form) {
323 t.Fatalf("%q left the worker (or is in its log)", form)
324 }
325 }
326 }
327}
328
329// An attempt runs to done, not pushed: the committed report names the
330// candidate and its outcome, the worker uploads its thin pack, and the
331// primary publishes exactly that commit, Equipo's, on the base.
332func TestWorkerEngineeringCommitsAndUploads(t *testing.T) {
333 x := newEngRig(t)
334 x.note("edit:Swipe.swift|false|true")
335 before := x.steps()
336 rep := x.run(t)
337 if rep.State != wire.StepDone || rep.Pushed || !rep.Termination || rep.Reason != "" || rep.BaseSHA != x.pri.base || rep.CandidateSHA == "" || !rep.Apple || rep.Account == "" {
338 t.Fatalf("report %+v\n%s", rep, x.logs.String())
339 }
340 cand := rep.CandidateSHA
341 c := x.committed()
342 if c.CandidateSHA != cand || c.OutcomePhase != wire.OutcomeCommitted || c.State != "" && c.State != wire.StepRunning {
343 t.Fatalf("committed report %+v", c)
344 }
345 if x.steps() != before+1 {
346 t.Fatalf("%d launches", x.steps()-before)
347 }
348 pub := x.publish(t, x.uploaded(t, "out-s1-1"), cand)
349 if !pub.Pushed || x.pri.head(t) != cand {
350 t.Fatalf("published %+v head %s", pub, x.pri.head(t))
351 }
352 if parents := x.remote(t, "rev-list", "--parents", "-n", "1", cand); parents != cand+" "+x.pri.base {
353 t.Fatalf("parents %q", parents)
354 }
355 if who := x.remote(t, "log", "-1", "--format=%an <%ae>", cand); who != commitName+" <"+commitEmail+">" {
356 t.Fatalf("made by %q", who)
357 }
358 if body := x.remote(t, "show", cand+":Swipe.swift"); body != "let back = true" {
359 t.Fatalf("change %q", body)
360 }
361 // Retained: the store's ref pins the candidate, whole.
362 if got, err := x.store(t, "rev-parse", "--verify", candidateRef(x.r)); err != nil || got != cand {
363 t.Fatalf("candidate ref %q %v", got, err)
364 }
365 // The kept session, for fix rounds and questions.
366 k, found, err := x.state.keptCommit(context.Background(), "tk1", connPerson, wire.SpecialistEngineering, cand)
367 if err != nil || !found || k.Attempt != 1 {
368 t.Fatalf("kept %+v %v %v", k, found, err)
369 }
370 if _, err := os.Stat(keptTranscript(k.Dir, k.SessionID)); err != nil {
371 t.Fatal(err)
372 }
373 if _, err := os.Stat(filepath.Join(x.w.stepsDir(), stepKey(x.r))); !os.IsNotExist(err) {
374 t.Fatalf("the attempt's directory stayed: %v", err)
375 }
376 if !x.turnFree() {
377 t.Fatal("the attempt kept the Mac's turn")
378 }
379 x.clean(t, x.tokens[0], engBearer)
380}
381
382// Each guard refuses before anything runs: no launch, no store, the
383// turn free.
384func TestWorkerEngineeringRefusesGuards(t *testing.T) {
385 for name, c := range map[string]struct {
386 change func(*engRig)
387 reason string
388 }{
389 "not an owner": {func(x *engRig) { x.r.Person = "q@example.com" }, "policy_rejected"},
390 "not a hub repository": {func(x *engRig) { x.r.Repo = "github.com/oficina/sample" }, "policy_rejected"},
391 "not a task branch": {func(x *engRig) { x.r.Branch = "main" }, "policy_rejected"},
392 "no base": {func(x *engRig) { x.r.BaseSHA = "" }, "policy_rejected"},
393 "a rebase without commits": {func(x *engRig) { x.r.Rebase = true }, "policy_rejected"},
394 "a republish": {func(x *engRig) { x.r.Republish, x.r.FromAttempt, x.r.CandidateSHA = true, 1, x.pri.commit }, "policy_rejected"},
395 "a task id no ref holds": {func(x *engRig) { x.r.TaskID = "tk1/../x" }, "policy_rejected"},
396 "unknown Xcode access": {func(x *engRig) { x.r.XcodeAccess = "full" }, "policy_rejected"},
397 "below protocol 37": {func(x *engRig) { x.w.Engine.Spoken = func() int { return wire.ProtocolMacEngineering - 1 } }, wire.ReasonEngineeringUnavailable},
398 "status not ready": {func(x *engRig) {
399 x.w.Eng.Status = func(context.Context) *wire.EngineeringStatus {
400 return &wire.EngineeringStatus{State: wire.EngineeringNoConnection}
401 }
402 }, wire.ReasonEngineeringUnavailable},
403 "status unknown": {func(x *engRig) { x.w.Eng.Status = func(context.Context) *wire.EngineeringStatus { return nil } }, wire.ReasonEngineeringUnavailable},
404 "Xcode access not proven": {func(x *engRig) { x.r.XcodeAccess = wire.XcodeAccessSandboxed }, wire.ReasonEngineeringUnavailable},
405 "no Mac Engineering": {func(x *engRig) { x.w.Eng = nil }, wire.ReasonEngineeringUnavailable},
406 "secrets unreadable": {func(x *engRig) {
407 x.w.Eng.Secrets = func(context.Context) ([]string, error) { return nil, os.ErrPermission }
408 }, wire.ReasonEngineeringUnavailable},
409 } {
410 t.Run(name, func(t *testing.T) {
411 x := newEngRig(t)
412 x.note("edit:Swipe.swift|false|true")
413 before := len(x.launches())
414 x.inbound(t)
415 c.change(x)
416 rep := x.exec(t, x.r)
417 if rep.State != wire.StepFailed || rep.Reason != c.reason || !rep.Termination || rep.CandidateSHA != "" {
418 t.Fatalf("report %+v", rep)
419 }
420 if n := len(x.launches()) - before; n != 0 {
421 t.Fatalf("%d launches", n)
422 }
423 if _, err := os.Stat(x.w.objects("amadan.net/oficina/sample")); !os.IsNotExist(err) {
424 t.Fatalf("the store was made: %v", err)
425 }
426 if !x.turnFree() {
427 t.Fatal("the turn was kept")
428 }
429 })
430 }
431}
432
433// One store across rounds: after two fix rounds and a rebase, git log
434// and rev-list in the store stop at the boundaries the packs named, and
435// the thin pack of the newest candidate builds.
436func TestWorkerStoreShallowBoundaries(t *testing.T) {
437 x := newEngRig(t)
438 base0 := x.pri.base
439 // walk is rev-list of the round's candidate ref in the store: it must
440 // succeed and stop at the round's base, the boundary its pack named.
441 walk := func(want ...string) {
442 t.Helper()
443 got, err := x.store(t, "rev-list", candidateRef(x.r))
444 if err != nil || got != strings.Join(want, "\n") {
445 t.Fatalf("rev-list of %s: %q %v, want %v", x.r.StepID, got, err, want)
446 }
447 }
448 x.note("edit:Swipe.swift|false|true")
449 c1 := x.round(t).CandidateSHA
450 walk(c1, base0)
451 fix := func(step, base, edit string) string {
452 x.r = x.dispatch(step, base, "Swipe back")
453 x.r.Round, x.r.Feedback = 1, "CI: the swipe test failed."
454 x.note(edit)
455 c := x.round(t).CandidateSHA
456 walk(c, base)
457 return c
458 }
459 c2 := fix("s2", c1, "create:Back.swift|let back2 = 1")
460 c3 := fix("s3", c2, "create:Back3.swift|let back3 = 1")
461 tip := x.moveMain(t, "Main.swift", "let main = 1\n")
462 x.r = x.dispatch("s4", tip, "Swipe back")
463 x.r.Rebase, x.r.FromBase, x.r.CandidateSHA = true, base0, c3
464 x.note("")
465 c4 := x.round(t).CandidateSHA
466 log, err := x.store(t, "log", "--format=%H", candidateRef(x.r))
467 if err != nil || log != c4+"\n"+tip {
468 t.Fatalf("log of the rebased candidate: %q %v", log, err)
469 }
470 for _, args := range [][]string{{"log", "--all", "--format=%H"}, {"rev-list", "--all", "--objects"}} {
471 if out, err := x.store(t, args...); err != nil {
472 t.Fatalf("%v: %v %s", args, err, out)
473 }
474 }
475 pack := exec.Command("git", "--git-dir="+x.w.objects(x.r.Repo), "pack-objects", "--revs", "--thin", "--stdout", "-q")
476 pack.Stdin = strings.NewReader(c4 + "\n^" + tip + "\n")
477 if out, err := pack.Output(); err != nil || len(out) == 0 {
478 t.Fatalf("thin pack: %v", err)
479 }
480}
481
482// A rebase round on the worker: the three commits relayed, the change
483// merged onto the new tip with the explicit merge base, the conflict
484// resolved, and the rebased commit published on the new tip.
485func TestWorkerEngineeringRebaseRound(t *testing.T) {
486 x := newEngRig(t)
487 base0 := x.pri.base
488 x.note("edit:Swipe.swift|false|true")
489 c1 := x.round(t).CandidateSHA
490 tip := x.moveMain(t, "Swipe.swift", "let back = maybe\n")
491 x.r = x.dispatch("s2", tip, "Swipe back")
492 x.r.Rebase, x.r.FromBase, x.r.CandidateSHA = true, base0, c1
493 x.note("")
494 c2 := x.round(t).CandidateSHA
495 if parents := x.remote(t, "rev-list", "--parents", "-n", "1", c2); parents != c2+" "+tip {
496 t.Fatalf("parents %q", parents)
497 }
498 if body := x.remote(t, "show", c2+":Swipe.swift"); body != "let back = true" {
499 t.Fatalf("resolved %q", body)
500 }
501}
502
503// A fix round resumes the session that made the commit it starts from.
504func TestWorkerEngineeringFixRoundResumes(t *testing.T) {
505 x := newEngRig(t)
506 x.note("edit:Swipe.swift|false|true")
507 c1 := x.round(t).CandidateSHA
508 k, found, err := x.state.keptCommit(context.Background(), "tk1", connPerson, wire.SpecialistEngineering, c1)
509 if err != nil || !found {
510 t.Fatalf("no kept session: %v", err)
511 }
512 x.r = x.dispatch("s2", c1, "Swipe back")
513 x.r.Round, x.r.Feedback = 1, "CI: the swipe test failed."
514 x.note("create:Fix.swift|let fixed = true")
515 rep := x.round(t)
516 resumed := false
517 for _, l := range x.launches() {
518 if strings.Contains(l.argv, "--resume "+k.SessionID) {
519 resumed = true
520 }
521 }
522 if !resumed || !strings.Contains(rep.Summary, "(resumed session)") {
523 t.Fatalf("not resumed (session %s): %+v", k.SessionID, rep)
524 }
525 if body, err := x.store(t, "show", rep.CandidateSHA+":Fix.swift"); err != nil || body != "let fixed = true" {
526 t.Fatalf("the round's change %q %v", body, err)
527 }
528}
529
530// The object scan: every form of a known secret, anywhere in the new
531// objects, refuses the step with nothing uploaded and nothing named; so
532// does gitleaks finding a key, the scanner failing, or an object past the
533// bound. A known secret in the CLI's own words is redacted.
534func TestWorkerObjectScan(t *testing.T) {
535 token := fakeclaude.Token("a@example.com")
536 binary := append(append([]byte{0, 1, 0xff, 0xfe}, []byte(base64.StdEncoding.EncodeToString([]byte(token)))...), 0, 7)
537 urlForm := base64.URLEncoding.EncodeToString([]byte(engBearer))
538 if !strings.ContainsAny(urlForm, "-_") {
539 t.Fatalf("the bearer's URL form %q is its standard form", urlForm)
540 }
541 for name, c := range map[string]struct {
542 note string
543 names []string
544 before func(*testing.T, *engRig)
545 // base: files the base already holds; kind: the diagnostic's kind.
546 base map[string]string
547 kind string
548 }{
549 // Paths gitleaks' defaults would skip are scanned on a worker.
550 "gitleaks under node_modules": {note: "create:node_modules/key.txt|token = \"ghp_" + "R4nd0mT0k3nW1thH1ghEntr0pyXyZ987654321\"", names: []string{"node_modules/key.txt"}, kind: "gitleaks"},
551 "gitleaks in gitleaks.toml": {note: "create:gitleaks.toml|token = \"ghp_" + "R4nd0mT0k3nW1thH1ghEntr0pyXyZ987654321\"", names: []string{"gitleaks.toml"}, kind: "gitleaks"},
552 "gitleaks in a .bin file": {note: "create:firmware.bin|token = \"ghp_" + "R4nd0mT0k3nW1thH1ghEntr0pyXyZ987654321\"", names: []string{"firmware.bin"}, kind: "gitleaks"},
553 "gitleaks by file name": {note: "create:nuget.config|<configuration><packageSourceCredentials><feed><add key=\"Username\" value=\"me\" /><add key=\"ClearTextPassword\" value=\"Xk9pQ2vR7sLm4TzWq8Ny\" /></feed></packageSourceCredentials></configuration>", names: []string{"nuget.config"}, kind: "gitleaks"},
554 "gitleaks in a renamed file": {base: map[string]string{"old-settings.txt": "token = \"ghp_" + "R4nd0mT0k3nW1thH1ghEntr0pyXyZ987654321\"\n"}, note: "move:old-settings.txt|moved-settings.txt", names: []string{"moved-settings.txt"}, kind: "gitleaks"},
555 "raw in a text file": {note: "create:notes.txt|key " + token, names: []string{"notes.txt"}},
556 "base64 in a binary file": {note: "bytes:blob.bin|" + base64.StdEncoding.EncodeToString(binary), names: []string{"blob.bin"}},
557 "in a file name": {note: "create:" + token + ".txt|hello"},
558 "in a symlink target": {note: "symlink:planted-link|/tmp/" + token, names: []string{"planted-link"}},
559 "hex-encoded": {note: "create:hex.txt|" + hex.EncodeToString([]byte(token)), names: []string{"hex.txt"}},
560 "the runner credential, URL": {note: "create:cred.txt|" + urlForm, names: []string{"cred.txt"}},
561 "gitleaks finds a key": {note: "create:keys.txt|token = \"ghp_" + "R4nd0mT0k3nW1thH1ghEntr0pyXyZ987654321\"", names: []string{"keys.txt"}},
562 "the scanner fails": {note: "edit:Swipe.swift|false|true", before: func(t *testing.T, x *engRig) {
563 script := filepath.Join(x.dir, "bin", "gitleaks")
564 os.Remove(script)
565 body := []byte("#!/bin/sh\nexit 2\n")
566 if err := os.WriteFile(script, body, 0o700); err != nil {
567 t.Fatal(err)
568 }
569 sum := sha256.Sum256(body)
570 old := previewScannerTool
571 previewScannerTool = func(c runner.Config) (string, string) { return script, hex.EncodeToString(sum[:]) }
572 t.Cleanup(func() { previewScannerTool = old })
573 }},
574 "an object past the bound": {note: "edit:Swipe.swift|false|true", kind: "too_large", before: func(t *testing.T, x *engRig) {
575 old := workerScanBound
576 workerScanBound = 64
577 t.Cleanup(func() { workerScanBound = old })
578 }},
579 } {
580 t.Run(name, func(t *testing.T) {
581 x := newEngRigWith(t, c.base)
582 if c.before != nil {
583 c.before(t, x)
584 }
585 x.note(c.note)
586 rep := x.run(t)
587 if rep.State != wire.StepFailed || rep.Reason != wire.ReasonSecretInCandidate || !rep.Termination || rep.CandidateSHA != "" || rep.Summary != "" || rep.Headline != "" || rep.LogTail != "" {
588 t.Fatalf("report %+v", rep)
589 }
590 if c := x.committed(); c.CandidateSHA != "" {
591 t.Fatalf("committed %+v", c)
592 }
593 for _, f := range x.outbox(t) {
594 if f.Type == wire.FrameBlob {
595 t.Fatal("a pack was queued")
596 }
597 }
598 if refs, _ := x.store(t, "for-each-ref", "refs/equipo/"); refs != "" {
599 t.Fatalf("the refused candidate is pinned: %s", refs)
600 }
601 x.clean(t, append([]string{token, engBearer, hex.EncodeToString([]byte(token))}, c.names...)...)
602 if !strings.Contains(x.logs.String(), "secret in candidate") || c.kind != "" && !strings.Contains(x.logs.String(), "kind="+c.kind) {
603 t.Fatalf("no diagnostic (kind %q): %s", c.kind, x.logs.String())
604 }
605 // The step log, which names files, is gone; so is the session.
606 if _, err := os.Stat(filepath.Join(x.w.Engine.root(), stepKey(x.r), "log.jsonl")); !os.IsNotExist(err) {
607 t.Fatalf("the refused attempt's step log stayed: %v", err)
608 }
609 if n := x.keptRows(t); n != 0 {
610 t.Fatalf("%d kept sessions of a refused attempt", n)
611 }
612 })
613 }
614 t.Run("in the CLI's summary", func(t *testing.T) {
615 x := newEngRig(t)
616 // The token, and what no generic pattern takes for a secret: the
617 // runner credential and the token's hex.
618 x.note("say:my key is " + token + " and " + engBearer + " and " + hex.EncodeToString([]byte(token)))
619 rep := x.run(t)
620 if rep.State != wire.StepFailed || rep.Reason != "no_changes" || !strings.Contains(rep.Summary, "***") {
621 t.Fatalf("report %+v", rep)
622 }
623 x.clean(t, token, engBearer, hex.EncodeToString([]byte(token)))
624 })
625 // Whole-branch fix 3, #4: a known secret the CLI writes into what
626 // becomes the commit message is redacted before the commit is made,
627 // so the candidate goes with "***" in its message.
628 t.Run("in the commit message", func(t *testing.T) {
629 x := newEngRig(t)
630 x.note("edit:Swipe.swift|false|true\nsay:" + token)
631 rep := x.run(t)
632 if rep.State != wire.StepDone || rep.CandidateSHA == "" {
633 t.Fatalf("report %+v", rep)
634 }
635 msg, err := x.store(t, "log", "-1", "--format=%B", rep.CandidateSHA)
636 if err != nil || strings.Contains(msg, token) || !strings.Contains(msg, "***") {
637 t.Fatalf("message %q %v", msg, err)
638 }
639 })
640}
641
642// The candidate is retained in the store: with the attempt's directory
643// gone and the runner started again, the upload is answered, a second
644// send_pack (Retry after the primary was replaced) is answered from the
645// store too, and the candidate is there to be read.
646func TestWorkerCandidateRetained(t *testing.T) {
647 x := newEngRig(t)
648 x.noUpload = true
649 x.note("edit:Swipe.swift|false|true")
650 rep := x.run(t)
651 if rep.State != wire.StepDone || rep.CandidateSHA == "" {
652 t.Fatalf("report %+v", rep)
653 }
654 cand := rep.CandidateSHA
655 if _, err := os.Stat(filepath.Join(x.w.stepsDir(), stepKey(x.r))); !os.IsNotExist(err) {
656 t.Fatal("the attempt's directory stayed")
657 }
658 // The runner starts again: nothing but its state and its store.
659 first := x.sendPack(t, x.committed())
660 e := &Engineer{O: x.w.Engine.O}
661 x.w = &Worker{State: x.state, Engine: e, StepRoot: x.w.StepRoot}
662 x.relay = &Relay{State: x.state, Engine: e, Worker: x.w}
663 if pub := x.publish(t, x.uploaded(t, first), cand); !pub.Pushed || x.pri.head(t) != cand {
664 t.Fatalf("published after a restart: %+v", pub)
665 }
666 again := x.sendPack(t, x.committed())
667 if pub := x.publish(t, x.uploaded(t, again), cand); !pub.Pushed {
668 t.Fatalf("published again: %+v", pub)
669 }
670 if body, err := x.store(t, "show", candidateRef(x.r)+":Swipe.swift"); err != nil || body != "let back = true" {
671 t.Fatalf("the candidate from the store: %q %v", body, err)
672 }
673 // Another candidate, or another base, is refused.
674 wrong := x.committed()
675 wrong.CandidateSHA = x.pri.commit
676 if blobs := x.uploaded(t, x.sendPack(t, wrong)); len(blobs) != 0 {
677 t.Fatal("a candidate the attempt did not make was uploaded")
678 }
679 wrong = x.committed()
680 wrong.BaseSHA = cand
681 if blobs := x.uploaded(t, x.sendPack(t, wrong)); len(blobs) != 0 {
682 t.Fatal("a pack on another base was uploaded")
683 }
684 // A ref that no longer pins the candidate: nothing goes.
685 if _, err := x.store(t, "update-ref", candidateRef(x.r), x.pri.base); err != nil {
686 t.Fatal(err)
687 }
688 if blobs := x.uploaded(t, x.sendPack(t, x.committed())); len(blobs) != 0 {
689 t.Fatal("uploaded what its ref no longer pins")
690 }
691 if _, err := x.store(t, "update-ref", candidateRef(x.r), cand); err != nil {
692 t.Fatal(err)
693 }
694 // A retention record that cannot be read: nothing goes.
695 if _, err := x.state.db.Exec("ALTER TABLE candidates RENAME TO candidates_gone"); err != nil {
696 t.Fatal(err)
697 }
698 if blobs := x.uploaded(t, x.sendPack(t, x.committed())); len(blobs) != 0 {
699 t.Fatal("uploaded without its retention record")
700 }
701}
702
703// forget_task: with no KeepUntil the candidate's ref and the kept
704// session go at once; with a later one they stay until it passes.
705func TestWorkerForgetTask(t *testing.T) {
706 for _, keep := range []bool{false, true} {
707 t.Run(fmt.Sprintf("keep=%v", keep), func(t *testing.T) {
708 x := newEngRig(t)
709 x.note("edit:Swipe.swift|false|true")
710 cand := x.round(t).CandidateSHA
711 ctx := context.Background()
712 k, _, _ := x.state.keptCommit(ctx, "tk1", connPerson, wire.SpecialistEngineering, cand)
713 cmd := wire.ForgetTaskCommand{Person: connPerson, TaskID: "tk1"}
714 if keep {
715 until := time.Now().Add(time.Second)
716 cmd.KeepUntil = &until
717 }
718 dirs, err := x.state.ForgetTask(ctx, "forget-1", cmd)
719 if err != nil {
720 t.Fatal(err)
721 }
722 x.w.forget(ctx, dirs)
723 gone := func() bool {
724 _, refErr := x.store(t, "rev-parse", "--verify", candidateRef(x.r))
725 _, dirErr := os.Stat(k.Dir)
726 _, found, _ := x.state.keptCommit(ctx, "tk1", connPerson, wire.SpecialistEngineering, cand)
727 return refErr != nil && os.IsNotExist(dirErr) && !found
728 }
729 if !keep {
730 if !gone() {
731 t.Fatal("not forgotten at once")
732 }
733 if blobs := x.uploaded(t, x.sendPack(t, x.committed())); len(blobs) != 0 {
734 t.Fatal("a forgotten candidate was uploaded")
735 }
736 return
737 }
738 if gone() {
739 t.Fatal("forgotten before its keep")
740 }
741 // Past its keep with nothing swept yet (a runner that was down at
742 // the deadline): the ref is still there, and nothing goes.
743 if _, err := x.state.db.Exec("UPDATE candidates SET expires_at=?", stamp(time.Now().Add(-time.Second))); err != nil {
744 t.Fatal(err)
745 }
746 if blobs := x.uploaded(t, x.sendPack(t, x.committed())); len(blobs) != 0 {
747 t.Fatal("a candidate past its keep, not yet swept, was uploaded")
748 }
749 if _, err := x.store(t, "rev-parse", "--verify", candidateRef(x.r)); err != nil {
750 t.Fatal("the ref went before the sweep: the case shows nothing")
751 }
752 time.Sleep(1100 * time.Millisecond)
753 // Past its keep, never uploaded again, sweep or not.
754 if blobs := x.uploaded(t, x.sendPack(t, x.committed())); len(blobs) != 0 {
755 t.Fatal("a candidate past its keep was uploaded")
756 }
757 // The cleanup was scheduled at the deadline: nobody sweeps here.
758 deadline := time.Now().Add(5 * time.Second)
759 for !gone() && time.Now().Before(deadline) {
760 time.Sleep(100 * time.Millisecond)
761 }
762 if !gone() {
763 t.Fatal("kept past its keep")
764 }
765 })
766 }
767}
768
769// A restart after committed resumes: the CLI never runs again for the
770// attempt, the committed report is said again, and the upload answered.
771func TestWorkerEngineeringRestartAfterCommit(t *testing.T) {
772 x := newEngRig(t)
773 x.noUpload = true
774 x.note("edit:Swipe.swift|false|true")
775 rep := x.run(t)
776 cand := rep.CandidateSHA
777 ctx := context.Background()
778 // The runner stopped before its final report was kept.
779 if _, err := x.state.db.Exec("UPDATE steps SET state='running' WHERE step_id=?", x.r.StepID); err != nil {
780 t.Fatal(err)
781 }
782 if err := x.state.RecoverSteps(ctx, func(context.Context, string) bool { return true }); err != nil {
783 t.Fatal(err)
784 }
785 r, ok, err := x.state.nextStep(ctx)
786 if err != nil || !ok || !committed(r.Phase) {
787 t.Fatalf("after the restart: %+v %v %v", r, ok, err)
788 }
789 launched := x.steps()
790 x.mu.Lock()
791 x.said = nil
792 x.mu.Unlock()
793 x.noUpload = false
794 again := x.exec(t, r)
795 if again.State != wire.StepDone || again.CandidateSHA != cand || again.Pushed || !again.Termination || x.steps() != launched {
796 t.Fatalf("resumed %+v, %d new launches", again, x.steps()-launched)
797 }
798 if c := x.committed(); c.CandidateSHA != cand || c.OutcomePhase != wire.OutcomeCommitted {
799 t.Fatalf("committed again %+v", c)
800 }
801 if again.SessionID == "" || again.SessionID != rep.SessionID || !again.Askable || again.Apple != rep.Apple || again.Summary != rep.Summary || again.Headline != rep.Headline {
802 t.Fatalf("resumed without the attempt's report: %+v, was %+v", again, rep)
803 }
804 if pub := x.publish(t, x.uploaded(t, fmt.Sprintf("out-s1-%d", x.opened)), cand); !pub.Pushed {
805 t.Fatalf("published %+v", pub)
806 }
807}
808
809// A limit on the first connection fails over to the next, as a new
810// attempt from a fresh tree: what the refused attempt left is not in the
811// candidate.
812func TestWorkerEngineeringFailover(t *testing.T) {
813 x := newEngRig(t, "a@example.com", "b@example.com")
814 x.note("steplimit:a@example.com limitleave:Leftover.txt\nedit:Swipe.swift|false|true")
815 rep := x.run(t)
816 if rep.State != wire.StepDone || rep.Attempt != 2 || rep.Switched == nil || rep.CandidateSHA == "" {
817 t.Fatalf("report %+v", rep)
818 }
819 cand := rep.CandidateSHA
820 if _, err := x.store(t, "cat-file", "-e", cand+":Leftover.txt"); err == nil {
821 t.Fatal("the refused attempt's tree was reused")
822 }
823 if body, err := x.store(t, "show", cand+":Swipe.swift"); err != nil || body != "let back = true" {
824 t.Fatalf("change %q %v", body, err)
825 }
826 r2 := x.r
827 r2.Attempt = 2
828 if got, err := x.store(t, "rev-parse", "--verify", candidateRef(r2)); err != nil || got != cand {
829 t.Fatalf("ref %q %v", got, err)
830 }
831}
832
833// The checks path is unchanged by Engineering's: a checks dispatch still
834// runs the gate on the relayed candidate, and a specialist a worker does
835// not take is still refused.
836func TestWorkerChecksUnchanged(t *testing.T) {
837 x := newWorkerRig(t)
838 x.chunk(t, "c1", x.header(), x.pack, 0, 1, "")
839 if rep := x.run(); rep.State != wire.StepDone || rep.Checks != wire.ChecksPassed || len(x.gate.ran) != 1 {
840 t.Fatalf("checks %+v", rep)
841 }
842 x.r.Specialist = wire.SpecialistReview
843 if rep := x.run(); rep.State != wire.StepFailed || rep.Reason != "placement_refused" || len(x.gate.ran) != 1 {
844 t.Fatalf("review %+v", rep)
845 }
846}
847
848// The worker's prompt is the primary's, for the Mac: the worktree's real
849// path, no Linux toolchain, the Research findings quoted, and its kept
850// images on the main runner, never relayed.
851func TestWorkerEngineeringPromptForTheMac(t *testing.T) {
852 x := newEngRig(t)
853 findings, _ := json.Marshal(wire.ResearchFindings{Summary: "Swipes go back.", Facts: []wire.ResearchFact{}, Images: []string{"img1"}, Gaps: []string{}})
854 x.r.RunnerID = "rn-mac"
855 x.r.ResearchNote = &wire.ResearchHandoff{Findings: findings, Sources: []wire.ResearchSource{}, Images: []wire.ResearchImage{{ID: "img1", SourceID: "s1", Role: "reference", Description: "a screen", SHA256: strings.Repeat("a", 64), Size: 10, Width: 2, Height: 2}}}
856 x.note("edit:Swipe.swift|false|true")
857 rep := x.run(t)
858 if rep.State != wire.StepDone {
859 t.Fatalf("report %+v", rep)
860 }
861 k, _, _ := x.state.keptCommit(context.Background(), "tk1", connPerson, wire.SpecialistEngineering, rep.CandidateSHA)
862 raw, err := os.ReadFile(keptTranscript(k.Dir, k.SessionID))
863 if err != nil {
864 t.Fatal(err)
865 }
866 var prompt string
867 for _, line := range strings.Split(string(raw), "\n") {
868 var v struct{ Type, Text string }
869 if json.Unmarshal([]byte(line), &v) == nil && v.Type == "user" {
870 prompt = v.Text
871 }
872 }
873 tree := filepath.Join(x.w.stepsDir(), stepKey(x.r), "tree")
874 for _, want := range []string{"checked out in " + tree, "Swipes go back.", "they stay on the main runner"} {
875 if !strings.Contains(prompt, want) {
876 t.Errorf("the prompt lacks %q:\n%s", want, prompt)
877 }
878 }
879 for _, never := range []string{"/workspace", "/opt/go", "/research/"} {
880 if strings.Contains(prompt, never) {
881 t.Errorf("the prompt names %q:\n%s", never, prompt)
882 }
883 }
884}
885
886// The inbound pack is checked before anything runs: chunks under another
887// header, and a pack that is not exactly the named commits, each whole.
888func TestWorkerEngineeringRefusesPacks(t *testing.T) {
889 for name, feed := range map[string]func(*testing.T, *engRig){
890 "a checks header": func(t *testing.T, x *engRig) {
891 h := wire.TransferHeader{ID: "in-x", Direction: wire.TransferInbound, Repo: x.r.Repo, TaskID: x.r.TaskID, StepID: x.r.StepID, Attempt: x.r.Attempt, BaseSHA: x.r.BaseSHA, CandidateSHA: x.r.BaseSHA}
892 x.chunk(t, h, onePack(t, x.pri.seed, x.pri.base))
893 },
894 "an extra commit": func(t *testing.T, x *engRig) {
895 objects, _ := exec.Command("git", "-C", x.pri.seed, "rev-list", "--objects", "--no-walk", x.pri.base, x.pri.commit).Output()
896 packer := exec.Command("git", "-C", x.pri.seed, "pack-objects", "--stdout", "-q")
897 packer.Stdin = bytes.NewReader(objects)
898 pack, err := packer.Output()
899 if err != nil {
900 t.Fatal(err)
901 }
902 x.chunk(t, x.engHeader(), pack)
903 },
904 "a commit without its tree": func(t *testing.T, x *engRig) {
905 packer := exec.Command("git", "-C", x.pri.seed, "pack-objects", "--stdout", "-q")
906 packer.Stdin = strings.NewReader(x.pri.base + "\n")
907 pack, err := packer.Output()
908 if err != nil {
909 t.Fatal(err)
910 }
911 x.chunk(t, x.engHeader(), pack)
912 },
913 } {
914 t.Run(name, func(t *testing.T) {
915 x := newEngRig(t)
916 x.w.PackWait = 300 * time.Millisecond
917 x.note("edit:Swipe.swift|false|true")
918 before := x.steps()
919 feed(t, x)
920 rep := x.exec(t, x.r)
921 if rep.State != wire.StepFailed || rep.Reason != "candidate_unavailable" || !rep.Termination || x.steps() != before {
922 t.Fatalf("report %+v", rep)
923 }
924 })
925 }
926}
927
928func (x *engRig) engHeader() wire.TransferHeader {
929 return wire.TransferHeader{ID: "in-e", Direction: wire.TransferInbound, Kind: wire.TransferKindEngineering, Repo: x.r.Repo, TaskID: x.r.TaskID, StepID: x.r.StepID, Attempt: x.r.Attempt, BaseSHA: x.r.BaseSHA}
930}
931
932func (x *engRig) chunk(t *testing.T, h wire.TransferHeader, pack []byte) {
933 t.Helper()
934 sum := sha256.Sum256(pack)
935 if err := x.state.AcceptChunk(context.Background(), "chunk-"+h.ID, wire.Blob{Transfer: h, Index: 0, Total: 1, SHA256: hex.EncodeToString(sum[:]), Data: base64.StdEncoding.EncodeToString(pack)}); err != nil {
936 t.Fatal(err)
937 }
938}
939
940// The Mac's guards are asked again before each launch, in the turn: a
941// runner tainted since the dispatch launches nothing.
942func TestWorkerEngineeringGatedPerLaunch(t *testing.T) {
943 x := newEngRig(t)
944 x.note("edit:Swipe.swift|false|true")
945 before := x.steps()
946 x.m.taint.Set()
947 rep := x.run(t)
948 if rep.State != wire.StepFailed || rep.Reason != wire.ReasonEngineeringUnavailable || !rep.Termination || x.steps() != before {
949 t.Fatalf("report %+v, %d launches", rep, x.steps()-before)
950 }
951 if !x.turnFree() {
952 t.Fatal("the turn was kept")
953 }
954}
955
956// A worker's unfinished work is recorded in its outcome field, never in
957// the progress phase, and still goes out as unfinished work.
958func TestWorkerUnfinishedOutcomeField(t *testing.T) {
959 x := newEngRig(t)
960 ctx := context.Background()
961 cand := strings.Repeat("2", 40)
962 if err := x.state.AcceptDispatch(ctx, "d-u", x.r.DispatchCommand); err != nil {
963 t.Fatal(err)
964 }
965 if err := x.state.setWorkerCommitted(ctx, x.r, x.pri.base, cand, wire.OutcomeUnfinished, wire.StepReport{}, false); err != nil {
966 t.Fatal(err)
967 }
968 var phase string
969 if err := x.state.db.QueryRow("SELECT phase FROM steps WHERE step_id=?", x.r.StepID).Scan(&phase); err != nil || phase != phaseCommitted {
970 t.Fatalf("phase %q %v", phase, err)
971 }
972 rep := workerDone(wire.StepReport{TaskID: "tk1", StepID: x.r.StepID, Attempt: 1, CandidateSHA: cand, Findings: []wire.Finding{}}, wire.OutcomeUnfinished)
973 if err := x.state.ReportStep(ctx, x.r, rep); err != nil {
974 t.Fatal(err)
975 }
976 var sent wire.StepReport
977 for _, f := range x.outbox(t) {
978 if f.Type != wire.FrameStep {
979 continue
980 }
981 out, err := x.state.unfinishedReport(ctx, f, wire.ProtocolMacEngineering, true)
982 if err != nil {
983 t.Fatal(err)
984 }
985 json.Unmarshal(out.Data, &sent)
986 }
987 if sent.State != wire.StepDone || sent.Reason != "step_timeout" || sent.Pushed || sent.OutcomePhase != wire.OutcomeUnfinished || sent.CandidateSHA != cand {
988 t.Fatalf("sent %+v", sent)
989 }
990}
991
992// A launch whose record cannot be written starts nothing, but the
993// attempt ends unproven (not terminated, no Retry), as a failover launch
994// after a lost evidence write must (mac.ErrRecord).
995func TestWorkerEngineeringLostRecordUnproven(t *testing.T) {
996 x := newEngRig(t)
997 x.note("edit:Swipe.swift|false|true")
998 // The executor writes the marker's record again before the CLI
999 // starts: that write fails.
1000 if _, err := x.state.db.Exec("CREATE TRIGGER lost_record BEFORE UPDATE OF ns_id ON steps WHEN OLD.ns_id = NEW.ns_id BEGIN SELECT RAISE(FAIL, 'lost'); END"); err != nil {
1001 t.Fatal(err)
1002 }
1003 before := x.steps()
1004 rep := x.run(t)
1005 if rep.State != wire.StepFailed || rep.Reason != wire.ReasonEngineeringUnavailable || rep.Termination || x.steps() != before {
1006 t.Fatalf("report %+v, %d launches", rep, x.steps()-before)
1007 }
1008}
1009
1010// keptRows counts the worker's kept sessions.
1011func (x *engRig) keptRows(t *testing.T) int {
1012 t.Helper()
1013 var n int
1014 if err := x.state.db.QueryRow("SELECT count(*) FROM kept_sessions").Scan(&n); err != nil {
1015 t.Fatal(err)
1016 }
1017 return n
1018}
1019
1020// authLaunches counts the CLI's auth status reads so far.
1021func (x *engRig) authLaunches() int {
1022 n := 0
1023 for _, l := range x.launches() {
1024 if strings.HasPrefix(l.argv, "auth status") {
1025 n++
1026 }
1027 }
1028 return n
1029}
1030
1031// Fix round 1, #1: the runtime copy's auth status can end unproven; the
1032// attempt then ends unproven too, never terminated.
1033func TestWorkerEngineeringPreflightUnproven(t *testing.T) {
1034 x := newEngRig(t)
1035 x.note("edit:Swipe.swift|false|true")
1036 // The next auth status leaves a child that outlives a short settle.
1037 if err := os.WriteFile(filepath.Join(x.dir, "linger"), []byte("auth"), 0o600); err != nil {
1038 t.Fatal(err)
1039 }
1040 x.m.exec.Settle = 300 * time.Millisecond
1041 before := x.steps()
1042 rep := x.run(t)
1043 if rep.State != wire.StepFailed || rep.Termination || x.steps() != before {
1044 t.Fatalf("report %+v, %d launches", rep, x.steps()-before)
1045 }
1046 if pid := waitPid(t, filepath.Join(x.dir, "linger.pid")); pid > 0 {
1047 _ = syscall.Kill(pid, syscall.SIGKILL)
1048 }
1049}
1050
1051// Fix round 1, #1: an auth status that says sign in again fails over to
1052// the next connection, as a refusal of the step's own run does.
1053func TestWorkerEngineeringPreflightSignInFailsOver(t *testing.T) {
1054 x := newEngRig(t, "a@example.com", "b@example.com")
1055 x.note("edit:Swipe.swift|false|true")
1056 first := filepath.Base(x.homes[0])
1057 x.w.Eng.refresh = func(ctx context.Context, b provider.Binding) (provider.Identity, error) {
1058 if filepath.Base(b.Home) == first || strings.Contains(b.Home, first) {
1059 return provider.Identity{}, provider.ErrLoginRequired
1060 }
1061 return x.m.authStatus(ctx, b)
1062 }
1063 rep := x.run(t)
1064 if rep.State != wire.StepDone || rep.Attempt != 2 || rep.Switched == nil || rep.CandidateSHA == "" {
1065 t.Fatalf("report %+v", rep)
1066 }
1067}
1068
1069// Fix round 1, #4: readiness and the Xcode proof are asked again inside
1070// the held turn: a proof lost while the attempt waited for the turn
1071// launches nothing, not even the auth status.
1072func TestWorkerEngineeringReadinessInTheTurn(t *testing.T) {
1073 for _, xcode := range []bool{false, true} {
1074 t.Run(fmt.Sprintf("xcode=%v", xcode), func(t *testing.T) {
1075 x := newEngRig(t)
1076 x.note("edit:Swipe.swift|false|true")
1077 var lost atomic.Bool
1078 x.w.Eng.Status = func(context.Context) *wire.EngineeringStatus {
1079 if !xcode && lost.Load() {
1080 return &wire.EngineeringStatus{State: wire.EngineeringProbesPending}
1081 }
1082 return &wire.EngineeringStatus{State: wire.EngineeringReady}
1083 }
1084 if xcode {
1085 x.r.XcodeAccess = wire.XcodeAccessSandboxed
1086 x.w.Eng.Xcode = func() bool { return !lost.Load() }
1087 }
1088 u, err := x.m.turns.Take(context.Background(), mac.OpProbe)
1089 if err != nil {
1090 t.Fatal(err)
1091 }
1092 if err := x.state.AcceptDispatch(context.Background(), "d-w", x.r.DispatchCommand); err != nil {
1093 t.Fatal(err)
1094 }
1095 x.inbound(t)
1096 auth, steps := x.authLaunches(), x.steps()
1097 done := make(chan wire.StepReport, 1)
1098 go func() { done <- x.exec(t, x.r) }()
1099 time.Sleep(500 * time.Millisecond)
1100 lost.Store(true)
1101 u.Give()
1102 rep := <-done
1103 if rep.State != wire.StepFailed || rep.Reason != wire.ReasonEngineeringUnavailable || x.authLaunches() != auth || x.steps() != steps {
1104 t.Fatalf("report %+v, %d auth, %d step launches", rep, x.authLaunches()-auth, x.steps()-steps)
1105 }
1106 })
1107 }
1108}
1109
1110// Fix round 1, #4: readiness lost while the runtime copy's auth status
1111// ran, in the same turn, still launches no step.
1112func TestWorkerEngineeringReadinessBeforeTheStep(t *testing.T) {
1113 x := newEngRig(t)
1114 x.note("edit:Swipe.swift|false|true")
1115 var lost atomic.Bool
1116 x.w.Eng.Status = func(context.Context) *wire.EngineeringStatus {
1117 if lost.Load() {
1118 return &wire.EngineeringStatus{State: wire.EngineeringSignedOut}
1119 }
1120 return &wire.EngineeringStatus{State: wire.EngineeringReady}
1121 }
1122 x.w.Eng.refresh = func(ctx context.Context, b provider.Binding) (provider.Identity, error) {
1123 id, err := x.m.authStatus(ctx, b)
1124 lost.Store(true)
1125 return id, err
1126 }
1127 before := x.steps()
1128 rep := x.run(t)
1129 if rep.State != wire.StepFailed || rep.Reason != wire.ReasonEngineeringUnavailable || x.steps() != before {
1130 t.Fatalf("report %+v, %d step launches", rep, x.steps()-before)
1131 }
1132}
1133
1134// Fix round 1, #5: a crash on either side of the committed transition.
1135// Before it, the attempt ends runner_restarted and nothing is uploaded;
1136// after it, the restart reports what the attempt reported (session,
1137// askable, Apple, words) and the kept session is bound to the candidate.
1138func TestWorkerEngineeringCrashAroundCommitted(t *testing.T) {
1139 for _, point := range []string{"retained", "committed"} {
1140 t.Run(point, func(t *testing.T) {
1141 x := newEngRig(t)
1142 x.noUpload = true
1143 x.note("edit:Swipe.swift|false|true")
1144 old := workerFault
1145 workerFault = func(p string) bool { return p == point }
1146 t.Cleanup(func() { workerFault = old })
1147 if err := x.state.AcceptDispatch(context.Background(), "d-c", x.r.DispatchCommand); err != nil {
1148 t.Fatal(err)
1149 }
1150 x.inbound(t)
1151 x.exec(t, x.r)
1152 workerFault = old
1153 ctx := context.Background()
1154 if err := x.state.RecoverSteps(ctx, func(context.Context, string) bool { return true }); err != nil {
1155 t.Fatal(err)
1156 }
1157 if point == "retained" {
1158 var state, reason string
1159 x.state.db.QueryRow("SELECT state, final_reason FROM steps WHERE step_id=?", x.r.StepID).Scan(&state, &reason)
1160 if reason != "runner_restarted" {
1161 t.Fatalf("after a crash before committed: %s %s", state, reason)
1162 }
1163 refs, _ := x.store(t, "for-each-ref", "--format=%(objectname)", "refs/equipo/")
1164 p := wire.StepReport{TaskID: "tk1", StepID: x.r.StepID, Attempt: 1, BaseSHA: x.pri.base, CandidateSHA: refs}
1165 if refs == "" || len(x.uploaded(t, x.sendPack(t, p))) != 0 {
1166 t.Fatalf("an uncommitted candidate (%q) was uploaded", refs)
1167 }
1168 return
1169 }
1170 r, ok, err := x.state.nextStep(ctx)
1171 if err != nil || !ok || !committed(r.Phase) {
1172 t.Fatalf("after the restart: %+v %v %v", r, ok, err)
1173 }
1174 rep := x.exec(t, r)
1175 if rep.State != wire.StepDone || rep.SessionID == "" || !rep.Askable || !rep.Apple || rep.Summary == "" || rep.Account == "" {
1176 t.Fatalf("recovered report %+v", rep)
1177 }
1178 if _, found, _ := x.state.keptCommit(ctx, "tk1", connPerson, wire.SpecialistEngineering, r.Candidate); !found {
1179 t.Fatal("the kept session is not bound to the candidate")
1180 }
1181 })
1182 }
1183}
1184
1185// Fix round 1, #3: finished attempts' step logs go with the sweep.
1186func TestWorkerSweepRemovesStepLogs(t *testing.T) {
1187 x := newEngRig(t)
1188 x.note("edit:Swipe.swift|false|true")
1189 x.run(t)
1190 log := filepath.Join(x.w.Engine.root(), stepKey(x.r), "log.jsonl")
1191 if _, err := os.Stat(log); err != nil {
1192 t.Fatalf("no step log: %v", err)
1193 }
1194 if _, err := x.state.db.Exec("UPDATE steps SET state=? WHERE step_id=?", runDone, x.r.StepID); err != nil {
1195 t.Fatal(err)
1196 }
1197 x.w.sweep(context.Background())
1198 if _, err := os.Stat(log); !os.IsNotExist(err) {
1199 t.Fatalf("the step log stayed: %v", err)
1200 }
1201}
1202
1203// Fix round 1, #7: on a Mac gitleaks runs in the checks gate (srt with
1204// the checks profile P2 proves); the gate's run is read the same way.
1205// Here the gate has no srt (Linux), and the scanner is the pinned one.
1206func TestGateLeaks(t *testing.T) {
1207 runnerPath := previewScannerFixture(t)
1208 binary, pin := previewScannerTool(runner.Config{Executable: runnerPath})
1209 g := &mac.Gate{Env: []string{"PATH=/usr/bin:/bin", "LANG=C"}, ScratchHome: true, Lines: 10, Sandbox: wire.SandboxNone}
1210 for name, c := range map[string]struct {
1211 files map[string]string
1212 found bool
1213 }{
1214 "clean": {map[string]string{"a.swift": "let a = 1\n"}, false},
1215 "under node_modules": {map[string]string{"node_modules/k.txt": "token = \"ghp_" + "R4nd0mT0k3nW1thH1ghEntr0pyXyZ987654321\"\n"}, true},
1216 "a key": {map[string]string{"keys.txt": "token = \"ghp_" + "R4nd0mT0k3nW1thH1ghEntr0pyXyZ987654321\"\n"}, true},
1217 "by name": {map[string]string{"nuget.config": "<configuration><packageSourceCredentials><feed><add key=\"ClearTextPassword\" value=\"Xk9pQ2vR7sLm4TzWq8Ny\" /></feed></packageSourceCredentials></configuration>\n"}, true},
1218 } {
1219 t.Run(name, func(t *testing.T) {
1220 stage := filepath.Join(t.TempDir(), "scan", "files")
1221 for p, body := range c.files {
1222 os.MkdirAll(filepath.Dir(filepath.Join(stage, p)), 0o700)
1223 os.WriteFile(filepath.Join(stage, p), []byte(body), 0o600)
1224 }
1225 found, err := gateLeaks(context.Background(), g, binary, pin, stage, "scan-test", nil)
1226 if err != nil || found != c.found {
1227 t.Fatalf("found %v, %v", found, err)
1228 }
1229 })
1230 }
1231 // Not the pinned scanner: it cannot tell.
1232 if _, err := gateLeaks(context.Background(), g, binary, strings.Repeat("0", 64), t.TempDir(), "scan-test", nil); err == nil {
1233 t.Fatal("an unpinned scanner was run")
1234 }
1235}
1236
1237// Fix round 1, #7: a Mac whose checks gate is not the proven sandboxed
1238// one cannot scan: the candidate does not leave.
1239func TestMacLeaksNeedTheProvenGate(t *testing.T) {
1240 install := filepath.Dir(previewScannerFixture(t))
1241 // Both gates can run the scanner here (no srt on Linux); only the one
1242 // P2's trusted verdict picks for checks may.
1243 sandboxed := &mac.Gate{Env: []string{"PATH=/usr/bin:/bin"}, ScratchHome: true, Lines: 10, Sandbox: wire.SandboxSeatbelt}
1244 bare := &mac.Gate{Env: []string{"PATH=/usr/bin:/bin"}, ScratchHome: true, Lines: 10, Sandbox: wire.SandboxNone}
1245 h := &macHost{paths: mac.Paths{InstallDir: install}, checks: &macChecks{probes: newMacProbes("v", "", nil, func() bool { return true }), taint: &macTaint{}, srt: "/nonexistent/srt", sandboxed: sandboxed, unproven: bare, bare: bare}}
1246 stage := filepath.Join(t.TempDir(), "scan", "files")
1247 os.MkdirAll(stage, 0o700)
1248 os.WriteFile(filepath.Join(stage, "a.swift"), []byte("let a = 1\n"), 0o600)
1249 if _, err := h.leaks(context.Background(), stage, "scan-test", nil); err == nil {
1250 t.Fatal("scanned without the proven gate")
1251 }
1252}
1253
1254// Fix round 2, #1: the worker's trusted rules are gitleaks' defaults with
1255// no path exclusion at all (global or per rule), its file-name rules
1256// kept, and the runner's own rules added.
1257func TestWorkerSecretRules(t *testing.T) {
1258 v := viper.New()
1259 v.SetConfigType("toml")
1260 if err := v.ReadConfig(strings.NewReader(workerSecretRules())); err != nil {
1261 t.Fatal(err)
1262 }
1263 var raw gitleaksconfig.ViperConfig
1264 if err := v.Unmarshal(&raw); err != nil {
1265 t.Fatal(err)
1266 }
1267 cfg, err := raw.Translate()
1268 if err != nil {
1269 t.Fatal(err)
1270 }
1271 for _, a := range cfg.Allowlists {
1272 if len(a.Paths) != 0 {
1273 t.Fatalf("a global path exclusion: %v", a.Paths)
1274 }
1275 }
1276 for id, r := range cfg.Rules {
1277 for _, a := range r.Allowlists {
1278 if len(a.Paths) != 0 {
1279 t.Fatalf("rule %s excludes paths: %v", id, a.Paths)
1280 }
1281 }
1282 }
1283 for _, id := range []string{"nuget-config-password", "pkcs12-file", "github-pat", "equipo-github-token", "equipo-private-key-header"} {
1284 if _, ok := cfg.Rules[id]; !ok {
1285 t.Errorf("rule %s missing", id)
1286 }
1287 }
1288 if r := cfg.Rules["nuget-config-password"]; r.Path == nil {
1289 t.Error("the nuget rule lost its file name")
1290 }
1291}
1292
1293// Fix round 2, #2: the scanner's record cannot be written at its start:
1294// the scan's end is unproven, never an ordinary scanner error.
1295func TestGateLeaksRecordLost(t *testing.T) {
1296 runnerPath := previewScannerFixture(t)
1297 binary, pin := previewScannerTool(runner.Config{Executable: runnerPath})
1298 g := &mac.Gate{Env: []string{"PATH=/usr/bin:/bin"}, ScratchHome: true, Lines: 10, Sandbox: wire.SandboxNone}
1299 stage := filepath.Join(t.TempDir(), "scan", "files")
1300 os.MkdirAll(stage, 0o700)
1301 os.WriteFile(filepath.Join(stage, "a.swift"), []byte("let a = 1\n"), 0o600)
1302 _, err := gateLeaks(context.Background(), g, binary, pin, stage, "scan-test", func(string) error { return errors.New("disk full") })
1303 if !errors.Is(err, errScanUnproven) {
1304 t.Fatalf("a lost scanner record: %v", err)
1305 }
1306}
1307
1308// Fix round 2, #2: in an attempt, the scanner's record write fails as it
1309// starts: secret_in_candidate, unterminated, nothing uploaded.
1310func TestWorkerEngineeringScannerRecordLost(t *testing.T) {
1311 x := newEngRig(t)
1312 x.note("edit:Swipe.swift|false|true")
1313 runnerPath := previewScannerFixture(t)
1314 binary, pin := previewScannerTool(runner.Config{Executable: runnerPath})
1315 g := &mac.Gate{Env: []string{"PATH=/usr/bin:/bin"}, ScratchHome: true, Lines: 10, Sandbox: wire.SandboxSeatbelt}
1316 x.w.Eng.Leaks = func(ctx context.Context, stage, marker string, record func(string) error) (bool, error) {
1317 return gateLeaks(ctx, g, binary, pin, stage, marker, record)
1318 }
1319 stage := filepath.Join(x.w.stepsDir(), stepKey(x.r), "scan", "files")
1320 if _, err := x.state.db.Exec("CREATE TRIGGER lost_scan BEFORE UPDATE OF ns_id ON steps WHEN NEW.ns_id = '" + mac.RecordID(0, engineeringMarker(stage)) + "' BEGIN SELECT RAISE(FAIL, 'lost'); END"); err != nil {
1321 t.Fatal(err)
1322 }
1323 rep := x.run(t)
1324 if rep.State != wire.StepFailed || rep.Reason != wire.ReasonSecretInCandidate || rep.Termination || rep.CandidateSHA != "" {
1325 t.Fatalf("report %+v", rep)
1326 }
1327 if c := x.committed(); c.CandidateSHA != "" {
1328 t.Fatalf("committed %+v", c)
1329 }
1330}
1331
1332// Fix round 2, #3: every chunk's header is compared (State.pack), the
1333// later ones too.
1334func TestWorkerEngineeringRefusesALaterChunk(t *testing.T) {
1335 x := newEngRig(t)
1336 x.w.PackWait = 300 * time.Millisecond
1337 x.note("edit:Swipe.swift|false|true")
1338 h := x.engHeader()
1339 pack, err := x.pri.e.packCommits(context.Background(), h)
1340 if err != nil {
1341 t.Fatal(err)
1342 }
1343 sum := sha256.Sum256(pack)
1344 half := len(pack) / 2
1345 other := h
1346 other.TaskID = "tkother"
1347 for i, c := range []struct {
1348 h wire.TransferHeader
1349 data []byte
1350 }{{h, pack[:half]}, {other, pack[half:]}} {
1351 if err := x.state.AcceptChunk(context.Background(), fmt.Sprintf("chunk-%d", i), wire.Blob{Transfer: c.h, Index: i, Total: 2, SHA256: hex.EncodeToString(sum[:]), Data: base64.StdEncoding.EncodeToString(c.data)}); err != nil {
1352 t.Fatal(err)
1353 }
1354 }
1355 before := x.steps()
1356 rep := x.exec(t, x.r)
1357 if rep.State != wire.StepFailed || rep.Reason != "candidate_unavailable" || x.steps() != before {
1358 t.Fatalf("report %+v", rep)
1359 }
1360}
1361