oficina / equipo Public

Clone
git clone https://amadan.net/oficina/equipo

Plain git — no account needed to clone.

Download

Download this file

1package thintest
2
3import (
4 "net/http"
5 "net/url"
6 "strings"
7 "testing"
8 "time"
9
10 "amadan.net/oficina/equipo/internal/wire"
11)
12
13// approvedWithPreview takes a task to Review's approval on cand, Review
14// saying the candidate has a preview config or not, and returns the task
15// and the preview dispatch, if any came.
16func (r *toolRig) approvedWithPreview(key, base, cand string, has bool) (string, *wire.DispatchCommand) {
17 r.t.Helper()
18 id, _ := r.pushed(key, "Barber mockups", base, cand)
19 r.expect(wire.FrameWatchMerge)
20 c := r.dispatched(wire.SpecialistChecks, base, cand, 0)
21 r.checks(key+"-c", c, wire.ChecksPassed, exit(0), "", "ok\n")
22 rv := r.dispatched(wire.SpecialistReview, base, cand, 0)
23 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})
24 return id, r.previewDispatch(cand)
25}
26
27// previewDispatch is the preview dispatch for cand among what the
28// instance sent so far, or nil.
29func (r *toolRig) previewDispatch(cand string) *wire.DispatchCommand {
30 r.t.Helper()
31 deadline := time.Now().Add(2 * time.Second)
32 for time.Now().Before(deadline) {
33 for i, h := range r.held {
34 if d, ok := h.body.(*wire.DispatchCommand); ok && d.Specialist == wire.SpecialistPreview && d.CandidateSHA == cand {
35 r.held = append(r.held[:i:i], r.held[i+1:]...)
36 return d
37 }
38 }
39 // Let the instance's next frames arrive (a ping lease is acked).
40 if refused := r.lease(r.runner, "pv-poll-"+itoa(int(time.Now().UnixNano()%1e9)), wire.LeaseCheck{}); refused != "" {
41 r.t.Fatalf("poll lease refused %q", refused)
42 }
43 }
44 return nil
45}
46
47var digestA, digestB = strings.Repeat("a", 64), strings.Repeat("b", 64)
48
49func (r *toolRig) built(key string, d *wire.DispatchCommand, digest string) {
50 r.t.Helper()
51 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}})
52}
53
54func (r *toolRig) previewDone(key string, d *wire.DispatchCommand, p wire.PreviewResult) {
55 r.t.Helper()
56 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})
57}
58
59// asksBeforeMerging sets the sample project to ask before every merge,
60// so an approved task stays at Ready to merge.
61func (r *toolRig) asksBeforeMerging() {
62 r.t.Helper()
63 project := r.project()
64 pol, err := r.client.MergePolicy(r.ctx, project)
65 if err != nil {
66 r.t.Fatal(err)
67 }
68 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 {
69 r.t.Fatal(err)
70 }
71}
72
73func (r *toolRig) audits(kind string) int {
74 r.t.Helper()
75 var n int
76 if err := r.inst.DB.Writer().QueryRow("SELECT count(*) FROM audit_events WHERE kind = ?", kind).Scan(&n); err != nil {
77 r.t.Fatal(err)
78 }
79 return n
80}
81
82// TestContractPreview: an approved candidate whose Review found a preview
83// config gets one preview step on the primary; its start and each publish
84// check are decided for the exact export reported as built; the deployed
85// preview gives the task card its line, and the timeline says it was
86// prepared, then ready; every decision and outcome is audited, and the
87// preview never moves the task.
88func TestContractPreview(t *testing.T) {
89 r := publicPreviewRig(t)
90 r.asksBeforeMerging()
91 base, cand := strings.Repeat("1", 40), strings.Repeat("2", 40)
92 id, d := r.approvedWithPreview("p", base, cand, true)
93 if d == nil || d.CandidateSHA != cand || d.Repo != "amadan.net/oficina/sample" {
94 t.Fatalf("no preview dispatched: %+v", d)
95 }
96 before, _ := r.client.Task(r.ctx, id)
97 if refused := r.lease(r.runner, "p-start", wire.LeaseCheck{StepID: d.StepID, Attempt: d.Attempt}); refused != "" {
98 t.Fatalf("start refused %q", refused)
99 }
100 if refused := r.lease(r.runner, "p-early", wire.LeaseCheck{StepID: d.StepID, Attempt: d.Attempt, Purpose: wire.LeasePurposePreview, Digest: digestA}); refused != wire.RefusedPreviewNotBuilt {
101 t.Fatalf("publish before built: %q", refused)
102 }
103 r.built("p-built", d, digestA)
104 if refused := r.lease(r.runner, "p-other", wire.LeaseCheck{StepID: d.StepID, Attempt: d.Attempt, Purpose: wire.LeasePurposePreview, Digest: digestB}); refused == "" {
105 t.Fatal("another export's publish check allowed")
106 }
107 if refused := r.lease(r.runner, "p-pub", wire.LeaseCheck{StepID: d.StepID, Attempt: d.Attempt, Purpose: wire.LeasePurposePreview, Digest: digestA}); refused != "" {
108 t.Fatalf("publish refused %q", refused)
109 }
110 expires := time.Now().Add(7 * 24 * time.Hour)
111 url := "https://tmp-" + id + ".bds.oncarlos.com/"
112 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})
113 k, _ := r.client.Task(r.ctx, id)
114 last := k.Steps[len(k.Steps)-1]
115 if last.Specialist != wire.SpecialistPreview || last.State != wire.StepDone || last.Preview == nil || last.Preview.URL != url || last.Preview.Files != 12 {
116 t.Fatalf("preview step %+v %+v", last, last.Preview)
117 }
118 if k.Stage != before.Stage || k.NeedsYou != before.NeedsYou {
119 t.Fatalf("the preview moved the task: %s/%s to %s/%s", before.Stage, before.NeedsYou, k.Stage, k.NeedsYou)
120 }
121 page := r.get(r.inst.Cookie(), "/tasks/"+id, 200)
122 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"} {
123 if !strings.Contains(page, want) {
124 t.Fatalf("task page lacks %q", want)
125 }
126 }
127 for _, s := range []string{"shipped", "deployed to production"} {
128 if strings.Contains(strings.ToLower(page), s) {
129 t.Fatalf("the page says %q", s)
130 }
131 }
132 if r.audits("preview.authorize") != 4 || r.audits("preview.built") != 1 || r.audits("preview.deployed") != 1 {
133 t.Fatalf("audits %d %d %d", r.audits("preview.authorize"), r.audits("preview.built"), r.audits("preview.deployed"))
134 }
135 // Once per candidate: the next sync schedules no second preview.
136 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{}})
137 if again := r.previewDispatch(cand); again != nil {
138 t.Fatalf("a second preview for the same candidate: %+v", again)
139 }
140}
141
142// TestContractPreviewNotScheduled: without Review's word that the
143// candidate has a preview config, or on a primary below protocol 9,
144// nothing is previewed. A protocol 8 primary speaks the empty-repository
145// merge but not previews: even when its Review says has_preview, it never
146// gets a preview dispatch.
147func TestContractPreviewNotScheduled(t *testing.T) {
148 r := publicPreviewRig(t)
149 if _, d := r.approvedWithPreview("n", strings.Repeat("1", 40), strings.Repeat("2", 40), false); d != nil {
150 t.Fatalf("previewed without a config: %+v", d)
151 }
152 for _, p := range []int{wire.ProtocolEmptyMerge, wire.ProtocolSandboxConsent, wire.Protocol26} {
153 old := newToolRigAt(t, p)
154 if _, d := old.approvedWithPreview("o", strings.Repeat("1", 40), strings.Repeat("3", 40), true); d != nil {
155 t.Fatalf("previewed on a protocol %d primary: %+v", p, d)
156 }
157 }
158}
159
160// TestContractPreviewAuthority: the start and publish checks hold only
161// while the candidate is the task's newest and approved, the task is not
162// cancelled and its creator is still an owner; a done report for another
163// app or export, or an unexpected URL, counts for nothing.
164func TestContractPreviewAuthority(t *testing.T) {
165 r := publicPreviewRig(t)
166 r.asksBeforeMerging()
167 base, cand := strings.Repeat("1", 40), strings.Repeat("2", 40)
168 id, d := r.approvedWithPreview("a", base, cand, true)
169 if d == nil {
170 t.Fatal("no preview")
171 }
172 r.built("a-built", d, digestA)
173 for name, p := range map[string]wire.PreviewResult{
174 "another app": {Phase: wire.PreviewDone, App: "tmp-other", URL: "https://tmp-other.bds.oncarlos.com/", Digest: digestA, Outcome: wire.PreviewDeployed},
175 "another export": {Phase: wire.PreviewDone, App: "tmp-" + id, URL: "https://tmp-" + id + ".bds.oncarlos.com/", Digest: digestB, Outcome: wire.PreviewDeployed},
176 "a foreign URL": {Phase: wire.PreviewDone, App: "tmp-" + id, URL: "https://evil.example/", Digest: digestA, Outcome: wire.PreviewDeployed},
177 "no outcome": {Phase: wire.PreviewDone, App: "tmp-" + id, Digest: digestA},
178 } {
179 r.previewDone("a-"+strings.ReplaceAll(name, " ", "-"), d, p)
180 k, _ := r.client.Task(r.ctx, id)
181 if s := k.Steps[len(k.Steps)-1]; s.State == wire.StepDone {
182 t.Fatalf("%s counted: %+v", name, s.Preview)
183 }
184 }
185 // A cancelled task refuses every check.
186 if res := r.call("a-cancel", wire.ToolCancelTask, map[string]string{"task": id}); res.IsError {
187 t.Fatalf("cancel %+v", res)
188 }
189 if refused := r.lease(r.runner, "a-pub", wire.LeaseCheck{StepID: d.StepID, Attempt: d.Attempt, Purpose: wire.LeasePurposePreview, Digest: digestA}); refused == "" {
190 t.Fatal("published on a cancelled task")
191 }
192 if r.audits("preview.authorize") < 1 {
193 t.Fatal("the refusal was not audited")
194 }
195}
196
197// TestContractPreviewFence: a primary that comes back below protocol 9
198// (here at 8, which has the empty-repository merge but no previews) holds
199// no preview: the queued step settles runner_outdated, its dispatch is
200// retired, and the refusal is audited.
201func TestContractPreviewFence(t *testing.T) {
202 r := publicPreviewRig(t)
203 id, d := r.approvedWithPreview("f", strings.Repeat("1", 40), strings.Repeat("2", 40), true)
204 if d == nil {
205 t.Fatal("no preview")
206 }
207 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))
208 if err != nil {
209 t.Fatal(err)
210 }
211 defer old.Close()
212 r.wait("settled", func(c *Conversation) bool {
213 k := c.Tasks[id]
214 return len(k.Steps) > 0 && k.Steps[len(k.Steps)-1].Specialist == wire.SpecialistPreview && k.Steps[len(k.Steps)-1].State == wire.StepCancelled
215 })
216 k, _ := r.client.Task(r.ctx, id)
217 if s := k.Steps[len(k.Steps)-1]; s.Reason != wire.ReasonRunnerOutdated {
218 t.Fatalf("settled %+v", s)
219 }
220 if r.audits("preview.failed") != 1 {
221 t.Fatalf("audit %d", r.audits("preview.failed"))
222 }
223}
224
225// TestContractPreviewFailureIsQuiet: a preview that fails leaves the task
226// where it was, with nothing asked of anyone.
227func TestContractPreviewFailureIsQuiet(t *testing.T) {
228 r := publicPreviewRig(t)
229 r.asksBeforeMerging()
230 id, d := r.approvedWithPreview("q", strings.Repeat("1", 40), strings.Repeat("2", 40), true)
231 if d == nil {
232 t.Fatal("no preview")
233 }
234 before, _ := r.client.Task(r.ctx, id)
235 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{}})
236 k, _ := r.client.Task(r.ctx, id)
237 if k.Stage != before.Stage || k.NeedsYou != before.NeedsYou || k.Steps[len(k.Steps)-1].State != wire.StepFailed {
238 t.Fatalf("after a failed preview: %s needs %q", k.Stage, k.NeedsYou)
239 }
240 if r.audits("preview.failed") != 1 {
241 t.Fatal("not audited")
242 }
243}
244
245// pairedWith says, in a new hello, that the primary pairs with host.
246func (r *toolRig) pairedWith(host *wire.PreviewHost) {
247 r.t.Helper()
248 h := primaryAt(toolHello(r.runner.Welcome.Generation), wire.ProtocolCurrent)
249 h.Capabilities.Previews, h.Capabilities.PreviewHost = true, host
250 if err := r.runner.Send(r.ctx, "h-paired", wire.FrameHello, h); err != nil {
251 r.t.Fatal(err)
252 }
253 r.client.Snapshot(r.ctx)
254}
255
256// TestContractPreviewDevbox: paired with a CARLOS devbox, Settings >
257// Machines says which machine hosts previews; the task's devbox link
258// (eq-<task>, no expiry) is on its card as on your tailnet, and leaves the
259// card once the task ends.
260func TestContractPreviewDevbox(t *testing.T) {
261 r := newToolRigAt(t, wire.ProtocolCurrent)
262 r.asksBeforeMerging()
263 if page := r.get(r.inst.Cookie(), "/conversation/settings/machines", 200); !strings.Contains(page, "data-previews-none") || !strings.Contains(page, `id="previews"`) {
264 t.Fatal("no pairing help on Machines before a host is paired")
265 }
266 r.pairedWith(&wire.PreviewHost{Kind: wire.PreviewHostDevbox, Domain: "devbox.dev.example"})
267 if page := r.get(r.inst.Cookie(), "/conversation/settings/machines", 200); !strings.Contains(page, "Previews: docs-t1 (on your tailnet)") {
268 t.Fatal("Machines does not say which machine hosts previews")
269 }
270 base, cand := strings.Repeat("1", 40), strings.Repeat("2", 40)
271 id, d := r.approvedWithPreview("dv", base, cand, true)
272 if d == nil {
273 t.Fatal("no preview with a paired devbox")
274 }
275 r.built("dv-built", d, digestA)
276 url := "https://eq-" + id + ".devbox.dev.example/"
277 r.previewDone("dv-published", d, wire.PreviewResult{Phase: wire.PreviewDone, App: "eq-" + id, URL: url, Digest: digestA, Outcome: wire.PreviewDeployed})
278 if page := r.get(r.inst.Cookie(), "/tasks/"+id, 200); !strings.Contains(page, "Preview: eq-"+id+".devbox.dev.example (on your tailnet)") {
279 t.Fatal("no tailnet preview line")
280 }
281 if res := r.call("dv-cancel", wire.ToolCancelTask, map[string]string{"task": id}); res.IsError {
282 t.Fatalf("cancel %+v", res)
283 }
284 if page := r.get(r.inst.Cookie(), "/tasks/"+id, 200); strings.Contains(page, "on your tailnet") {
285 t.Fatal("an ended task still shows its devbox link")
286 }
287}
288
289func publicPreviewRig(t *testing.T) *toolRig {
290 t.Helper()
291 r := newToolRigAt(t, wire.ProtocolCurrent)
292 project := r.project()
293 if code, _ := r.post(r.inst.Cookie(), "/settings/autonomy", url.Values{"project": {project}, "revision": {"0"}, "public_previews": {"on"}}); code != http.StatusSeeOther {
294 t.Fatalf("enable public previews: %d", code)
295 }
296 r.pairedWith(&wire.PreviewHost{Kind: wire.PreviewHostCarlokuTemp, Domain: "bds.oncarlos.com"})
297 return r
298}
299
300func TestContractPreviewMissingHeaderOffersOwnerTap(t *testing.T) {
301 r := publicPreviewRig(t)
302 r.asksBeforeMerging()
303 base, cand := strings.Repeat("1", 40), strings.Repeat("2", 40)
304 id, d := r.approvedWithPreview("missing-header", base, cand, true)
305 if d == nil {
306 t.Fatal("missing preview dispatch")
307 }
308 r.built("header-built", d, digestA)
309 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}})
310 page := r.get(r.inst.Cookie(), "/tasks/"+id+"/preview", 200)
311 if !strings.Contains(page, "Open this preview without the safety header?") || strings.Contains(page, "<iframe") {
312 t.Fatal("unsafe preview opened without tap", page)
313 }
314 form := url.Values{"step": {d.StepID}, "attempt": {itoa(int(d.Attempt))}, "digest": {digestA}, "person": {"forged@example.com"}}
315 principal, err := r.inst.Store.AuthenticateRunner(r.ctx, r.rig.runner)
316 if err != nil {
317 t.Fatal(err)
318 }
319 if err := r.inst.DB.G.Exec("UPDATE members SET role='member' WHERE address=?", principal.Person).Error; err != nil {
320 t.Fatal(err)
321 }
322 r.get(r.inst.Cookie(), "/tasks/"+id+"/preview", 403)
323 if code, _ := r.post(r.inst.Cookie(), "/tasks/"+id+"/preview", form); code != 403 {
324 t.Fatal("member granted preview", code)
325 }
326 if err := r.inst.DB.G.Exec("UPDATE members SET role='owner' WHERE address=?", principal.Person).Error; err != nil {
327 t.Fatal(err)
328 }
329 if code, _ := r.post(r.inst.Cookie(), "/tasks/"+id+"/preview", form); code != 303 {
330 t.Fatal("owner tap refused", code)
331 }
332 next := r.previewDispatch(cand)
333 if next == nil || next.PreviewUnsafeDigest != digestA {
334 t.Fatalf("tap not bound in dispatch: %+v", next)
335 }
336 if r.audits("preview.unsafe") != 1 {
337 t.Fatal("tap not audited")
338 }
339}
340