package thin import ( "context" "crypto/sha256" "encoding/base64" "encoding/hex" "os" "os/exec" "path/filepath" "strings" "testing" "time" "amadan.net/oficina/equipo/internal/wire" ) // stubGate records what it was asked to run and answers code. type stubGate struct { ran [][]string dirs []string code int sandbox string } func (g *stubGate) Sandbox() string { return wire.SandboxNone } func (g *stubGate) Run(_ context.Context, _, dir string, argv []string, _ time.Duration, record func(string) error) gateResult { g.ran = append(g.ran, argv) g.dirs = append(g.dirs, dir) record("pg:1:stub") head, _ := os.ReadFile(filepath.Join(dir, "Swipe.swift")) return gateResult{code: g.code, terminated: true, output: "ran on " + strings.TrimSpace(string(head)), sandbox: g.sandbox} } func (g *stubGate) Verify(string) bool { return true } type workerRig struct { w *Worker gate *stubGate r stepRow base, commit string pack, other []byte } func onePack(t *testing.T, dir, sha string) []byte { t.Helper() objects, err := exec.Command("git", "-C", dir, "rev-list", "--objects", "--no-walk", sha).Output() if err != nil { t.Fatal(err) } packer := exec.Command("git", "-C", dir, "pack-objects", "--stdout", "-q") packer.Stdin = strings.NewReader(string(objects)) pack, err := packer.Output() if err != nil { t.Fatal(err) } return pack } func newWorkerRig(t *testing.T) *workerRig { t.Helper() root := t.TempDir() seed := filepath.Join(root, "seed") gitOut(t, root, "init", "-q", "-b", "main", seed) os.MkdirAll(filepath.Join(seed, ".amadan"), 0755) os.WriteFile(filepath.Join(seed, ".amadan", "ci"), []byte("#!/bin/sh\nxcodebuild test\n"), 0755) os.WriteFile(filepath.Join(seed, "Swipe.swift"), []byte("let back = false\n"), 0644) gitOut(t, seed, "add", "-A") gitOut(t, seed, "commit", "-q", "-m", "base") base := gitOut(t, seed, "rev-parse", "HEAD") os.WriteFile(filepath.Join(seed, "Swipe.swift"), []byte("let back = true\n"), 0644) gitOut(t, seed, "commit", "-q", "-am", "swipe") commit := gitOut(t, seed, "rev-parse", "HEAD") state := filepath.Join(root, "state") os.MkdirAll(state, 0700) s, err := OpenState(context.Background(), state) if err != nil { t.Fatal(err) } t.Cleanup(func() { s.Close() }) e := &Engineer{} e.O.Runner.GitPath, e.O.Runner.StateDir, e.O.State = "/usr/bin/git", state, s g := &stubGate{} r := stepRow{DispatchCommand: wire.DispatchCommand{Person: "p@x", TaskID: "tk1", StepID: "s2", Attempt: 1, Specialist: wire.SpecialistChecks, Repo: "amadan.net/woodstar/woodstar", Branch: "equipo/tk1-swipe", BaseSHA: base, CandidateSHA: commit, Needs: []string{wire.TagMacOS, wire.TagXcode}}} return &workerRig{w: &Worker{State: s, Engine: e, Gate: g, PackWait: 300 * time.Millisecond}, gate: g, r: r, base: base, commit: commit, pack: onePack(t, seed, commit), other: onePack(t, seed, base)} } func (x *workerRig) header() wire.TransferHeader { return wire.TransferHeader{ID: "tr_1", 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.CandidateSHA} } func (x *workerRig) chunk(t *testing.T, id string, h wire.TransferHeader, data []byte, index, total int, digest string) { t.Helper() if digest == "" { sum := sha256.Sum256(data) digest = hex.EncodeToString(sum[:]) } if err := x.w.State.AcceptChunk(context.Background(), id, wire.Blob{Transfer: h, Index: index, Total: total, SHA256: digest, Data: base64.StdEncoding.EncodeToString(data)}); err != nil { t.Fatal(err) } } func (x *workerRig) run() wire.StepReport { return x.w.Exec(context.Background(), x.r, func(wire.StepReport) {}) } // The relayed candidate is checked out at exactly its SHA and the gate // runs there; the report proves termination by process group and says // the worker now holds the commit. func TestWorkerRunsChecksOnTheRelayedCandidate(t *testing.T) { x := newWorkerRig(t) x.chunk(t, "c1", x.header(), x.pack, 0, 1, "") rep := x.run() if rep.State != wire.StepDone || rep.Checks != wire.ChecksPassed || rep.Gate != ".amadan/ci" || rep.ExitCode == nil || *rep.ExitCode != 0 || !rep.Termination || rep.TerminationKind != wire.TerminationProcessGroup || len(rep.Have) != 1 || rep.Have[0] != x.commit { t.Fatalf("report %+v", rep) } if len(x.gate.ran) != 1 || !strings.Contains(rep.Output, "let back = true") { t.Fatalf("gate %v output %q", x.gate.ran, rep.Output) } if _, err := os.Stat(x.gate.dirs[0]); !os.IsNotExist(err) { t.Fatal("the checks tree was kept") } x.gate.code = 65 x.r.Attempt = 2 h := x.header() h.ID = "tr_2" x.chunk(t, "c2", h, x.pack, 0, 1, "") if rep = x.run(); rep.State != wire.StepDone || rep.Checks != wire.ChecksFailed || *rep.ExitCode != 65 { t.Fatalf("failing gate %+v", rep) } } // M7 at the receiver: a pack whose digest is wrong, a pack that does not // hold the dispatched SHA, chunks under another task's header, and a // missing chunk are all refused before the gate runs. func TestWorkerRefusesTamperedPacks(t *testing.T) { for name, feed := range map[string]func(*testing.T, *workerRig){ "bad sha256": func(t *testing.T, x *workerRig) { x.chunk(t, "c1", x.header(), x.pack, 0, 1, strings.Repeat("0", 64)) }, "wrong SHA": func(t *testing.T, x *workerRig) { x.chunk(t, "c1", x.header(), x.other, 0, 1, "") }, "another task's header": func(t *testing.T, x *workerRig) { h := x.header() h.TaskID = "tkother" x.chunk(t, "c1", h, x.pack, 0, 1, "") }, "missing chunk": func(t *testing.T, x *workerRig) { half := len(x.pack) / 2 sum := sha256.Sum256(x.pack) x.chunk(t, "c1", x.header(), x.pack[:half], 0, 2, hex.EncodeToString(sum[:])) }, "bytes changed": func(t *testing.T, x *workerRig) { bad := append([]byte{}, x.pack...) bad[len(bad)/2] ^= 0xff sum := sha256.Sum256(x.pack) x.chunk(t, "c1", x.header(), bad, 0, 1, hex.EncodeToString(sum[:])) }, } { t.Run(name, func(t *testing.T) { x := newWorkerRig(t) feed(t, x) rep := x.run() if rep.State != wire.StepFailed || rep.Reason != "candidate_unavailable" || !rep.Termination || len(x.gate.ran) != 0 { t.Fatalf("%s: %+v gate %v", name, rep, x.gate.ran) } }) } } // A withdrawn attempt never runs: the start authorization is refused and // it ends cancelled (withdrawn) with nothing run. A dispatch whose needs // the runner lacks is refused (placement_refused) and marks the // capability report stale. func TestWorkerStartAndPlacement(t *testing.T) { x := newWorkerRig(t) x.chunk(t, "c1", x.header(), x.pack, 0, 1, "") x.w.Engine.AuthorizeStep = func(context.Context, string, int64) error { return ErrWithdrawn } if rep := x.run(); rep.State != wire.StepCancelled || rep.Reason != "withdrawn" || !rep.Termination || len(x.gate.ran) != 0 { t.Fatalf("withdrawn %+v", rep) } stale := false guard := placementGuard(func() []string { return []string{wire.TagLinux} }, func() { stale = true }, x.w.Exec) if rep := guard(context.Background(), x.r, func(wire.StepReport) {}); rep.State != wire.StepFailed || rep.Reason != "placement_refused" || !rep.Termination || !stale || len(x.gate.ran) != 0 { t.Fatalf("placement %+v stale %v", rep, stale) } }