//go:build testbuild package thin import ( "bytes" "context" "crypto/sha256" "encoding/base64" "encoding/hex" "encoding/json" "errors" "fmt" "log/slog" "os" "os/exec" "path/filepath" "strings" "sync" "sync/atomic" "syscall" "testing" "time" "amadan.net/oficina/equipo/internal/fakeclaude" "amadan.net/oficina/equipo/internal/runner" "amadan.net/oficina/equipo/internal/runner/mac" "amadan.net/oficina/equipo/internal/runner/provider" "amadan.net/oficina/equipo/internal/wire" "github.com/spf13/viper" gitleaksconfig "github.com/zricethezav/gitleaks/v8/config" ) // Engineering on a Mac worker (Mac runners slice F, task 12) on Linux: // the darwin launch of the pinned stand-in (darwinRig: package mac's // executor and turns, the fake CLI, no sandbox), connections pasted // through the worker's own connector, and a primary (relayRig) whose // remote holds the base, which packs the inbound commits as the instance // asks and publishes the worker's candidate from its upload. // engBearer is the rig's runner credential: its URL base64 differs from // its standard base64 (it has '-' or '_'). const engBearer = "rnr~bearer>?>?~~0123456789abcdefghij" type engRig struct { *darwinRig pri *relayRig w *Worker relay *Relay r stepRow // tokens are the connections' tokens, in the order they were pasted, // and homes their dedicated homes. tokens, homes []string mu sync.Mutex said []wire.StepReport opened int // noUpload: the instance does not ask for the upload (yet). noUpload bool } func newEngRig(t *testing.T, emails ...string) *engRig { return newEngRigWith(t, nil, emails...) } // newEngRigWith is the rig whose base also holds the files before. func newEngRigWith(t *testing.T, before map[string]string, emails ...string) *engRig { t.Helper() asLaunch(t, true) if len(emails) == 0 { emails = []string{"a@example.com"} } d := newDarwinRig(t) c := d.connector() x := &engRig{darwinRig: d} for i, email := range emails { token := fakeclaude.Token(email) id := fmt.Sprintf("c%d", i+1) home, _ := d.paste(c, id, token) d.healthy(id, home, token, email) x.tokens = append(x.tokens, token) x.homes = append(x.homes, home) } x.pri = newRelayRigFiles(t, before, nil, nil) x.pri.e.Owners = []string{connPerson} // The pinned gitleaks beside the runner binary, as on a Mac. scanner := filepath.Join(filepath.Dir(previewScannerFixture(t)), "gitleaks") if err := os.Link(scanner, filepath.Join(d.dir, "bin", "gitleaks")); err != nil { raw, rerr := os.ReadFile(scanner) if rerr != nil || os.WriteFile(filepath.Join(d.dir, "bin", "gitleaks"), raw, 0o700) != nil { t.Fatal(err) } } e := &Engineer{O: d.opts, Conns: d.conns, Owners: []string{connPerson}, Spoken: func() int { return wire.ProtocolMacEngineering }, MaxStep: time.Minute} e.O.Runner.GitPath = "/usr/bin/git" e.O.SessionRoot = d.m.paths.SessionRoot e.O.Logger = slog.New(slog.NewTextHandler(&d.logs, nil)) x.w = &Worker{State: d.state, Engine: e, Gate: &stubGate{}, PackWait: 5 * time.Second, StepRoot: filepath.Join(d.cfg.ScratchRoot, "worker-steps"), Eng: &WorkerEngineering{Creds: d.m, Status: func(context.Context) *wire.EngineeringStatus { return &wire.EngineeringStatus{State: wire.EngineeringReady} }, Xcode: func() bool { return false }, Secrets: func(context.Context) ([]string, error) { return workerSecrets(d.cfg, engBearer) }, Leaks: e.workerLeaks}} x.relay = &Relay{State: d.state, Engine: e, Worker: x.w} x.r = x.dispatch("s1", x.pri.base, "Swipe back") return x } // dispatch is a first Engineering attempt of step on base. func (x *engRig) dispatch(step, base, title string) stepRow { 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}} return stepRow{DispatchCommand: d, Base: base} } func (x *engRig) note(n string) { x.w.Engine.Note = "\n" + n + "\n" } // steps counts the CLI's step launches so far (its auth status reads // and checks are not steps). func (x *engRig) steps() int { n := 0 for _, l := range x.launches() { if strings.HasPrefix(l.argv, "-p ") && !strings.Contains(l.argv, "--tools ") { n++ } } return n } // inbound relays the attempt's commits from the primary as the // instance's Engineering transfer does: the primary packs the header's // commits and the worker receives the chunk. func (x *engRig) inbound(t *testing.T) wire.TransferHeader { t.Helper() 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} if x.r.Rebase { h.OldBaseSHA, h.CandidateSHA = x.r.FromBase, x.r.CandidateSHA } pack, err := x.pri.e.packCommits(context.Background(), h) if err != nil { t.Fatal(err) } sum := sha256.Sum256(pack) 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 { t.Fatal(err) } return h } // run accepts the dispatch, relays its commits and runs the attempt; // its final report is queued as the step engine queues it. func (x *engRig) run(t *testing.T) wire.StepReport { t.Helper() if err := x.state.AcceptDispatch(context.Background(), "d-"+x.r.key(), x.r.DispatchCommand); err != nil { t.Fatal(err) } x.inbound(t) rep := x.exec(t, x.r) if wire.StepTerminal(rep.State) { if err := x.state.ReportStep(context.Background(), x.r, rep); err != nil { t.Fatal(err) } } return rep } // exec runs r; a committed report makes the instance open the outbound // transfer: send_pack to the worker. func (x *engRig) exec(t *testing.T, r stepRow) wire.StepReport { t.Helper() return x.w.Exec(context.Background(), r, func(p wire.StepReport) { x.mu.Lock() x.said = append(x.said, p) x.mu.Unlock() if p.Phase == wire.OutcomeCommitted && p.CandidateSHA != "" && !x.noUpload { x.sendPack(t, p) } }) } // sendPack is the instance's send_pack for an outbound transfer of p's // candidate; it returns the transfer's id. func (x *engRig) sendPack(t *testing.T, p wire.StepReport) string { x.mu.Lock() x.opened++ id := fmt.Sprintf("out-%s-%d", p.StepID, x.opened) x.mu.Unlock() 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} if err := x.state.AcceptUpload(context.Background(), "sp-"+id, wire.SendPackCommand{Transfer: h, Have: []string{}}); err != nil { t.Error(err) } return id } // committed is the newest committed report ("" candidate: none). func (x *engRig) committed() wire.StepReport { x.mu.Lock() defer x.mu.Unlock() for i := len(x.said) - 1; i >= 0; i-- { if p := x.said[i]; p.Phase == wire.OutcomeCommitted && p.CandidateSHA != "" { return p } } return wire.StepReport{} } // outbox is every frame the worker has queued, as JSON. func (x *engRig) outbox(t *testing.T) []wire.Frame { t.Helper() frames, _, err := x.state.Unacked(context.Background(), 0) if err != nil { t.Fatal(err) } return frames } // uploaded runs the worker's relay and returns the transfer's chunks. func (x *engRig) uploaded(t *testing.T, id string) []wire.Blob { t.Helper() x.relay.Once(context.Background()) var out []wire.Blob for _, f := range x.outbox(t) { if f.Type != wire.FrameBlob { continue } var b wire.Blob if json.Unmarshal(f.Data, &b) == nil && b.Transfer.ID == id { out = append(out, b) } } return out } // publish gives the uploaded chunks to the primary, which publishes the // candidate as it would for the instance's publish command. func (x *engRig) publish(t *testing.T, blobs []wire.Blob, cand string) wire.PublishedReport { t.Helper() if len(blobs) == 0 { t.Fatal("nothing was uploaded") } ctx := context.Background() h := blobs[0].Transfer for i, b := range blobs { if err := x.pri.e.O.State.AcceptChunk(ctx, fmt.Sprintf("pc-%s-%d", h.ID, i), b); err != nil { t.Fatal(err) } } pub := "pub-" + h.ID 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 { t.Fatal(err) } x.pri.relay.Once(ctx) for _, p := range x.pri.reports(t) { if p.Publication == pub { return p } } t.Fatal("no published report") return wire.PublishedReport{} } // round runs an attempt to its publication. func (x *engRig) round(t *testing.T) wire.StepReport { t.Helper() rep := x.run(t) if rep.State != wire.StepDone || rep.Pushed || rep.CandidateSHA == "" { t.Fatalf("round %s: %+v", x.r.StepID, rep) } c := x.committed() if pub := x.publish(t, x.uploaded(t, fmt.Sprintf("out-%s-%d", c.StepID, x.opened)), rep.CandidateSHA); !pub.Pushed { t.Fatalf("round %s not published: %+v", x.r.StepID, pub) } return rep } // store runs git in the worker's store. func (x *engRig) store(t *testing.T, args ...string) (string, error) { t.Helper() out, err := exec.Command("git", append([]string{"--git-dir=" + x.w.objects(x.r.Repo)}, args...)...).CombinedOutput() return strings.TrimSpace(string(out)), err } // remote runs git in the primary's hub remote. func (x *engRig) remote(t *testing.T, args ...string) string { t.Helper() out, err := exec.Command("git", append([]string{"--git-dir=" + x.pri.f.dir}, args...)...).CombinedOutput() if err != nil { t.Fatalf("git %v: %v %s", args, err, out) } return strings.TrimSpace(string(out)) } // moveMain moves the remote's default branch on with one commit that // writes file; it returns the new tip. func (x *engRig) moveMain(t *testing.T, file, text string) string { t.Helper() work := filepath.Join(t.TempDir(), "mover") gitOut(t, filepath.Dir(work), "clone", "-q", "-b", "main", x.pri.f.dir, work) os.WriteFile(filepath.Join(work, file), []byte(text), 0644) gitOut(t, work, "add", "-A") gitOut(t, work, "commit", "-q", "-m", "main moves") gitOut(t, work, "push", "-q", "origin", "main") return gitOut(t, work, "rev-parse", "HEAD") } // clean fails if any frame the worker queued, its log, or a step log it // keeps on disk (/steps) holds one of words (raw, or in base64). func (x *engRig) clean(t *testing.T, words ...string) { t.Helper() var all bytes.Buffer for _, f := range x.outbox(t) { all.Write(f.Data) } all.WriteString(x.logs.String()) _ = filepath.WalkDir(x.w.Engine.root(), func(path string, d os.DirEntry, err error) error { if err == nil && !d.IsDir() { raw, _ := os.ReadFile(path) all.Write(raw) } return nil }) for _, w := range words { for _, form := range []string{w, base64.StdEncoding.EncodeToString([]byte(w))} { if strings.Contains(all.String(), form) { t.Fatalf("%q left the worker (or is in its log)", form) } } } } // An attempt runs to done, not pushed: the committed report names the // candidate and its outcome, the worker uploads its thin pack, and the // primary publishes exactly that commit, Equipo's, on the base. func TestWorkerEngineeringCommitsAndUploads(t *testing.T) { x := newEngRig(t) x.note("edit:Swipe.swift|false|true") before := x.steps() rep := x.run(t) if rep.State != wire.StepDone || rep.Pushed || !rep.Termination || rep.Reason != "" || rep.BaseSHA != x.pri.base || rep.CandidateSHA == "" || !rep.Apple || rep.Account == "" { t.Fatalf("report %+v\n%s", rep, x.logs.String()) } cand := rep.CandidateSHA c := x.committed() if c.CandidateSHA != cand || c.OutcomePhase != wire.OutcomeCommitted || c.State != "" && c.State != wire.StepRunning { t.Fatalf("committed report %+v", c) } if x.steps() != before+1 { t.Fatalf("%d launches", x.steps()-before) } pub := x.publish(t, x.uploaded(t, "out-s1-1"), cand) if !pub.Pushed || x.pri.head(t) != cand { t.Fatalf("published %+v head %s", pub, x.pri.head(t)) } if parents := x.remote(t, "rev-list", "--parents", "-n", "1", cand); parents != cand+" "+x.pri.base { t.Fatalf("parents %q", parents) } if who := x.remote(t, "log", "-1", "--format=%an <%ae>", cand); who != commitName+" <"+commitEmail+">" { t.Fatalf("made by %q", who) } if body := x.remote(t, "show", cand+":Swipe.swift"); body != "let back = true" { t.Fatalf("change %q", body) } // Retained: the store's ref pins the candidate, whole. if got, err := x.store(t, "rev-parse", "--verify", candidateRef(x.r)); err != nil || got != cand { t.Fatalf("candidate ref %q %v", got, err) } // The kept session, for fix rounds and questions. k, found, err := x.state.keptCommit(context.Background(), "tk1", connPerson, wire.SpecialistEngineering, cand) if err != nil || !found || k.Attempt != 1 { t.Fatalf("kept %+v %v %v", k, found, err) } if _, err := os.Stat(keptTranscript(k.Dir, k.SessionID)); err != nil { t.Fatal(err) } if _, err := os.Stat(filepath.Join(x.w.stepsDir(), stepKey(x.r))); !os.IsNotExist(err) { t.Fatalf("the attempt's directory stayed: %v", err) } if !x.turnFree() { t.Fatal("the attempt kept the Mac's turn") } x.clean(t, x.tokens[0], engBearer) } // Each guard refuses before anything runs: no launch, no store, the // turn free. func TestWorkerEngineeringRefusesGuards(t *testing.T) { for name, c := range map[string]struct { change func(*engRig) reason string }{ "not an owner": {func(x *engRig) { x.r.Person = "q@example.com" }, "policy_rejected"}, "not a hub repository": {func(x *engRig) { x.r.Repo = "github.com/oficina/sample" }, "policy_rejected"}, "not a task branch": {func(x *engRig) { x.r.Branch = "main" }, "policy_rejected"}, "no base": {func(x *engRig) { x.r.BaseSHA = "" }, "policy_rejected"}, "a rebase without commits": {func(x *engRig) { x.r.Rebase = true }, "policy_rejected"}, "a republish": {func(x *engRig) { x.r.Republish, x.r.FromAttempt, x.r.CandidateSHA = true, 1, x.pri.commit }, "policy_rejected"}, "a task id no ref holds": {func(x *engRig) { x.r.TaskID = "tk1/../x" }, "policy_rejected"}, "unknown Xcode access": {func(x *engRig) { x.r.XcodeAccess = "full" }, "policy_rejected"}, "below protocol 37": {func(x *engRig) { x.w.Engine.Spoken = func() int { return wire.ProtocolMacEngineering - 1 } }, wire.ReasonEngineeringUnavailable}, "status not ready": {func(x *engRig) { x.w.Eng.Status = func(context.Context) *wire.EngineeringStatus { return &wire.EngineeringStatus{State: wire.EngineeringNoConnection} } }, wire.ReasonEngineeringUnavailable}, "status unknown": {func(x *engRig) { x.w.Eng.Status = func(context.Context) *wire.EngineeringStatus { return nil } }, wire.ReasonEngineeringUnavailable}, "Xcode access not proven": {func(x *engRig) { x.r.XcodeAccess = wire.XcodeAccessSandboxed }, wire.ReasonEngineeringUnavailable}, "no Mac Engineering": {func(x *engRig) { x.w.Eng = nil }, wire.ReasonEngineeringUnavailable}, "secrets unreadable": {func(x *engRig) { x.w.Eng.Secrets = func(context.Context) ([]string, error) { return nil, os.ErrPermission } }, wire.ReasonEngineeringUnavailable}, } { t.Run(name, func(t *testing.T) { x := newEngRig(t) x.note("edit:Swipe.swift|false|true") before := len(x.launches()) x.inbound(t) c.change(x) rep := x.exec(t, x.r) if rep.State != wire.StepFailed || rep.Reason != c.reason || !rep.Termination || rep.CandidateSHA != "" { t.Fatalf("report %+v", rep) } if n := len(x.launches()) - before; n != 0 { t.Fatalf("%d launches", n) } if _, err := os.Stat(x.w.objects("amadan.net/oficina/sample")); !os.IsNotExist(err) { t.Fatalf("the store was made: %v", err) } if !x.turnFree() { t.Fatal("the turn was kept") } }) } } // One store across rounds: after two fix rounds and a rebase, git log // and rev-list in the store stop at the boundaries the packs named, and // the thin pack of the newest candidate builds. func TestWorkerStoreShallowBoundaries(t *testing.T) { x := newEngRig(t) base0 := x.pri.base // walk is rev-list of the round's candidate ref in the store: it must // succeed and stop at the round's base, the boundary its pack named. walk := func(want ...string) { t.Helper() got, err := x.store(t, "rev-list", candidateRef(x.r)) if err != nil || got != strings.Join(want, "\n") { t.Fatalf("rev-list of %s: %q %v, want %v", x.r.StepID, got, err, want) } } x.note("edit:Swipe.swift|false|true") c1 := x.round(t).CandidateSHA walk(c1, base0) fix := func(step, base, edit string) string { x.r = x.dispatch(step, base, "Swipe back") x.r.Round, x.r.Feedback = 1, "CI: the swipe test failed." x.note(edit) c := x.round(t).CandidateSHA walk(c, base) return c } c2 := fix("s2", c1, "create:Back.swift|let back2 = 1") c3 := fix("s3", c2, "create:Back3.swift|let back3 = 1") tip := x.moveMain(t, "Main.swift", "let main = 1\n") x.r = x.dispatch("s4", tip, "Swipe back") x.r.Rebase, x.r.FromBase, x.r.CandidateSHA = true, base0, c3 x.note("") c4 := x.round(t).CandidateSHA log, err := x.store(t, "log", "--format=%H", candidateRef(x.r)) if err != nil || log != c4+"\n"+tip { t.Fatalf("log of the rebased candidate: %q %v", log, err) } for _, args := range [][]string{{"log", "--all", "--format=%H"}, {"rev-list", "--all", "--objects"}} { if out, err := x.store(t, args...); err != nil { t.Fatalf("%v: %v %s", args, err, out) } } pack := exec.Command("git", "--git-dir="+x.w.objects(x.r.Repo), "pack-objects", "--revs", "--thin", "--stdout", "-q") pack.Stdin = strings.NewReader(c4 + "\n^" + tip + "\n") if out, err := pack.Output(); err != nil || len(out) == 0 { t.Fatalf("thin pack: %v", err) } } // A rebase round on the worker: the three commits relayed, the change // merged onto the new tip with the explicit merge base, the conflict // resolved, and the rebased commit published on the new tip. func TestWorkerEngineeringRebaseRound(t *testing.T) { x := newEngRig(t) base0 := x.pri.base x.note("edit:Swipe.swift|false|true") c1 := x.round(t).CandidateSHA tip := x.moveMain(t, "Swipe.swift", "let back = maybe\n") x.r = x.dispatch("s2", tip, "Swipe back") x.r.Rebase, x.r.FromBase, x.r.CandidateSHA = true, base0, c1 x.note("") c2 := x.round(t).CandidateSHA if parents := x.remote(t, "rev-list", "--parents", "-n", "1", c2); parents != c2+" "+tip { t.Fatalf("parents %q", parents) } if body := x.remote(t, "show", c2+":Swipe.swift"); body != "let back = true" { t.Fatalf("resolved %q", body) } } // A fix round resumes the session that made the commit it starts from. func TestWorkerEngineeringFixRoundResumes(t *testing.T) { x := newEngRig(t) x.note("edit:Swipe.swift|false|true") c1 := x.round(t).CandidateSHA k, found, err := x.state.keptCommit(context.Background(), "tk1", connPerson, wire.SpecialistEngineering, c1) if err != nil || !found { t.Fatalf("no kept session: %v", err) } x.r = x.dispatch("s2", c1, "Swipe back") x.r.Round, x.r.Feedback = 1, "CI: the swipe test failed." x.note("create:Fix.swift|let fixed = true") rep := x.round(t) resumed := false for _, l := range x.launches() { if strings.Contains(l.argv, "--resume "+k.SessionID) { resumed = true } } if !resumed || !strings.Contains(rep.Summary, "(resumed session)") { t.Fatalf("not resumed (session %s): %+v", k.SessionID, rep) } if body, err := x.store(t, "show", rep.CandidateSHA+":Fix.swift"); err != nil || body != "let fixed = true" { t.Fatalf("the round's change %q %v", body, err) } } // The object scan: every form of a known secret, anywhere in the new // objects, refuses the step with nothing uploaded and nothing named; so // does gitleaks finding a key, the scanner failing, or an object past the // bound. A known secret in the CLI's own words is redacted. func TestWorkerObjectScan(t *testing.T) { token := fakeclaude.Token("a@example.com") binary := append(append([]byte{0, 1, 0xff, 0xfe}, []byte(base64.StdEncoding.EncodeToString([]byte(token)))...), 0, 7) urlForm := base64.URLEncoding.EncodeToString([]byte(engBearer)) if !strings.ContainsAny(urlForm, "-_") { t.Fatalf("the bearer's URL form %q is its standard form", urlForm) } for name, c := range map[string]struct { note string names []string before func(*testing.T, *engRig) // base: files the base already holds; kind: the diagnostic's kind. base map[string]string kind string }{ // Paths gitleaks' defaults would skip are scanned on a worker. "gitleaks under node_modules": {note: "create:node_modules/key.txt|token = \"ghp_" + "R4nd0mT0k3nW1thH1ghEntr0pyXyZ987654321\"", names: []string{"node_modules/key.txt"}, kind: "gitleaks"}, "gitleaks in gitleaks.toml": {note: "create:gitleaks.toml|token = \"ghp_" + "R4nd0mT0k3nW1thH1ghEntr0pyXyZ987654321\"", names: []string{"gitleaks.toml"}, kind: "gitleaks"}, "gitleaks in a .bin file": {note: "create:firmware.bin|token = \"ghp_" + "R4nd0mT0k3nW1thH1ghEntr0pyXyZ987654321\"", names: []string{"firmware.bin"}, kind: "gitleaks"}, "gitleaks by file name": {note: "create:nuget.config|", names: []string{"nuget.config"}, kind: "gitleaks"}, "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"}, "raw in a text file": {note: "create:notes.txt|key " + token, names: []string{"notes.txt"}}, "base64 in a binary file": {note: "bytes:blob.bin|" + base64.StdEncoding.EncodeToString(binary), names: []string{"blob.bin"}}, "in a file name": {note: "create:" + token + ".txt|hello"}, "in a symlink target": {note: "symlink:planted-link|/tmp/" + token, names: []string{"planted-link"}}, "hex-encoded": {note: "create:hex.txt|" + hex.EncodeToString([]byte(token)), names: []string{"hex.txt"}}, "the runner credential, URL": {note: "create:cred.txt|" + urlForm, names: []string{"cred.txt"}}, "gitleaks finds a key": {note: "create:keys.txt|token = \"ghp_" + "R4nd0mT0k3nW1thH1ghEntr0pyXyZ987654321\"", names: []string{"keys.txt"}}, "the scanner fails": {note: "edit:Swipe.swift|false|true", before: func(t *testing.T, x *engRig) { script := filepath.Join(x.dir, "bin", "gitleaks") os.Remove(script) body := []byte("#!/bin/sh\nexit 2\n") if err := os.WriteFile(script, body, 0o700); err != nil { t.Fatal(err) } sum := sha256.Sum256(body) old := previewScannerTool previewScannerTool = func(c runner.Config) (string, string) { return script, hex.EncodeToString(sum[:]) } t.Cleanup(func() { previewScannerTool = old }) }}, "an object past the bound": {note: "edit:Swipe.swift|false|true", kind: "too_large", before: func(t *testing.T, x *engRig) { old := workerScanBound workerScanBound = 64 t.Cleanup(func() { workerScanBound = old }) }}, } { t.Run(name, func(t *testing.T) { x := newEngRigWith(t, c.base) if c.before != nil { c.before(t, x) } x.note(c.note) rep := x.run(t) if rep.State != wire.StepFailed || rep.Reason != wire.ReasonSecretInCandidate || !rep.Termination || rep.CandidateSHA != "" || rep.Summary != "" || rep.Headline != "" || rep.LogTail != "" { t.Fatalf("report %+v", rep) } if c := x.committed(); c.CandidateSHA != "" { t.Fatalf("committed %+v", c) } for _, f := range x.outbox(t) { if f.Type == wire.FrameBlob { t.Fatal("a pack was queued") } } if refs, _ := x.store(t, "for-each-ref", "refs/equipo/"); refs != "" { t.Fatalf("the refused candidate is pinned: %s", refs) } x.clean(t, append([]string{token, engBearer, hex.EncodeToString([]byte(token))}, c.names...)...) if !strings.Contains(x.logs.String(), "secret in candidate") || c.kind != "" && !strings.Contains(x.logs.String(), "kind="+c.kind) { t.Fatalf("no diagnostic (kind %q): %s", c.kind, x.logs.String()) } // The step log, which names files, is gone; so is the session. if _, err := os.Stat(filepath.Join(x.w.Engine.root(), stepKey(x.r), "log.jsonl")); !os.IsNotExist(err) { t.Fatalf("the refused attempt's step log stayed: %v", err) } if n := x.keptRows(t); n != 0 { t.Fatalf("%d kept sessions of a refused attempt", n) } }) } t.Run("in the CLI's summary", func(t *testing.T) { x := newEngRig(t) // The token, and what no generic pattern takes for a secret: the // runner credential and the token's hex. x.note("say:my key is " + token + " and " + engBearer + " and " + hex.EncodeToString([]byte(token))) rep := x.run(t) if rep.State != wire.StepFailed || rep.Reason != "no_changes" || !strings.Contains(rep.Summary, "***") { t.Fatalf("report %+v", rep) } x.clean(t, token, engBearer, hex.EncodeToString([]byte(token))) }) // Whole-branch fix 3, #4: a known secret the CLI writes into what // becomes the commit message is redacted before the commit is made, // so the candidate goes with "***" in its message. t.Run("in the commit message", func(t *testing.T) { x := newEngRig(t) x.note("edit:Swipe.swift|false|true\nsay:" + token) rep := x.run(t) if rep.State != wire.StepDone || rep.CandidateSHA == "" { t.Fatalf("report %+v", rep) } msg, err := x.store(t, "log", "-1", "--format=%B", rep.CandidateSHA) if err != nil || strings.Contains(msg, token) || !strings.Contains(msg, "***") { t.Fatalf("message %q %v", msg, err) } }) } // The candidate is retained in the store: with the attempt's directory // gone and the runner started again, the upload is answered, a second // send_pack (Retry after the primary was replaced) is answered from the // store too, and the candidate is there to be read. func TestWorkerCandidateRetained(t *testing.T) { x := newEngRig(t) x.noUpload = true x.note("edit:Swipe.swift|false|true") rep := x.run(t) if rep.State != wire.StepDone || rep.CandidateSHA == "" { t.Fatalf("report %+v", rep) } cand := rep.CandidateSHA if _, err := os.Stat(filepath.Join(x.w.stepsDir(), stepKey(x.r))); !os.IsNotExist(err) { t.Fatal("the attempt's directory stayed") } // The runner starts again: nothing but its state and its store. first := x.sendPack(t, x.committed()) e := &Engineer{O: x.w.Engine.O} x.w = &Worker{State: x.state, Engine: e, StepRoot: x.w.StepRoot} x.relay = &Relay{State: x.state, Engine: e, Worker: x.w} if pub := x.publish(t, x.uploaded(t, first), cand); !pub.Pushed || x.pri.head(t) != cand { t.Fatalf("published after a restart: %+v", pub) } again := x.sendPack(t, x.committed()) if pub := x.publish(t, x.uploaded(t, again), cand); !pub.Pushed { t.Fatalf("published again: %+v", pub) } if body, err := x.store(t, "show", candidateRef(x.r)+":Swipe.swift"); err != nil || body != "let back = true" { t.Fatalf("the candidate from the store: %q %v", body, err) } // Another candidate, or another base, is refused. wrong := x.committed() wrong.CandidateSHA = x.pri.commit if blobs := x.uploaded(t, x.sendPack(t, wrong)); len(blobs) != 0 { t.Fatal("a candidate the attempt did not make was uploaded") } wrong = x.committed() wrong.BaseSHA = cand if blobs := x.uploaded(t, x.sendPack(t, wrong)); len(blobs) != 0 { t.Fatal("a pack on another base was uploaded") } // A ref that no longer pins the candidate: nothing goes. if _, err := x.store(t, "update-ref", candidateRef(x.r), x.pri.base); err != nil { t.Fatal(err) } if blobs := x.uploaded(t, x.sendPack(t, x.committed())); len(blobs) != 0 { t.Fatal("uploaded what its ref no longer pins") } if _, err := x.store(t, "update-ref", candidateRef(x.r), cand); err != nil { t.Fatal(err) } // A retention record that cannot be read: nothing goes. if _, err := x.state.db.Exec("ALTER TABLE candidates RENAME TO candidates_gone"); err != nil { t.Fatal(err) } if blobs := x.uploaded(t, x.sendPack(t, x.committed())); len(blobs) != 0 { t.Fatal("uploaded without its retention record") } } // forget_task: with no KeepUntil the candidate's ref and the kept // session go at once; with a later one they stay until it passes. func TestWorkerForgetTask(t *testing.T) { for _, keep := range []bool{false, true} { t.Run(fmt.Sprintf("keep=%v", keep), func(t *testing.T) { x := newEngRig(t) x.note("edit:Swipe.swift|false|true") cand := x.round(t).CandidateSHA ctx := context.Background() k, _, _ := x.state.keptCommit(ctx, "tk1", connPerson, wire.SpecialistEngineering, cand) cmd := wire.ForgetTaskCommand{Person: connPerson, TaskID: "tk1"} if keep { until := time.Now().Add(time.Second) cmd.KeepUntil = &until } dirs, err := x.state.ForgetTask(ctx, "forget-1", cmd) if err != nil { t.Fatal(err) } x.w.forget(ctx, dirs) gone := func() bool { _, refErr := x.store(t, "rev-parse", "--verify", candidateRef(x.r)) _, dirErr := os.Stat(k.Dir) _, found, _ := x.state.keptCommit(ctx, "tk1", connPerson, wire.SpecialistEngineering, cand) return refErr != nil && os.IsNotExist(dirErr) && !found } if !keep { if !gone() { t.Fatal("not forgotten at once") } if blobs := x.uploaded(t, x.sendPack(t, x.committed())); len(blobs) != 0 { t.Fatal("a forgotten candidate was uploaded") } return } if gone() { t.Fatal("forgotten before its keep") } // Past its keep with nothing swept yet (a runner that was down at // the deadline): the ref is still there, and nothing goes. if _, err := x.state.db.Exec("UPDATE candidates SET expires_at=?", stamp(time.Now().Add(-time.Second))); err != nil { t.Fatal(err) } if blobs := x.uploaded(t, x.sendPack(t, x.committed())); len(blobs) != 0 { t.Fatal("a candidate past its keep, not yet swept, was uploaded") } if _, err := x.store(t, "rev-parse", "--verify", candidateRef(x.r)); err != nil { t.Fatal("the ref went before the sweep: the case shows nothing") } time.Sleep(1100 * time.Millisecond) // Past its keep, never uploaded again, sweep or not. if blobs := x.uploaded(t, x.sendPack(t, x.committed())); len(blobs) != 0 { t.Fatal("a candidate past its keep was uploaded") } // The cleanup was scheduled at the deadline: nobody sweeps here. deadline := time.Now().Add(5 * time.Second) for !gone() && time.Now().Before(deadline) { time.Sleep(100 * time.Millisecond) } if !gone() { t.Fatal("kept past its keep") } }) } } // A restart after committed resumes: the CLI never runs again for the // attempt, the committed report is said again, and the upload answered. func TestWorkerEngineeringRestartAfterCommit(t *testing.T) { x := newEngRig(t) x.noUpload = true x.note("edit:Swipe.swift|false|true") rep := x.run(t) cand := rep.CandidateSHA ctx := context.Background() // The runner stopped before its final report was kept. if _, err := x.state.db.Exec("UPDATE steps SET state='running' WHERE step_id=?", x.r.StepID); err != nil { t.Fatal(err) } if err := x.state.RecoverSteps(ctx, func(context.Context, string) bool { return true }); err != nil { t.Fatal(err) } r, ok, err := x.state.nextStep(ctx) if err != nil || !ok || !committed(r.Phase) { t.Fatalf("after the restart: %+v %v %v", r, ok, err) } launched := x.steps() x.mu.Lock() x.said = nil x.mu.Unlock() x.noUpload = false again := x.exec(t, r) if again.State != wire.StepDone || again.CandidateSHA != cand || again.Pushed || !again.Termination || x.steps() != launched { t.Fatalf("resumed %+v, %d new launches", again, x.steps()-launched) } if c := x.committed(); c.CandidateSHA != cand || c.OutcomePhase != wire.OutcomeCommitted { t.Fatalf("committed again %+v", c) } if again.SessionID == "" || again.SessionID != rep.SessionID || !again.Askable || again.Apple != rep.Apple || again.Summary != rep.Summary || again.Headline != rep.Headline { t.Fatalf("resumed without the attempt's report: %+v, was %+v", again, rep) } if pub := x.publish(t, x.uploaded(t, fmt.Sprintf("out-s1-%d", x.opened)), cand); !pub.Pushed { t.Fatalf("published %+v", pub) } } // A limit on the first connection fails over to the next, as a new // attempt from a fresh tree: what the refused attempt left is not in the // candidate. func TestWorkerEngineeringFailover(t *testing.T) { x := newEngRig(t, "a@example.com", "b@example.com") x.note("steplimit:a@example.com limitleave:Leftover.txt\nedit:Swipe.swift|false|true") rep := x.run(t) if rep.State != wire.StepDone || rep.Attempt != 2 || rep.Switched == nil || rep.CandidateSHA == "" { t.Fatalf("report %+v", rep) } cand := rep.CandidateSHA if _, err := x.store(t, "cat-file", "-e", cand+":Leftover.txt"); err == nil { t.Fatal("the refused attempt's tree was reused") } if body, err := x.store(t, "show", cand+":Swipe.swift"); err != nil || body != "let back = true" { t.Fatalf("change %q %v", body, err) } r2 := x.r r2.Attempt = 2 if got, err := x.store(t, "rev-parse", "--verify", candidateRef(r2)); err != nil || got != cand { t.Fatalf("ref %q %v", got, err) } } // The checks path is unchanged by Engineering's: a checks dispatch still // runs the gate on the relayed candidate, and a specialist a worker does // not take is still refused. func TestWorkerChecksUnchanged(t *testing.T) { x := newWorkerRig(t) x.chunk(t, "c1", x.header(), x.pack, 0, 1, "") if rep := x.run(); rep.State != wire.StepDone || rep.Checks != wire.ChecksPassed || len(x.gate.ran) != 1 { t.Fatalf("checks %+v", rep) } x.r.Specialist = wire.SpecialistReview if rep := x.run(); rep.State != wire.StepFailed || rep.Reason != "placement_refused" || len(x.gate.ran) != 1 { t.Fatalf("review %+v", rep) } } // The worker's prompt is the primary's, for the Mac: the worktree's real // path, no Linux toolchain, the Research findings quoted, and its kept // images on the main runner, never relayed. func TestWorkerEngineeringPromptForTheMac(t *testing.T) { x := newEngRig(t) findings, _ := json.Marshal(wire.ResearchFindings{Summary: "Swipes go back.", Facts: []wire.ResearchFact{}, Images: []string{"img1"}, Gaps: []string{}}) x.r.RunnerID = "rn-mac" 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}}} x.note("edit:Swipe.swift|false|true") rep := x.run(t) if rep.State != wire.StepDone { t.Fatalf("report %+v", rep) } k, _, _ := x.state.keptCommit(context.Background(), "tk1", connPerson, wire.SpecialistEngineering, rep.CandidateSHA) raw, err := os.ReadFile(keptTranscript(k.Dir, k.SessionID)) if err != nil { t.Fatal(err) } var prompt string for _, line := range strings.Split(string(raw), "\n") { var v struct{ Type, Text string } if json.Unmarshal([]byte(line), &v) == nil && v.Type == "user" { prompt = v.Text } } tree := filepath.Join(x.w.stepsDir(), stepKey(x.r), "tree") for _, want := range []string{"checked out in " + tree, "Swipes go back.", "they stay on the main runner"} { if !strings.Contains(prompt, want) { t.Errorf("the prompt lacks %q:\n%s", want, prompt) } } for _, never := range []string{"/workspace", "/opt/go", "/research/"} { if strings.Contains(prompt, never) { t.Errorf("the prompt names %q:\n%s", never, prompt) } } } // The inbound pack is checked before anything runs: chunks under another // header, and a pack that is not exactly the named commits, each whole. func TestWorkerEngineeringRefusesPacks(t *testing.T) { for name, feed := range map[string]func(*testing.T, *engRig){ "a checks header": func(t *testing.T, x *engRig) { 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} x.chunk(t, h, onePack(t, x.pri.seed, x.pri.base)) }, "an extra commit": func(t *testing.T, x *engRig) { objects, _ := exec.Command("git", "-C", x.pri.seed, "rev-list", "--objects", "--no-walk", x.pri.base, x.pri.commit).Output() packer := exec.Command("git", "-C", x.pri.seed, "pack-objects", "--stdout", "-q") packer.Stdin = bytes.NewReader(objects) pack, err := packer.Output() if err != nil { t.Fatal(err) } x.chunk(t, x.engHeader(), pack) }, "a commit without its tree": func(t *testing.T, x *engRig) { packer := exec.Command("git", "-C", x.pri.seed, "pack-objects", "--stdout", "-q") packer.Stdin = strings.NewReader(x.pri.base + "\n") pack, err := packer.Output() if err != nil { t.Fatal(err) } x.chunk(t, x.engHeader(), pack) }, } { t.Run(name, func(t *testing.T) { x := newEngRig(t) x.w.PackWait = 300 * time.Millisecond x.note("edit:Swipe.swift|false|true") before := x.steps() feed(t, x) rep := x.exec(t, x.r) if rep.State != wire.StepFailed || rep.Reason != "candidate_unavailable" || !rep.Termination || x.steps() != before { t.Fatalf("report %+v", rep) } }) } } func (x *engRig) engHeader() wire.TransferHeader { 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} } func (x *engRig) chunk(t *testing.T, h wire.TransferHeader, pack []byte) { t.Helper() sum := sha256.Sum256(pack) 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 { t.Fatal(err) } } // The Mac's guards are asked again before each launch, in the turn: a // runner tainted since the dispatch launches nothing. func TestWorkerEngineeringGatedPerLaunch(t *testing.T) { x := newEngRig(t) x.note("edit:Swipe.swift|false|true") before := x.steps() x.m.taint.Set() rep := x.run(t) if rep.State != wire.StepFailed || rep.Reason != wire.ReasonEngineeringUnavailable || !rep.Termination || x.steps() != before { t.Fatalf("report %+v, %d launches", rep, x.steps()-before) } if !x.turnFree() { t.Fatal("the turn was kept") } } // A worker's unfinished work is recorded in its outcome field, never in // the progress phase, and still goes out as unfinished work. func TestWorkerUnfinishedOutcomeField(t *testing.T) { x := newEngRig(t) ctx := context.Background() cand := strings.Repeat("2", 40) if err := x.state.AcceptDispatch(ctx, "d-u", x.r.DispatchCommand); err != nil { t.Fatal(err) } if err := x.state.setWorkerCommitted(ctx, x.r, x.pri.base, cand, wire.OutcomeUnfinished, wire.StepReport{}, false); err != nil { t.Fatal(err) } var phase string if err := x.state.db.QueryRow("SELECT phase FROM steps WHERE step_id=?", x.r.StepID).Scan(&phase); err != nil || phase != phaseCommitted { t.Fatalf("phase %q %v", phase, err) } rep := workerDone(wire.StepReport{TaskID: "tk1", StepID: x.r.StepID, Attempt: 1, CandidateSHA: cand, Findings: []wire.Finding{}}, wire.OutcomeUnfinished) if err := x.state.ReportStep(ctx, x.r, rep); err != nil { t.Fatal(err) } var sent wire.StepReport for _, f := range x.outbox(t) { if f.Type != wire.FrameStep { continue } out, err := x.state.unfinishedReport(ctx, f, wire.ProtocolMacEngineering, true) if err != nil { t.Fatal(err) } json.Unmarshal(out.Data, &sent) } if sent.State != wire.StepDone || sent.Reason != "step_timeout" || sent.Pushed || sent.OutcomePhase != wire.OutcomeUnfinished || sent.CandidateSHA != cand { t.Fatalf("sent %+v", sent) } } // A launch whose record cannot be written starts nothing, but the // attempt ends unproven (not terminated, no Retry), as a failover launch // after a lost evidence write must (mac.ErrRecord). func TestWorkerEngineeringLostRecordUnproven(t *testing.T) { x := newEngRig(t) x.note("edit:Swipe.swift|false|true") // The executor writes the marker's record again before the CLI // starts: that write fails. 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 { t.Fatal(err) } before := x.steps() rep := x.run(t) if rep.State != wire.StepFailed || rep.Reason != wire.ReasonEngineeringUnavailable || rep.Termination || x.steps() != before { t.Fatalf("report %+v, %d launches", rep, x.steps()-before) } } // keptRows counts the worker's kept sessions. func (x *engRig) keptRows(t *testing.T) int { t.Helper() var n int if err := x.state.db.QueryRow("SELECT count(*) FROM kept_sessions").Scan(&n); err != nil { t.Fatal(err) } return n } // authLaunches counts the CLI's auth status reads so far. func (x *engRig) authLaunches() int { n := 0 for _, l := range x.launches() { if strings.HasPrefix(l.argv, "auth status") { n++ } } return n } // Fix round 1, #1: the runtime copy's auth status can end unproven; the // attempt then ends unproven too, never terminated. func TestWorkerEngineeringPreflightUnproven(t *testing.T) { x := newEngRig(t) x.note("edit:Swipe.swift|false|true") // The next auth status leaves a child that outlives a short settle. if err := os.WriteFile(filepath.Join(x.dir, "linger"), []byte("auth"), 0o600); err != nil { t.Fatal(err) } x.m.exec.Settle = 300 * time.Millisecond before := x.steps() rep := x.run(t) if rep.State != wire.StepFailed || rep.Termination || x.steps() != before { t.Fatalf("report %+v, %d launches", rep, x.steps()-before) } if pid := waitPid(t, filepath.Join(x.dir, "linger.pid")); pid > 0 { _ = syscall.Kill(pid, syscall.SIGKILL) } } // Fix round 1, #1: an auth status that says sign in again fails over to // the next connection, as a refusal of the step's own run does. func TestWorkerEngineeringPreflightSignInFailsOver(t *testing.T) { x := newEngRig(t, "a@example.com", "b@example.com") x.note("edit:Swipe.swift|false|true") first := filepath.Base(x.homes[0]) x.w.Eng.refresh = func(ctx context.Context, b provider.Binding) (provider.Identity, error) { if filepath.Base(b.Home) == first || strings.Contains(b.Home, first) { return provider.Identity{}, provider.ErrLoginRequired } return x.m.authStatus(ctx, b) } rep := x.run(t) if rep.State != wire.StepDone || rep.Attempt != 2 || rep.Switched == nil || rep.CandidateSHA == "" { t.Fatalf("report %+v", rep) } } // Fix round 1, #4: readiness and the Xcode proof are asked again inside // the held turn: a proof lost while the attempt waited for the turn // launches nothing, not even the auth status. func TestWorkerEngineeringReadinessInTheTurn(t *testing.T) { for _, xcode := range []bool{false, true} { t.Run(fmt.Sprintf("xcode=%v", xcode), func(t *testing.T) { x := newEngRig(t) x.note("edit:Swipe.swift|false|true") var lost atomic.Bool x.w.Eng.Status = func(context.Context) *wire.EngineeringStatus { if !xcode && lost.Load() { return &wire.EngineeringStatus{State: wire.EngineeringProbesPending} } return &wire.EngineeringStatus{State: wire.EngineeringReady} } if xcode { x.r.XcodeAccess = wire.XcodeAccessSandboxed x.w.Eng.Xcode = func() bool { return !lost.Load() } } u, err := x.m.turns.Take(context.Background(), mac.OpProbe) if err != nil { t.Fatal(err) } if err := x.state.AcceptDispatch(context.Background(), "d-w", x.r.DispatchCommand); err != nil { t.Fatal(err) } x.inbound(t) auth, steps := x.authLaunches(), x.steps() done := make(chan wire.StepReport, 1) go func() { done <- x.exec(t, x.r) }() time.Sleep(500 * time.Millisecond) lost.Store(true) u.Give() rep := <-done if rep.State != wire.StepFailed || rep.Reason != wire.ReasonEngineeringUnavailable || x.authLaunches() != auth || x.steps() != steps { t.Fatalf("report %+v, %d auth, %d step launches", rep, x.authLaunches()-auth, x.steps()-steps) } }) } } // Fix round 1, #4: readiness lost while the runtime copy's auth status // ran, in the same turn, still launches no step. func TestWorkerEngineeringReadinessBeforeTheStep(t *testing.T) { x := newEngRig(t) x.note("edit:Swipe.swift|false|true") var lost atomic.Bool x.w.Eng.Status = func(context.Context) *wire.EngineeringStatus { if lost.Load() { return &wire.EngineeringStatus{State: wire.EngineeringSignedOut} } return &wire.EngineeringStatus{State: wire.EngineeringReady} } x.w.Eng.refresh = func(ctx context.Context, b provider.Binding) (provider.Identity, error) { id, err := x.m.authStatus(ctx, b) lost.Store(true) return id, err } before := x.steps() rep := x.run(t) if rep.State != wire.StepFailed || rep.Reason != wire.ReasonEngineeringUnavailable || x.steps() != before { t.Fatalf("report %+v, %d step launches", rep, x.steps()-before) } } // Fix round 1, #5: a crash on either side of the committed transition. // Before it, the attempt ends runner_restarted and nothing is uploaded; // after it, the restart reports what the attempt reported (session, // askable, Apple, words) and the kept session is bound to the candidate. func TestWorkerEngineeringCrashAroundCommitted(t *testing.T) { for _, point := range []string{"retained", "committed"} { t.Run(point, func(t *testing.T) { x := newEngRig(t) x.noUpload = true x.note("edit:Swipe.swift|false|true") old := workerFault workerFault = func(p string) bool { return p == point } t.Cleanup(func() { workerFault = old }) if err := x.state.AcceptDispatch(context.Background(), "d-c", x.r.DispatchCommand); err != nil { t.Fatal(err) } x.inbound(t) x.exec(t, x.r) workerFault = old ctx := context.Background() if err := x.state.RecoverSteps(ctx, func(context.Context, string) bool { return true }); err != nil { t.Fatal(err) } if point == "retained" { var state, reason string x.state.db.QueryRow("SELECT state, final_reason FROM steps WHERE step_id=?", x.r.StepID).Scan(&state, &reason) if reason != "runner_restarted" { t.Fatalf("after a crash before committed: %s %s", state, reason) } refs, _ := x.store(t, "for-each-ref", "--format=%(objectname)", "refs/equipo/") p := wire.StepReport{TaskID: "tk1", StepID: x.r.StepID, Attempt: 1, BaseSHA: x.pri.base, CandidateSHA: refs} if refs == "" || len(x.uploaded(t, x.sendPack(t, p))) != 0 { t.Fatalf("an uncommitted candidate (%q) was uploaded", refs) } return } r, ok, err := x.state.nextStep(ctx) if err != nil || !ok || !committed(r.Phase) { t.Fatalf("after the restart: %+v %v %v", r, ok, err) } rep := x.exec(t, r) if rep.State != wire.StepDone || rep.SessionID == "" || !rep.Askable || !rep.Apple || rep.Summary == "" || rep.Account == "" { t.Fatalf("recovered report %+v", rep) } if _, found, _ := x.state.keptCommit(ctx, "tk1", connPerson, wire.SpecialistEngineering, r.Candidate); !found { t.Fatal("the kept session is not bound to the candidate") } }) } } // Fix round 1, #3: finished attempts' step logs go with the sweep. func TestWorkerSweepRemovesStepLogs(t *testing.T) { x := newEngRig(t) x.note("edit:Swipe.swift|false|true") x.run(t) log := filepath.Join(x.w.Engine.root(), stepKey(x.r), "log.jsonl") if _, err := os.Stat(log); err != nil { t.Fatalf("no step log: %v", err) } if _, err := x.state.db.Exec("UPDATE steps SET state=? WHERE step_id=?", runDone, x.r.StepID); err != nil { t.Fatal(err) } x.w.sweep(context.Background()) if _, err := os.Stat(log); !os.IsNotExist(err) { t.Fatalf("the step log stayed: %v", err) } } // Fix round 1, #7: on a Mac gitleaks runs in the checks gate (srt with // the checks profile P2 proves); the gate's run is read the same way. // Here the gate has no srt (Linux), and the scanner is the pinned one. func TestGateLeaks(t *testing.T) { runnerPath := previewScannerFixture(t) binary, pin := previewScannerTool(runner.Config{Executable: runnerPath}) g := &mac.Gate{Env: []string{"PATH=/usr/bin:/bin", "LANG=C"}, ScratchHome: true, Lines: 10, Sandbox: wire.SandboxNone} for name, c := range map[string]struct { files map[string]string found bool }{ "clean": {map[string]string{"a.swift": "let a = 1\n"}, false}, "under node_modules": {map[string]string{"node_modules/k.txt": "token = \"ghp_" + "R4nd0mT0k3nW1thH1ghEntr0pyXyZ987654321\"\n"}, true}, "a key": {map[string]string{"keys.txt": "token = \"ghp_" + "R4nd0mT0k3nW1thH1ghEntr0pyXyZ987654321\"\n"}, true}, "by name": {map[string]string{"nuget.config": "\n"}, true}, } { t.Run(name, func(t *testing.T) { stage := filepath.Join(t.TempDir(), "scan", "files") for p, body := range c.files { os.MkdirAll(filepath.Dir(filepath.Join(stage, p)), 0o700) os.WriteFile(filepath.Join(stage, p), []byte(body), 0o600) } found, err := gateLeaks(context.Background(), g, binary, pin, stage, "scan-test", nil) if err != nil || found != c.found { t.Fatalf("found %v, %v", found, err) } }) } // Not the pinned scanner: it cannot tell. if _, err := gateLeaks(context.Background(), g, binary, strings.Repeat("0", 64), t.TempDir(), "scan-test", nil); err == nil { t.Fatal("an unpinned scanner was run") } } // Fix round 1, #7: a Mac whose checks gate is not the proven sandboxed // one cannot scan: the candidate does not leave. func TestMacLeaksNeedTheProvenGate(t *testing.T) { install := filepath.Dir(previewScannerFixture(t)) // Both gates can run the scanner here (no srt on Linux); only the one // P2's trusted verdict picks for checks may. sandboxed := &mac.Gate{Env: []string{"PATH=/usr/bin:/bin"}, ScratchHome: true, Lines: 10, Sandbox: wire.SandboxSeatbelt} bare := &mac.Gate{Env: []string{"PATH=/usr/bin:/bin"}, ScratchHome: true, Lines: 10, Sandbox: wire.SandboxNone} 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}} stage := filepath.Join(t.TempDir(), "scan", "files") os.MkdirAll(stage, 0o700) os.WriteFile(filepath.Join(stage, "a.swift"), []byte("let a = 1\n"), 0o600) if _, err := h.leaks(context.Background(), stage, "scan-test", nil); err == nil { t.Fatal("scanned without the proven gate") } } // Fix round 2, #1: the worker's trusted rules are gitleaks' defaults with // no path exclusion at all (global or per rule), its file-name rules // kept, and the runner's own rules added. func TestWorkerSecretRules(t *testing.T) { v := viper.New() v.SetConfigType("toml") if err := v.ReadConfig(strings.NewReader(workerSecretRules())); err != nil { t.Fatal(err) } var raw gitleaksconfig.ViperConfig if err := v.Unmarshal(&raw); err != nil { t.Fatal(err) } cfg, err := raw.Translate() if err != nil { t.Fatal(err) } for _, a := range cfg.Allowlists { if len(a.Paths) != 0 { t.Fatalf("a global path exclusion: %v", a.Paths) } } for id, r := range cfg.Rules { for _, a := range r.Allowlists { if len(a.Paths) != 0 { t.Fatalf("rule %s excludes paths: %v", id, a.Paths) } } } for _, id := range []string{"nuget-config-password", "pkcs12-file", "github-pat", "equipo-github-token", "equipo-private-key-header"} { if _, ok := cfg.Rules[id]; !ok { t.Errorf("rule %s missing", id) } } if r := cfg.Rules["nuget-config-password"]; r.Path == nil { t.Error("the nuget rule lost its file name") } } // Fix round 2, #2: the scanner's record cannot be written at its start: // the scan's end is unproven, never an ordinary scanner error. func TestGateLeaksRecordLost(t *testing.T) { runnerPath := previewScannerFixture(t) binary, pin := previewScannerTool(runner.Config{Executable: runnerPath}) g := &mac.Gate{Env: []string{"PATH=/usr/bin:/bin"}, ScratchHome: true, Lines: 10, Sandbox: wire.SandboxNone} stage := filepath.Join(t.TempDir(), "scan", "files") os.MkdirAll(stage, 0o700) os.WriteFile(filepath.Join(stage, "a.swift"), []byte("let a = 1\n"), 0o600) _, err := gateLeaks(context.Background(), g, binary, pin, stage, "scan-test", func(string) error { return errors.New("disk full") }) if !errors.Is(err, errScanUnproven) { t.Fatalf("a lost scanner record: %v", err) } } // Fix round 2, #2: in an attempt, the scanner's record write fails as it // starts: secret_in_candidate, unterminated, nothing uploaded. func TestWorkerEngineeringScannerRecordLost(t *testing.T) { x := newEngRig(t) x.note("edit:Swipe.swift|false|true") runnerPath := previewScannerFixture(t) binary, pin := previewScannerTool(runner.Config{Executable: runnerPath}) g := &mac.Gate{Env: []string{"PATH=/usr/bin:/bin"}, ScratchHome: true, Lines: 10, Sandbox: wire.SandboxSeatbelt} x.w.Eng.Leaks = func(ctx context.Context, stage, marker string, record func(string) error) (bool, error) { return gateLeaks(ctx, g, binary, pin, stage, marker, record) } stage := filepath.Join(x.w.stepsDir(), stepKey(x.r), "scan", "files") 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 { t.Fatal(err) } rep := x.run(t) if rep.State != wire.StepFailed || rep.Reason != wire.ReasonSecretInCandidate || rep.Termination || rep.CandidateSHA != "" { t.Fatalf("report %+v", rep) } if c := x.committed(); c.CandidateSHA != "" { t.Fatalf("committed %+v", c) } } // Fix round 2, #3: every chunk's header is compared (State.pack), the // later ones too. func TestWorkerEngineeringRefusesALaterChunk(t *testing.T) { x := newEngRig(t) x.w.PackWait = 300 * time.Millisecond x.note("edit:Swipe.swift|false|true") h := x.engHeader() pack, err := x.pri.e.packCommits(context.Background(), h) if err != nil { t.Fatal(err) } sum := sha256.Sum256(pack) half := len(pack) / 2 other := h other.TaskID = "tkother" for i, c := range []struct { h wire.TransferHeader data []byte }{{h, pack[:half]}, {other, pack[half:]}} { 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 { t.Fatal(err) } } before := x.steps() rep := x.exec(t, x.r) if rep.State != wire.StepFailed || rep.Reason != "candidate_unavailable" || x.steps() != before { t.Fatalf("report %+v", rep) } }