package thin import ( "bytes" "context" "encoding/base64" "encoding/json" "errors" "os" "os/exec" "path/filepath" "slices" "sort" "strings" "testing" "amadan.net/oficina/equipo/internal/wire" ) // Mac runners slice F, plan task 4: the primary's side of the base // exchange. It resolves a worker attempt's base (prepare_base, then a // durable base report), packs exactly the commits an Engineering header // names, and, once it has pushed a worker's candidate, sends the change // files and diffs bound to that publication. const sampleRepo = "amadan.net/oficina/sample" // bases are the base reports in the outbox, in order. func (r *relayRig) bases(t *testing.T) []wire.BaseReport { t.Helper() frames, _, err := r.e.O.State.Unacked(context.Background(), 0) if err != nil { t.Fatal(err) } var out []wire.BaseReport for _, f := range frames { if f.Type == wire.FrameBase { var b wire.BaseReport if err := json.Unmarshal(f.Data, &b); err != nil { t.Fatal(err) } out = append(out, b) } } return out } func (r *relayRig) prepare(t *testing.T, frame string, attempt int64) { t.Helper() if err := r.e.O.State.AcceptPrepareBase(context.Background(), frame, wire.PrepareBaseCommand{TaskID: "tk1", StepID: "s1", Attempt: attempt, Repo: sampleRepo}); err != nil { t.Fatal(err) } } // reopen is a restart: the same state directory opened again, a new // relay over it. func (r *relayRig) reopen(t *testing.T) { t.Helper() r.e.O.State.Close() s, err := OpenState(context.Background(), filepath.Join(r.root, "state")) if err != nil { t.Fatal(err) } t.Cleanup(func() { s.Close() }) r.e.O.State = s r.relay = &Relay{State: s, Engine: r.e} } // The primary fetches and reports the default branch's tip for the // attempt, once. The same attempt asked again (a restart, a resent // command) is answered with the same SHA even after the branch moved; a // new attempt gets the tip as it is now. func TestPrepareBaseResolvesAndIsIdempotent(t *testing.T) { r := newRelayRig(t) ctx := context.Background() r.prepare(t, "pb-1", 1) r.relay.Once(ctx) got := r.bases(t) if len(got) != 1 || got[0] != (wire.BaseReport{TaskID: "tk1", StepID: "s1", Attempt: 1, BaseSHA: r.base}) || !got[0].Valid() { t.Fatalf("base reports %+v, want %s", got, r.base) } // The default branch moves on. gitOut(t, r.seed, "push", "-q", r.remote, "main") r.reopen(t) r.relay.Once(ctx) if got := r.bases(t); len(got) != 1 { t.Fatalf("reported again after a restart: %+v", got) } // The same frame again does nothing; the same attempt asked again is // answered with the SHA it was given. r.prepare(t, "pb-1", 1) r.prepare(t, "pb-2", 1) r.relay.Once(ctx) got = r.bases(t) if len(got) != 2 || got[1].BaseSHA != r.base || got[1].Attempt != 1 { t.Fatalf("same attempt asked again: %+v", got) } r.prepare(t, "pb-3", 2) r.relay.Once(ctx) got = r.bases(t) if len(got) != 3 || got[2].Attempt != 2 || got[2].BaseSHA != r.commit { t.Fatalf("a new attempt: %+v, want %s", got, r.commit) } } // A repository with no commits has no base for a worker (it is never Mac // work): base_unavailable. So does a repository the primary does not // publish to (before git runs) and a rebase round whose commits the clone // does not have. func TestPrepareBaseRefusesUnborn(t *testing.T) { ctx := context.Background() t.Run("unborn", func(t *testing.T) { r := newRelayRig(t) empty := filepath.Join(r.root, "empty.git") gitOut(t, r.root, "init", "-q", "--bare", "-b", "main", empty) r.f.dir = empty r.prepare(t, "pb-1", 1) r.relay.Once(ctx) if got := r.bases(t); len(got) != 1 || got[0].Reason != wire.ReasonBaseUnavailable || got[0].BaseSHA != "" || !got[0].Valid() { t.Fatalf("unborn: %+v", got) } }) t.Run("not a hub repository", func(t *testing.T) { r := newRelayRig(t) r.e.O.Runner.GitPath, r.e.Clones.Git = "/nonexistent/git", "/nonexistent/git" if err := r.e.O.State.AcceptPrepareBase(ctx, "pb-1", wire.PrepareBaseCommand{TaskID: "tk1", StepID: "s1", Attempt: 1, Repo: "github.com/someone/else"}); err != nil { t.Fatal(err) } r.relay.Once(ctx) if got := r.bases(t); len(got) != 1 || got[0].Reason != wire.ReasonBaseUnavailable { t.Fatalf("not a hub repository: %+v", got) } }) t.Run("rebase commits missing", func(t *testing.T) { r := newRelayRig(t) if err := r.e.O.State.AcceptPrepareBase(ctx, "pb-1", wire.PrepareBaseCommand{TaskID: "tk1", StepID: "s1", Attempt: 1, Repo: sampleRepo, Rebase: true, FromBase: r.base, CandidateSHA: strings.Repeat("e", 40)}); err != nil { t.Fatal(err) } r.relay.Once(ctx) if got := r.bases(t); len(got) != 1 || got[0].Reason != wire.ReasonBaseUnavailable { t.Fatalf("rebase without its candidate: %+v", got) } }) } // packRig is a remote with history: main at c1 on c0, and a task branch // whose tip c2 sits on c0 (the old base of a rebase round onto c1). func packRig(t *testing.T) (r *relayRig, c0, c1, c2 string) { t.Helper() r = newRelayRig(t) work := filepath.Join(r.root, "history") gitOut(t, r.root, "init", "-q", "-b", "main", work) write := func(name, text string) { os.MkdirAll(filepath.Dir(filepath.Join(work, name)), 0755) os.WriteFile(filepath.Join(work, name), []byte(text), 0644) } write("README.md", "zero\n") write("Sources/App.swift", "let a = 0\n") gitOut(t, work, "add", "-A") gitOut(t, work, "commit", "-q", "-m", "c0") c0 = gitOut(t, work, "rev-parse", "HEAD") write("Sources/App.swift", "let a = 1\n") write("Sources/More.swift", "let m = 1\n") gitOut(t, work, "add", "-A") gitOut(t, work, "commit", "-q", "-m", "c1") c1 = gitOut(t, work, "rev-parse", "HEAD") gitOut(t, work, "checkout", "-q", "-b", relayBranch, c0) write("Sources/Task.swift", "let t = 2\n") gitOut(t, work, "add", "-A") gitOut(t, work, "commit", "-q", "-m", "c2") c2 = gitOut(t, work, "rev-parse", "HEAD") remote := filepath.Join(r.root, "history.git") gitOut(t, r.root, "clone", "-q", "--bare", "--no-single-branch", work, remote) r.f.dir = remote return r, c0, c1, c2 } // packInventory indexes pack into an empty repository and lists the // objects in the pack itself (verify-pack), by type. func packInventory(t *testing.T, pack []byte) map[string][]string { t.Helper() dir := filepath.Join(t.TempDir(), "empty.git") if out, err := exec.Command("git", "init", "-q", "--bare", dir).CombinedOutput(); err != nil { t.Fatalf("%v: %s", err, out) } index := exec.Command("git", "--git-dir="+dir, "index-pack", "--stdin") index.Stdin = bytes.NewReader(pack) if out, err := index.CombinedOutput(); err != nil { t.Fatalf("index-pack: %v: %s", err, out) } idx, _ := filepath.Glob(filepath.Join(dir, "objects", "pack", "*.idx")) if len(idx) != 1 { t.Fatalf("pack indexes %v", idx) } out, err := exec.Command("git", "verify-pack", "-v", idx[0]).Output() if err != nil { t.Fatal(err) } inv := map[string][]string{} for _, line := range strings.Split(string(out), "\n") { f := strings.Fields(line) if len(f) >= 3 && shaPattern.MatchString(f[0]) { inv[f[1]] = append(inv[f[1]], f[0]) } } for _, v := range inv { sort.Strings(v) } return inv } // objectsOf is every object of the commits and their trees, no history, // from the source repository. func objectsOf(t *testing.T, gitDir string, commits ...string) []string { t.Helper() out, err := exec.Command("git", append([]string{"--git-dir=" + gitDir, "rev-list", "--objects", "--no-walk"}, commits...)...).Output() if err != nil { t.Fatal(err) } var all []string for _, line := range strings.Split(strings.TrimSpace(string(out)), "\n") { all = append(all, strings.Fields(line)[0]) } sort.Strings(all) return all } // An Engineering pack holds exactly the commits its header names, each // with its complete tree, and no other commit (their parents stay out); // a checks pack is still exactly the candidate. func TestPackCommitsInventory(t *testing.T) { r, c0, c1, c2 := packRig(t) ctx := context.Background() for _, c := range []struct { name string h wire.TransferHeader want []string }{ {"first step", wire.TransferHeader{ID: "tr_e1", Direction: wire.TransferInbound, Kind: wire.TransferKindEngineering, Repo: sampleRepo, TaskID: "tk1", StepID: "s1", Attempt: 1, BaseSHA: c1}, []string{c1}}, {"rebase round", wire.TransferHeader{ID: "tr_e2", Direction: wire.TransferInbound, Kind: wire.TransferKindEngineering, Repo: sampleRepo, TaskID: "tk1", StepID: "s2", Attempt: 1, BaseSHA: c1, OldBaseSHA: c0, CandidateSHA: c2}, []string{c1, c0, c2}}, {"checks", wire.TransferHeader{ID: "tr_c", Direction: wire.TransferInbound, Repo: sampleRepo, TaskID: "tk1", StepID: "s3", Attempt: 1, BaseSHA: c0, CandidateSHA: c2}, []string{c2}}, } { t.Run(c.name, func(t *testing.T) { pack, err := r.e.packCommits(ctx, c.h) if err != nil { t.Fatal(err) } inv := packInventory(t, pack) want := slices.Clone(c.want) sort.Strings(want) if !slices.Equal(inv["commit"], want) { t.Fatalf("commits in the pack %v, want exactly %v", inv["commit"], want) } var got []string for _, kind := range []string{"commit", "tree", "blob", "tag"} { got = append(got, inv[kind]...) } sort.Strings(got) if all := objectsOf(t, r.e.Clones.Path(sampleRepo), c.want...); !slices.Equal(got, all) { t.Fatalf("objects in the pack %v, want the commits' trees exactly %v", got, all) } }) } } // Before git runs, a header naming something other than full SHAs, a // repository that is not a hub repository or an invalid kind is refused; // after the fetch, a commit the clone does not have is refused. func TestPackCommitsRefuses(t *testing.T) { r, c0, c1, c2 := packRig(t) ctx := context.Background() eng := wire.TransferHeader{ID: "tr_e", Direction: wire.TransferInbound, Kind: wire.TransferKindEngineering, Repo: sampleRepo, TaskID: "tk1", StepID: "s1", Attempt: 1, BaseSHA: c1} before := map[string]wire.TransferHeader{} h := eng h.Repo = "github.com/someone/else" before["not a hub repository"] = h h = eng h.BaseSHA = "main" before["a ref, not a SHA"] = h h = eng h.BaseSHA = strings.ToUpper(c1) before["not lowercase"] = h h = eng h.OldBaseSHA = c0 before["old base without candidate"] = h h = eng h.Direction = wire.TransferOutbound before["outbound engineering"] = h h = eng h.Kind = "everything" before["unknown kind"] = h h = wire.TransferHeader{ID: "tr_c", Direction: wire.TransferInbound, Repo: sampleRepo, TaskID: "tk1", StepID: "s1", Attempt: 1, CandidateSHA: "HEAD"} before["checks candidate not a SHA"] = h git := r.e.O.Runner.GitPath r.e.O.Runner.GitPath, r.e.Clones.Git = "/nonexistent/git", "/nonexistent/git" for name, h := range before { if _, err := r.e.packCommits(ctx, h); !errors.Is(err, errPackRefused) { t.Errorf("%s: %v, want refused before git runs", name, err) } } r.e.O.Runner.GitPath, r.e.Clones.Git = git, git missing := eng missing.OldBaseSHA, missing.CandidateSHA = c0, strings.Repeat("e", 40) if _, err := r.e.packCommits(ctx, missing); !errors.Is(err, errPackRefused) { t.Fatalf("a commit the clone does not have: %v", err) } ok := eng ok.OldBaseSHA, ok.CandidateSHA = c0, c2 if _, err := r.e.packCommits(ctx, ok); err != nil { t.Fatalf("the rebase round's pack: %v", err) } } // changeDiffs are the change_diff uploads in the outbox, in order. func (r *relayRig) changeDiffs(t *testing.T) (ups []wire.ChangeDiffUpload, raw []string) { t.Helper() frames, _, err := r.e.O.State.Unacked(context.Background(), 0) if err != nil { t.Fatal(err) } for _, f := range frames { if f.Type == wire.FrameChangeDiff { var v wire.ChangeDiffUpload if err := json.Unmarshal(f.Data, &v); err != nil { t.Fatal(err) } ups = append(ups, v) raw = append(raw, string(f.Data)) } } return ups, raw } // After the push, the primary measures the worker's candidate on the // base and queues its diffs, each naming the publication and the // worker's task, step and attempt, before the published report that // carries the files, the collection and the outcome the publish command // named. The runner's bearer token never reaches a diff. func TestPublishWorkerChangeFilesAndDiffs(t *testing.T) { // Words no generic secret rule flags: only the known-secret exclusion // keeps the runner's bearer token out of the diffs. const token = "correcthorsebatterystaplerunnerbearer" ctx := context.Background() publish := func(r *relayRig, id string) { t.Helper() h := r.header() if err := r.e.O.State.AcceptPublish(ctx, "pub-"+id, wire.PublishCommand{Publication: id, TaskID: h.TaskID, StepID: h.StepID, Attempt: h.Attempt, Repo: h.Repo, Branch: relayBranch, Person: "p@x", BaseSHA: r.base, CandidateSHA: r.commit, Transfer: h.ID, OutcomePhase: wire.OutcomeUnfinished}); err != nil { t.Fatal(err) } } rig := func(t *testing.T) *relayRig { r := newRelayRigWith(t, map[string]string{"Config.txt": "server = example.com\nmotto = " + token + "\n", "Notes.md": "plain words\n"}) r.e.DiffSecrets = []string{token} r.e.O.Protocol = func() int { return wire.ProtocolMacEngineering } r.receive(t, r.pack, r.header()) return r } t.Run("pushed", func(t *testing.T) { r := rig(t) publish(r, "pb_1") r.relay.Once(ctx) reps := r.reports(t) if len(reps) != 1 || !reps[0].Pushed || reps[0].OutcomePhase != wire.OutcomeUnfinished { t.Fatalf("published %+v", reps) } f := reps[0].ChangeFiles if f == nil || f.Base != r.base || f.SHA != r.commit || f.Files != 3 || !wire.ValidChangeFiles(f) { t.Fatalf("change files %+v", f) } ups, raw := r.changeDiffs(t) if len(ups) != 3 { t.Fatalf("%d diffs", len(ups)) } files := make([]wire.FileDiff, len(ups)) for i, u := range ups { if u.Publication != "pb_1" || u.TaskID != "tk1" || u.StepID != "s1" || u.Attempt != 1 || u.Base != r.base || u.Candidate != r.commit || u.Index != i || u.Total != 3 { t.Fatalf("diff %d not bound to the publication: %+v", i, u) } patch, _ := base64.StdEncoding.DecodeString(u.Data) files[i] = wire.FileDiff{Path: u.Path, Patch: string(patch), Reason: u.Reason, Truncated: u.Truncated} if strings.Contains(string(patch), token) || strings.Contains(raw[i], token) || strings.Contains(raw[i], base64.StdEncoding.EncodeToString([]byte(token))) { t.Fatalf("the bearer token in diff %d: %s", i, raw[i]) } switch u.Path { case "Config.txt": if u.Reason == "" || u.Size != 0 { t.Fatalf("the secret-bearing file was shown: %+v", u) } case "Swipe.swift": if !strings.Contains(string(patch), "+let back = true") { t.Fatalf("swipe diff %q", patch) } } } if reps[0].DiffCollection == "" || reps[0].DiffCollection != wire.DiffCollection(files) { t.Fatalf("collection %q", reps[0].DiffCollection) } // The diffs go before the report that names them. frames, _, _ := r.e.O.State.Unacked(ctx, 0) if last := frames[len(frames)-1]; last.Type != wire.FramePublished { t.Fatalf("last frame %s", last.Type) } for _, fr := range frames { if strings.Contains(string(fr.Data), token) { t.Fatalf("the bearer token in %s", fr.Type) } } }) t.Run("push failed", func(t *testing.T) { r := rig(t) publish(r, "pb_1") // The hub refuses the push itself, after everything before it // succeeded. hook := filepath.Join(r.remote, "hooks", "pre-receive") if err := os.WriteFile(hook, []byte("#!/bin/sh\nexit 1\n"), 0755); err != nil { t.Fatal(err) } r.relay.Once(ctx) reps := r.reports(t) if len(reps) != 1 || reps[0].Pushed || reps[0].ChangeFiles != nil || reps[0].DiffCollection != "" || reps[0].OutcomePhase != wire.OutcomeUnfinished { t.Fatalf("failed push %+v", reps) } if ups, _ := r.changeDiffs(t); len(ups) != 0 { t.Fatalf("%d diffs queued without a push", len(ups)) } // Retry's publication pushes and then sends them. os.Remove(hook) publish(r, "pb_2") r.relay.Once(ctx) ups, _ := r.changeDiffs(t) if reps = r.reports(t); len(reps) != 2 || !reps[1].Pushed || len(ups) != 3 || ups[0].Publication != "pb_2" || reps[1].DiffCollection == "" { t.Fatalf("republished %+v, %d diffs", reps, len(ups)) } }) t.Run("diffs unavailable", func(t *testing.T) { // The forge credential cannot be read, so its secrets cannot be // left out: no diffs, and still a push. r := rig(t) r.e.O.Runner.AmadanCredentialPath = filepath.Join(r.root, "missing-credential") publish(r, "pb_1") r.relay.Once(ctx) reps := r.reports(t) if ups, _ := r.changeDiffs(t); len(reps) != 1 || !reps[0].Pushed || reps[0].DiffCollection != "" || len(ups) != 0 || r.pushCount() != 1 { t.Fatalf("diagnostic, not a push failure: %+v, %d diffs", reps, len(ups)) } }) t.Run("older instance", func(t *testing.T) { r := rig(t) r.e.O.Protocol = func() int { return wire.ProtocolChangeDiffs } publish(r, "pb_1") r.relay.Once(ctx) reps := r.reports(t) if ups, _ := r.changeDiffs(t); len(reps) != 1 || !reps[0].Pushed || reps[0].ChangeFiles != nil || len(ups) != 0 { t.Fatalf("below 37: %+v, %d diffs", reps, len(ups)) } }) } // A file name, or a renamed file's old name, holding a secret this // primary knows (its bearer token) would reach the instance in the // change files and in every diff upload, whatever the worker scanned // (the worker does not know the primary's secrets). Such a measurement // is withheld: no files, no diffs, and the push stands. func TestPublishWorkerSecretInFileName(t *testing.T) { const token = "correcthorsebatterystaplerunnerbearer" ctx := context.Background() for _, c := range []struct { name string before, extra map[string]string moves [][2]string }{ {name: "file name", extra: map[string]string{"keys-" + token + ".txt": "nothing secret inside\n"}}, {name: "renamed from", before: map[string]string{"notes-" + token + ".md": "the same words\nin both names\n"}, moves: [][2]string{{"notes-" + token + ".md", "notes.md"}}}, } { t.Run(c.name, func(t *testing.T) { r := newRelayRigFiles(t, c.before, c.extra, c.moves) r.e.DiffSecrets = []string{token} r.e.O.Protocol = func() int { return wire.ProtocolMacEngineering } r.receive(t, r.pack, r.header()) h := r.header() if err := r.e.O.State.AcceptPublish(ctx, "pub-1", wire.PublishCommand{Publication: "pb_1", TaskID: h.TaskID, StepID: h.StepID, Attempt: h.Attempt, Repo: h.Repo, Branch: relayBranch, Person: "p@x", BaseSHA: r.base, CandidateSHA: r.commit, Transfer: h.ID}); err != nil { t.Fatal(err) } r.relay.Once(ctx) reps := r.reports(t) if len(reps) != 1 || !reps[0].Pushed || reps[0].ChangeFiles != nil || reps[0].DiffCollection != "" { t.Fatalf("published %+v", reps) } if ups, _ := r.changeDiffs(t); len(ups) != 0 { t.Fatalf("%d diffs sent", len(ups)) } frames, _, err := r.e.O.State.Unacked(ctx, 0) if err != nil { t.Fatal(err) } for _, f := range frames { if strings.Contains(string(f.Data), token) || strings.Contains(string(f.Data), base64.StdEncoding.EncodeToString([]byte(token))) { t.Fatalf("the bearer token in %s: %s", f.Type, f.Data) } } }) } } // On a worker, unfinished work sent at protocol 37 is the work done, never // pushed (only the primary's published report says that), with its // outcome; the primary's own report is unchanged. func TestWorkerUnfinishedReportNeverPushed(t *testing.T) { e, _, r, _ := hubRig(t) ctx := context.Background() s := e.O.State cand := strings.Repeat("2", 40) r.Specialist, r.StepID = wire.SpecialistEngineering, "s9" if err := s.AcceptDispatch(ctx, "d-s9", r.DispatchCommand); err != nil { t.Fatal(err) } if err := s.setStepPhase(ctx, r, phaseCommittedUnfinished, "", cand); err != nil { t.Fatal(err) } if err := s.ReportStep(ctx, r, wire.StepReport{TaskID: r.TaskID, StepID: "s9", Attempt: 1, State: wire.StepDone, Reason: "step_timeout", CandidateSHA: cand, Termination: true, Findings: []wire.Finding{}}); err != nil { t.Fatal(err) } frames, _, err := s.Unacked(ctx, 0) if err != nil || len(frames) != 1 { t.Fatalf("queued %d: %v", len(frames), err) } read := func(f wire.Frame) *wire.StepReport { body, err := f.Decode() if err != nil { t.Fatal(err) } return body.(*wire.StepReport) } sent, err := s.unfinishedReport(ctx, frames[0], wire.ProtocolMacEngineering, true) if err != nil { t.Fatal(err) } if v := read(sent); v.Pushed || v.State != wire.StepDone || v.CandidateSHA != cand || v.Reason != "step_timeout" || v.OutcomePhase != wire.OutcomeUnfinished { t.Fatalf("a worker's unfinished work sent as %+v", v) } if v := read(must(s.unfinishedReport(ctx, frames[0], wire.ProtocolMacEngineering, false))); !v.Pushed || v.State != wire.StepDone || v.OutcomePhase != "" { t.Fatalf("the primary's unfinished work sent as %+v", v) } if v := read(must(s.unfinishedReport(ctx, frames[0], wire.ProtocolChangeDiffs, true))); v.Pushed || v.State != wire.StepFailed { t.Fatalf("a worker's unfinished work below 37 sent as %+v", v) } } func must[T any](v T, err error) T { if err != nil { panic(err) } return v }