package thintest import ( "crypto/sha256" "encoding/base64" "encoding/hex" "strings" "testing" "time" "amadan.net/oficina/equipo/internal/wire" ) func chunk(h wire.TransferHeader, data []byte) wire.Blob { sum := sha256.Sum256(data) return wire.Blob{Transfer: h, Index: 0, Total: 1, SHA256: hex.EncodeToString(sum[:]), Data: base64.StdEncoding.EncodeToString(data)} } // relayed counts the blob commands that reached a runner's mailbox. func (r *runnersRig) relayed(p *peer) int { r.t.Helper() var n int if err := r.inst.DB.Writer().QueryRow("SELECT count(*) FROM runner_commands WHERE runner_id = ? AND kind = ?", p.fr.Welcome.RunnerID, wire.FrameBlob).Scan(&n); err != nil { r.t.Fatal(err) } return n } // Every chunk is authorised against its transfer before a byte is kept: // a chunk from another runner, under another task's transfer, for // another candidate, in the wrong direction, or for an attempt Retry has // replaced, is refused and nothing reaches the receiver. func TestContractTransferAuthorization(t *testing.T) { r := newRunnersRig(t) w, _ := r.newWorker("Mac A") other, _ := r.newWorker("Mac B") taskA, _ := r.candidate("iOS one", true) _, body := r.primary.expect(wire.FrameSendPack) ha := body.(*wire.SendPackCommand).Transfer _, body = w.expect(wire.FrameDispatch) da := body.(*wire.DispatchCommand) taskB, _ := r.candidate("iOS two", true) _, body = r.primary.expect(wire.FrameSendPack) hb := body.(*wire.SendPackCommand).Transfer if ha.TaskID != taskA || hb.TaskID != taskB || ha.Direction != wire.TransferInbound { t.Fatalf("headers %+v %+v", ha, hb) } before := r.relayed(w) + r.relayed(other) data := []byte("PACK") // A second worker uploading for a transfer not its own. other.send(wire.FrameBlob, chunk(ha, data)) // Chunks for task A sent under task B's transfer. mixed := hb mixed.TaskID, mixed.StepID = ha.TaskID, ha.StepID r.primary.send(wire.FrameBlob, chunk(mixed, data)) // A candidate that does not match the opened transfer. wrong := ha wrong.CandidateSHA = strings.Repeat("9", 40) r.primary.send(wire.FrameBlob, chunk(wrong, data)) // An inbound transfer answered in the outbound direction. back := ha back.Direction = wire.TransferOutbound w.send(wire.FrameBlob, chunk(back, data)) // Out of bounds: a chunk index past the total. bad := chunk(ha, data) bad.Index = 3 r.primary.send(wire.FrameBlob, bad) if n := r.relayed(w) + r.relayed(other); n != before { t.Fatalf("%d refused chunks were relayed", n-before) } // A stale attempt's chunks after Retry: the worker refuses, the // attempt is replaced, and the old transfer's chunk is refused. w.send(wire.FrameStep, wire.StepReport{TaskID: taskA, StepID: da.StepID, Attempt: 1, State: wire.StepFailed, Reason: "placement_refused", Termination: true, Findings: []wire.Finding{}}) r.primary.send(wire.FrameBlob, chunk(ha, data)) if n := r.relayed(w) + r.relayed(other); n != before { t.Fatalf("a stale attempt's chunk was relayed") } // The new attempt's transfer is open, and its chunk goes through. _, body = r.primary.expect(wire.FrameSendPack) h2 := body.(*wire.SendPackCommand).Transfer if h2.Attempt != 2 || h2.StepID != ha.StepID || h2.ID == ha.ID { t.Fatalf("second transfer %+v", h2) } r.primary.send(wire.FrameBlob, chunk(h2, data)) _, got := other.expect(wire.FrameBlob) if got.(*wire.Blob).Transfer != h2 { t.Fatalf("relayed %+v", got) } } // Oversize (M7): a transfer past 64 MB is refused, and checks that never // started end as not run (checks_unavailable), never a pass. func TestContractTransferTooLarge(t *testing.T) { r := newRunnersRig(t) w, _ := r.newWorker("Mac A") task, _ := r.candidate("iOS big", true) _, body := r.primary.expect(wire.FrameSendPack) h := body.(*wire.SendPackCommand).Transfer w.expect(wire.FrameDispatch) if _, err := r.inst.DB.Writer().Exec("UPDATE runner_transfers SET bytes = ? WHERE id = ?", wire.MaxTransferBytes-2, h.ID); err != nil { t.Fatal(err) } r.primary.send(wire.FrameBlob, chunk(h, []byte("PACK"))) s := r.checksStep(task) if s.State != wire.StepDone || s.Checks != wire.ChecksCannotRun || s.Reason != "checks_unavailable" { t.Fatalf("oversized candidate: %+v", s) } if n := r.relayed(w); n != 0 { t.Fatalf("oversized chunk relayed") } } // workerCommit runs a Mac task's Engineering step on the worker (placed // there by Mac Engineering, its base prepared by the primary) to a commit // and its pack, which reaches the primary with a publish command. func (r *runnersRig) workerCommit(w *peer, title string) (task string, d *wire.DispatchCommand, sha string, pub *wire.PublishCommand) { r.t.Helper() task, d = r.macDispatch(w, title, strings.Repeat("1", 40)) if !w.lease(d.StepID, d.Attempt) { r.t.Fatal("start refused") } sha = strings.Repeat("c", 40) w.send(wire.FrameStep, wire.StepReport{TaskID: task, StepID: d.StepID, Attempt: d.Attempt, State: wire.StepRunning, BaseSHA: strings.Repeat("1", 40), Findings: []wire.Finding{}}) w.send(wire.FrameStep, wire.StepReport{TaskID: task, StepID: d.StepID, Attempt: d.Attempt, State: wire.StepRunning, CandidateSHA: sha, Phase: "committed", Findings: []wire.Finding{}}) _, body := w.expect(wire.FrameSendPack) h := body.(*wire.SendPackCommand).Transfer if h.Direction != wire.TransferOutbound || h.CandidateSHA != sha { r.t.Fatalf("outbound header %+v", h) } // A worker claiming it pushed is refused: the step does not end. w.send(wire.FrameStep, wire.StepReport{TaskID: task, StepID: d.StepID, Attempt: d.Attempt, State: wire.StepDone, CandidateSHA: sha, Pushed: true, Termination: true, Findings: []wire.Finding{}}) if k, _ := r.client.Task(r.ctx, task); k.Steps[0].State != wire.StepRunning || k.Steps[0].Pushed { r.t.Fatalf("a worker's pushed was accepted: %+v", k.Steps[0]) } w.send(wire.FrameStep, wire.StepReport{TaskID: task, StepID: d.StepID, Attempt: d.Attempt, State: wire.StepDone, CandidateSHA: sha, Termination: true, TerminationKind: wire.TerminationProcessGroup, Findings: []wire.Finding{}}) w.send(wire.FrameBlob, chunk(h, []byte("PACK commit"))) r.fromPrimary(wire.FrameBlob) pub = r.fromPrimary(wire.FramePublish).(*wire.PublishCommand) if pub.CandidateSHA != sha || pub.Transfer != h.ID || pub.StepID != d.StepID { r.t.Fatalf("publish %+v", pub) } return task, d, sha, pub } // Publication stays the primary's word: a worker's pushed is refused; the // candidate counts as pushed only on the primary's published report for // the current attempt and candidate, and only then are checks and review // created. A failed push is Needs you retry, and Retry publishes the same // commit again without running Engineering. func TestContractPublication(t *testing.T) { r := newMacRig(t) w := r.newMacEngineer("Mac A", wire.EngineeringReady) task, d, sha, pub := r.workerCommit(w, "iOS fix") // The worker claiming it pushed is refused. w.send(wire.FrameStep, wire.StepReport{TaskID: task, StepID: d.StepID, Attempt: d.Attempt, State: wire.StepDone, CandidateSHA: sha, Pushed: true, Termination: true, Findings: []wire.Finding{}}) k, _ := r.client.Task(r.ctx, task) if k.Steps[0].Pushed || k.Steps[0].Publication != wire.PublicationPending || k.CandidateSHA != "" || len(k.Steps) != 1 { t.Fatalf("before publication %+v", k.Steps[0]) } // A published report from the worker is refused. w.send(wire.FramePublished, wire.PublishedReport{Publication: pub.Publication, TaskID: task, StepID: d.StepID, Attempt: d.Attempt, CandidateSHA: sha, Pushed: true}) if k, _ = r.client.Task(r.ctx, task); k.Steps[0].Pushed { t.Fatal("a worker published") } // The primary's push fails: Needs you retry. if !r.primary.leasePublication(d.StepID, d.Attempt, pub.Publication) { t.Fatal("publication refused") } r.primary.send(wire.FramePublished, wire.PublishedReport{Publication: pub.Publication, TaskID: task, StepID: d.StepID, Attempt: d.Attempt, CandidateSHA: sha, Pushed: false, Reason: "push_failed"}) k, _ = r.client.Task(r.ctx, task) if k.NeedsYou != wire.NeedsRetry || k.Steps[0].Publication != wire.PublicationFailed { t.Fatalf("after a failed push %+v", k) } acc, err := r.client.RetryTask(r.ctx, task) if err != nil || acc.Attempt != d.Attempt { t.Fatalf("retry %+v %v", acc, err) } again := r.fromPrimary(wire.FramePublish).(*wire.PublishCommand) if again.CandidateSHA != sha || again.Transfer != pub.Transfer || again.Publication == pub.Publication || again.Attempt != d.Attempt { t.Fatalf("republish %+v", again) } w.none(wire.FrameDispatch, 50*time.Millisecond) // The old publication is no longer the pending one. if r.primary.leasePublication(d.StepID, d.Attempt, pub.Publication) { t.Fatal("a superseded publication was confirmed") } r.primary.send(wire.FramePublished, wire.PublishedReport{Publication: again.Publication, TaskID: task, StepID: d.StepID, Attempt: d.Attempt, CandidateSHA: sha, Pushed: true}) if _, c := r.macChecked(task, w); c.CandidateSHA != sha { t.Fatalf("checks after publication %+v", c) } if k, _ = r.client.Task(r.ctx, task); !k.Steps[0].Pushed || k.Steps[0].Publication != wire.PublicationPublished || k.CandidateSHA != sha || k.EngineeringRunner != w.fr.Welcome.RunnerID { t.Fatalf("published %+v", k) } } // Cancel after the pack arrived and before the push: the primary's // confirmation right before it pushes is refused, so nothing is pushed. func TestContractCancelBeforePublication(t *testing.T) { r := newMacRig(t) w := r.newMacEngineer("Mac A", wire.EngineeringReady) task, d, sha, pub := r.workerCommit(w, "iOS cancel") if _, err := r.client.CancelTask(r.ctx, task); err != nil { t.Fatal(err) } if r.primary.leasePublication(d.StepID, d.Attempt, pub.Publication) { t.Fatal("a cancelled task's publication was confirmed") } r.primary.send(wire.FramePublished, wire.PublishedReport{Publication: pub.Publication, TaskID: task, StepID: d.StepID, Attempt: d.Attempt, CandidateSHA: sha, Pushed: false, Reason: "cancelled"}) if k, _ := r.client.Task(r.ctx, task); k.Stage != wire.StageCancelled || k.Steps[0].Pushed { t.Fatalf("cancelled %+v", k) } }