package thintest import ( "net/http" "net/url" "strings" "testing" "time" "amadan.net/oficina/equipo/internal/wire" ) // approvedWithPreview takes a task to Review's approval on cand, Review // saying the candidate has a preview config or not, and returns the task // and the preview dispatch, if any came. func (r *toolRig) approvedWithPreview(key, base, cand string, has bool) (string, *wire.DispatchCommand) { r.t.Helper() id, _ := r.pushed(key, "Barber mockups", base, cand) r.expect(wire.FrameWatchMerge) c := r.dispatched(wire.SpecialistChecks, base, cand, 0) r.checks(key+"-c", c, wire.ChecksPassed, exit(0), "", "ok\n") rv := r.dispatched(wire.SpecialistReview, base, cand, 0) r.step(key+"-r", wire.StepReport{TaskID: rv.TaskID, StepID: rv.StepID, Attempt: rv.Attempt, State: wire.StepDone, BaseSHA: base, CandidateSHA: cand, Termination: true, Family: "codex", Account: "codex-a", Verdict: wire.VerdictApprove, ReviewLabel: wire.ReviewOtherFamily, Findings: []wire.Finding{}, Summary: "Read it.", HasPreview: has}) return id, r.previewDispatch(cand) } // previewDispatch is the preview dispatch for cand among what the // instance sent so far, or nil. func (r *toolRig) previewDispatch(cand string) *wire.DispatchCommand { r.t.Helper() deadline := time.Now().Add(2 * time.Second) for time.Now().Before(deadline) { for i, h := range r.held { if d, ok := h.body.(*wire.DispatchCommand); ok && d.Specialist == wire.SpecialistPreview && d.CandidateSHA == cand { r.held = append(r.held[:i:i], r.held[i+1:]...) return d } } // Let the instance's next frames arrive (a ping lease is acked). if refused := r.lease(r.runner, "pv-poll-"+itoa(int(time.Now().UnixNano()%1e9)), wire.LeaseCheck{}); refused != "" { r.t.Fatalf("poll lease refused %q", refused) } } return nil } var digestA, digestB = strings.Repeat("a", 64), strings.Repeat("b", 64) func (r *toolRig) built(key string, d *wire.DispatchCommand, digest string) { r.t.Helper() r.step(key, wire.StepReport{TaskID: d.TaskID, StepID: d.StepID, Attempt: d.Attempt, State: wire.StepRunning, BaseSHA: d.BaseSHA, CandidateSHA: d.CandidateSHA, Findings: []wire.Finding{}, Preview: &wire.PreviewResult{Phase: wire.PreviewBuilt, Digest: digest, Files: 12, Bytes: 340 << 10}}) } func (r *toolRig) previewDone(key string, d *wire.DispatchCommand, p wire.PreviewResult) { r.t.Helper() r.step(key, wire.StepReport{TaskID: d.TaskID, StepID: d.StepID, Attempt: d.Attempt, State: wire.StepDone, BaseSHA: d.BaseSHA, CandidateSHA: d.CandidateSHA, Termination: true, Findings: []wire.Finding{}, Preview: &p}) } // asksBeforeMerging sets the sample project to ask before every merge, // so an approved task stays at Ready to merge. func (r *toolRig) asksBeforeMerging() { r.t.Helper() project := r.project() pol, err := r.client.MergePolicy(r.ctx, project) if err != nil { r.t.Fatal(err) } if _, err := r.client.SetMergePolicy(r.ctx, project, wire.SetMergePolicy{Mode: "ask", MaxLines: pol.MaxLines, MaxFiles: pol.MaxFiles, MainShips: pol.MainShips, ExtraSensitive: pol.ExtraSensitive, Revision: pol.Revision}); err != nil { r.t.Fatal(err) } } func (r *toolRig) audits(kind string) int { r.t.Helper() var n int if err := r.inst.DB.Writer().QueryRow("SELECT count(*) FROM audit_events WHERE kind = ?", kind).Scan(&n); err != nil { r.t.Fatal(err) } return n } // TestContractPreview: an approved candidate whose Review found a preview // config gets one preview step on the primary; its start and each publish // check are decided for the exact export reported as built; the deployed // preview gives the task card its line, and the timeline says it was // prepared, then ready; every decision and outcome is audited, and the // preview never moves the task. func TestContractPreview(t *testing.T) { r := publicPreviewRig(t) r.asksBeforeMerging() base, cand := strings.Repeat("1", 40), strings.Repeat("2", 40) id, d := r.approvedWithPreview("p", base, cand, true) if d == nil || d.CandidateSHA != cand || d.Repo != "amadan.net/oficina/sample" { t.Fatalf("no preview dispatched: %+v", d) } before, _ := r.client.Task(r.ctx, id) if refused := r.lease(r.runner, "p-start", wire.LeaseCheck{StepID: d.StepID, Attempt: d.Attempt}); refused != "" { t.Fatalf("start refused %q", refused) } if refused := r.lease(r.runner, "p-early", wire.LeaseCheck{StepID: d.StepID, Attempt: d.Attempt, Purpose: wire.LeasePurposePreview, Digest: digestA}); refused != wire.RefusedPreviewNotBuilt { t.Fatalf("publish before built: %q", refused) } r.built("p-built", d, digestA) if refused := r.lease(r.runner, "p-other", wire.LeaseCheck{StepID: d.StepID, Attempt: d.Attempt, Purpose: wire.LeasePurposePreview, Digest: digestB}); refused == "" { t.Fatal("another export's publish check allowed") } if refused := r.lease(r.runner, "p-pub", wire.LeaseCheck{StepID: d.StepID, Attempt: d.Attempt, Purpose: wire.LeasePurposePreview, Digest: digestA}); refused != "" { t.Fatalf("publish refused %q", refused) } expires := time.Now().Add(7 * 24 * time.Hour) url := "https://tmp-" + id + ".bds.oncarlos.com/" r.previewDone("p-published", d, wire.PreviewResult{Phase: wire.PreviewDone, App: "tmp-" + id, URL: url, Version: "p-" + d.StepID + "-1", Digest: digestA, ExpiresAt: &expires, Outcome: wire.PreviewDeployed}) k, _ := r.client.Task(r.ctx, id) last := k.Steps[len(k.Steps)-1] if last.Specialist != wire.SpecialistPreview || last.State != wire.StepDone || last.Preview == nil || last.Preview.URL != url || last.Preview.Files != 12 { t.Fatalf("preview step %+v %+v", last, last.Preview) } if k.Stage != before.Stage || k.NeedsYou != before.NeedsYou { t.Fatalf("the preview moved the task: %s/%s to %s/%s", before.Stage, before.NeedsYou, k.Stage, k.NeedsYou) } page := r.get(r.inst.Cookie(), "/tasks/"+id, 200) for _, want := range []string{"Preview: tmp-" + id + ".bds.oncarlos.com (expires in 7 days)", `href="/tasks/` + id + `/preview"`, "Prepared 12 files (340 KiB).", "Preview ready"} { if !strings.Contains(page, want) { t.Fatalf("task page lacks %q", want) } } for _, s := range []string{"shipped", "deployed to production"} { if strings.Contains(strings.ToLower(page), s) { t.Fatalf("the page says %q", s) } } if r.audits("preview.authorize") != 4 || r.audits("preview.built") != 1 || r.audits("preview.deployed") != 1 { t.Fatalf("audits %d %d %d", r.audits("preview.authorize"), r.audits("preview.built"), r.audits("preview.deployed")) } // Once per candidate: the next sync schedules no second preview. r.step("p-again", wire.StepReport{TaskID: d.TaskID, StepID: d.StepID, Attempt: d.Attempt, State: wire.StepDone, BaseSHA: base, CandidateSHA: cand, Termination: true, Findings: []wire.Finding{}}) if again := r.previewDispatch(cand); again != nil { t.Fatalf("a second preview for the same candidate: %+v", again) } } // TestContractPreviewNotScheduled: without Review's word that the // candidate has a preview config, or on a primary below protocol 9, // nothing is previewed. A protocol 8 primary speaks the empty-repository // merge but not previews: even when its Review says has_preview, it never // gets a preview dispatch. func TestContractPreviewNotScheduled(t *testing.T) { r := publicPreviewRig(t) if _, d := r.approvedWithPreview("n", strings.Repeat("1", 40), strings.Repeat("2", 40), false); d != nil { t.Fatalf("previewed without a config: %+v", d) } for _, p := range []int{wire.ProtocolEmptyMerge, wire.ProtocolSandboxConsent, wire.Protocol26} { old := newToolRigAt(t, p) if _, d := old.approvedWithPreview("o", strings.Repeat("1", 40), strings.Repeat("3", 40), true); d != nil { t.Fatalf("previewed on a protocol %d primary: %+v", p, d) } } } // TestContractPreviewAuthority: the start and publish checks hold only // while the candidate is the task's newest and approved, the task is not // cancelled and its creator is still an owner; a done report for another // app or export, or an unexpected URL, counts for nothing. func TestContractPreviewAuthority(t *testing.T) { r := publicPreviewRig(t) r.asksBeforeMerging() base, cand := strings.Repeat("1", 40), strings.Repeat("2", 40) id, d := r.approvedWithPreview("a", base, cand, true) if d == nil { t.Fatal("no preview") } r.built("a-built", d, digestA) for name, p := range map[string]wire.PreviewResult{ "another app": {Phase: wire.PreviewDone, App: "tmp-other", URL: "https://tmp-other.bds.oncarlos.com/", Digest: digestA, Outcome: wire.PreviewDeployed}, "another export": {Phase: wire.PreviewDone, App: "tmp-" + id, URL: "https://tmp-" + id + ".bds.oncarlos.com/", Digest: digestB, Outcome: wire.PreviewDeployed}, "a foreign URL": {Phase: wire.PreviewDone, App: "tmp-" + id, URL: "https://evil.example/", Digest: digestA, Outcome: wire.PreviewDeployed}, "no outcome": {Phase: wire.PreviewDone, App: "tmp-" + id, Digest: digestA}, } { r.previewDone("a-"+strings.ReplaceAll(name, " ", "-"), d, p) k, _ := r.client.Task(r.ctx, id) if s := k.Steps[len(k.Steps)-1]; s.State == wire.StepDone { t.Fatalf("%s counted: %+v", name, s.Preview) } } // A cancelled task refuses every check. if res := r.call("a-cancel", wire.ToolCancelTask, map[string]string{"task": id}); res.IsError { t.Fatalf("cancel %+v", res) } if refused := r.lease(r.runner, "a-pub", wire.LeaseCheck{StepID: d.StepID, Attempt: d.Attempt, Purpose: wire.LeasePurposePreview, Digest: digestA}); refused == "" { t.Fatal("published on a cancelled task") } if r.audits("preview.authorize") < 1 { t.Fatal("the refusal was not audited") } } // TestContractPreviewFence: a primary that comes back below protocol 9 // (here at 8, which has the empty-repository merge but no previews) holds // no preview: the queued step settles runner_outdated, its dispatch is // retired, and the refusal is audited. func TestContractPreviewFence(t *testing.T) { r := publicPreviewRig(t) id, d := r.approvedWithPreview("f", strings.Repeat("1", 40), strings.Repeat("2", 40), true) if d == nil { t.Fatal("no preview") } old, err := DialRunnerHello(r.ctx, r.inst.URL, r.rig.runner, primaryAt(wire.Hello{Generation: r.runner.Welcome.Generation, Repos: []string{}, Connections: []wire.HeldConnection{}, Versions: map[string]string{"runner": "test"}}, wire.ProtocolEmptyMerge)) if err != nil { t.Fatal(err) } defer old.Close() r.wait("settled", func(c *Conversation) bool { k := c.Tasks[id] return len(k.Steps) > 0 && k.Steps[len(k.Steps)-1].Specialist == wire.SpecialistPreview && k.Steps[len(k.Steps)-1].State == wire.StepCancelled }) k, _ := r.client.Task(r.ctx, id) if s := k.Steps[len(k.Steps)-1]; s.Reason != wire.ReasonRunnerOutdated { t.Fatalf("settled %+v", s) } if r.audits("preview.failed") != 1 { t.Fatalf("audit %d", r.audits("preview.failed")) } } // TestContractPreviewFailureIsQuiet: a preview that fails leaves the task // where it was, with nothing asked of anyone. func TestContractPreviewFailureIsQuiet(t *testing.T) { r := publicPreviewRig(t) r.asksBeforeMerging() id, d := r.approvedWithPreview("q", strings.Repeat("1", 40), strings.Repeat("2", 40), true) if d == nil { t.Fatal("no preview") } before, _ := r.client.Task(r.ctx, id) r.step("q-cap", wire.StepReport{TaskID: d.TaskID, StepID: d.StepID, Attempt: d.Attempt, State: wire.StepFailed, Reason: "preview_cap", BaseSHA: d.BaseSHA, CandidateSHA: d.CandidateSHA, Termination: true, Findings: []wire.Finding{}}) k, _ := r.client.Task(r.ctx, id) if k.Stage != before.Stage || k.NeedsYou != before.NeedsYou || k.Steps[len(k.Steps)-1].State != wire.StepFailed { t.Fatalf("after a failed preview: %s needs %q", k.Stage, k.NeedsYou) } if r.audits("preview.failed") != 1 { t.Fatal("not audited") } } // pairedWith says, in a new hello, that the primary pairs with host. func (r *toolRig) pairedWith(host *wire.PreviewHost) { r.t.Helper() h := primaryAt(toolHello(r.runner.Welcome.Generation), wire.ProtocolCurrent) h.Capabilities.Previews, h.Capabilities.PreviewHost = true, host if err := r.runner.Send(r.ctx, "h-paired", wire.FrameHello, h); err != nil { r.t.Fatal(err) } r.client.Snapshot(r.ctx) } // TestContractPreviewDevbox: paired with a CARLOS devbox, Settings > // Machines says which machine hosts previews; the task's devbox link // (eq-, no expiry) is on its card as on your tailnet, and leaves the // card once the task ends. func TestContractPreviewDevbox(t *testing.T) { r := newToolRigAt(t, wire.ProtocolCurrent) r.asksBeforeMerging() if page := r.get(r.inst.Cookie(), "/conversation/settings/machines", 200); !strings.Contains(page, "data-previews-none") || !strings.Contains(page, `id="previews"`) { t.Fatal("no pairing help on Machines before a host is paired") } r.pairedWith(&wire.PreviewHost{Kind: wire.PreviewHostDevbox, Domain: "devbox.dev.example"}) if page := r.get(r.inst.Cookie(), "/conversation/settings/machines", 200); !strings.Contains(page, "Previews: docs-t1 (on your tailnet)") { t.Fatal("Machines does not say which machine hosts previews") } base, cand := strings.Repeat("1", 40), strings.Repeat("2", 40) id, d := r.approvedWithPreview("dv", base, cand, true) if d == nil { t.Fatal("no preview with a paired devbox") } r.built("dv-built", d, digestA) url := "https://eq-" + id + ".devbox.dev.example/" r.previewDone("dv-published", d, wire.PreviewResult{Phase: wire.PreviewDone, App: "eq-" + id, URL: url, Digest: digestA, Outcome: wire.PreviewDeployed}) if page := r.get(r.inst.Cookie(), "/tasks/"+id, 200); !strings.Contains(page, "Preview: eq-"+id+".devbox.dev.example (on your tailnet)") { t.Fatal("no tailnet preview line") } if res := r.call("dv-cancel", wire.ToolCancelTask, map[string]string{"task": id}); res.IsError { t.Fatalf("cancel %+v", res) } if page := r.get(r.inst.Cookie(), "/tasks/"+id, 200); strings.Contains(page, "on your tailnet") { t.Fatal("an ended task still shows its devbox link") } } func publicPreviewRig(t *testing.T) *toolRig { t.Helper() r := newToolRigAt(t, wire.ProtocolCurrent) project := r.project() if code, _ := r.post(r.inst.Cookie(), "/settings/autonomy", url.Values{"project": {project}, "revision": {"0"}, "public_previews": {"on"}}); code != http.StatusSeeOther { t.Fatalf("enable public previews: %d", code) } r.pairedWith(&wire.PreviewHost{Kind: wire.PreviewHostCarlokuTemp, Domain: "bds.oncarlos.com"}) return r } func TestContractPreviewMissingHeaderOffersOwnerTap(t *testing.T) { r := publicPreviewRig(t) r.asksBeforeMerging() base, cand := strings.Repeat("1", 40), strings.Repeat("2", 40) id, d := r.approvedWithPreview("missing-header", base, cand, true) if d == nil { t.Fatal("missing preview dispatch") } r.built("header-built", d, digestA) r.step("header-missing", wire.StepReport{TaskID: id, StepID: d.StepID, Attempt: d.Attempt, BaseSHA: base, CandidateSHA: cand, State: wire.StepDone, Termination: true, Reason: "preview_header_missing", Findings: []wire.Finding{}, Preview: &wire.PreviewResult{Phase: wire.PreviewDone, App: "tmp-" + id, Digest: digestA, Outcome: wire.PreviewUnconfirmed}}) page := r.get(r.inst.Cookie(), "/tasks/"+id+"/preview", 200) if !strings.Contains(page, "Open this preview without the safety header?") || strings.Contains(page, "