package thintest import ( "net/http" "regexp" "slices" "strings" "testing" "time" "amadan.net/oficina/equipo/internal/equipo" "amadan.net/oficina/equipo/internal/wire" ) // sitesOn says hello again as a primary at protocol that is paired with // a CARLOS devbox for previews and, when sites, a current carlos signed in // to Carloku owning account oficina (protocol 31: places). With sites, a // merge then confirms that place on its place card (placeOnMerge), so a // test about the publish card meets one. func (r *toolRig) sitesOn(protocol int, sites bool) { r.t.Helper() hello := primaryAt(toolHello(r.runner.Welcome.Generation), protocol) hello.Capabilities.Previews, hello.Capabilities.PreviewHost = true, &wire.PreviewHost{Kind: wire.PreviewHostDevbox, Domain: "docs-t1.example.ts.net"} if sites { hello.Capabilities.Tools = &wire.ToolHealth{Scanner: wire.ToolHealthy, Carlos: wire.CarlosOK, CarlosVersion: "v0.43.3"} hello.Capabilities.Reach = &wire.Reach{Logins: []wire.ReachLogin{{Console: wire.FlagshipConsole, Accounts: []wire.ReachAccount{{Name: "oficina", Sqid: "bcdfg"}, {Name: "paulca", Sqid: "kmnpq"}}}}, Deploys: []wire.ReachDeploy{}} r.placeOnMerge = protocol >= wire.ProtocolPlaces } if err := r.runner.Send(r.ctx, "h-sites-"+itoa(int(time.Now().UnixNano()%1e9)), wire.FrameHello, hello); err != nil { r.t.Fatal(err) } if refused := r.lease(r.runner, "h-sites-ping", wire.LeaseCheck{}); refused != "" { r.t.Fatalf("ping refused %q", refused) } } // websiteReady takes a website task to Review's approval on cand with no // checks found (so its merge is asked), Review saying the candidate has a // static site config when has; it returns the task and its merge card. func (r *toolRig) websiteReady(key, title, base, cand string, has bool) (string, wire.Card) { r.t.Helper() id := r.websiteJudged(key, title, base, cand, has) var card wire.Card r.wait("the merge card", func(c *Conversation) bool { for _, k := range c.Cards { if k.Kind == wire.CardMerge && k.TaskID == id { card = k return true } } return false }) return id, card } // websiteJudged is websiteReady up to Review's approval: the task. func (r *toolRig) websiteJudged(key, title, base, cand string, has bool) string { r.t.Helper() id, _ := r.pushed(key, title, base, cand) r.expect(wire.FrameWatchMerge) c := r.dispatched(wire.SpecialistChecks, base, cand, 0) r.checks(key+"-c", c, wire.ChecksNone, nil, "", "") 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 } // mergeFromCard answers the merge card Merge and reports the hub's merge // of cand as sha. func (r *toolRig) mergeFromCard(key, id, base, cand, sha string) { r.t.Helper() card := r.cardOf(id) if _, err := r.client.Answer(r.ctx, card.ID, wire.ChoiceMerge, card.Revision); err != nil { r.t.Fatalf("merge %v", err) } m := r.dispatched(wire.SpecialistMerge, base, cand, 0) r.mergedStep(key, m, sha) r.wait("done", func(c *Conversation) bool { return c.Tasks[id].Stage == wire.StageDone }) } // publishCard is the task's newest publish card, if any. func (r *toolRig) publishCard(id string) (wire.Card, bool) { r.t.Helper() snap, err := r.client.Snapshot(r.ctx) if err != nil { r.t.Fatal(err) } var out wire.Card found := false for _, c := range snap.Cards { if c.Kind == wire.CardPublish && c.TaskID == id { out, found = c, true } } return out, found } func (r *toolRig) publishDispatch() *wire.DispatchCommand { r.t.Helper() for { _, body := r.expect(wire.FrameDispatch) if d := body.(*wire.DispatchCommand); d.Specialist == wire.SpecialistPublish { return d } } } func (r *toolRig) publishReport(key string, d *wire.DispatchCommand, state string, p *wire.PublishResult) { r.t.Helper() r.step(key, wire.StepReport{TaskID: d.TaskID, StepID: d.StepID, Attempt: d.Attempt, State: state, CandidateSHA: d.CandidateSHA, Termination: state != wire.StepRunning, Findings: []wire.Finding{}, Publish: p}) } // TestContractPublishSite: the website's preview reaches its merge card // once it is up (the card raised first gets a new revision with it). // After Equipo merges it, a separate publish card asks its creator, and // only they answer it; Publish places one publish step on their primary // for exactly the merged commit and the app derived from the project. // Its start and its deploy check are decided for that commit and the // export reported built; only a report for this app, this export and a // URL on the app's own host counts; the task then carries the public URL // and the coordinator says it in one line. Every step is audited. func TestContractPublishSite(t *testing.T) { r := newToolRigAt(t, wire.ProtocolCurrent) r.sitesOn(wire.ProtocolCurrent, true) ctx := r.ctx base, cand, merged := strings.Repeat("1", 40), strings.Repeat("2", 40), strings.Repeat("e", 40) id, card := r.websiteReady("w", "Quick website", base, cand, true) if card.PreviewURL != "" { t.Fatalf("a preview link before the preview: %+v", card) } pv := r.previewDispatch(cand) if pv == nil { t.Fatal("no preview") } r.built("w-pv-built", pv, digestA) link := "https://eq-" + id + ".docs-t1.example.ts.net/" r.previewDone("w-pv-done", pv, wire.PreviewResult{Phase: wire.PreviewDone, App: "eq-" + id, URL: link, Digest: digestA, Outcome: wire.PreviewDeployed}) after := r.cardOf(id) if after.PreviewURL != link || after.Revision <= card.Revision || after.State != wire.CardOpen { t.Fatalf("merge card after the preview %+v", after) } if k, _ := r.client.Task(ctx, id); k.PreviewURL != r.inst.URL+"/tasks/"+id+"/preview" || k.Site != nil { t.Fatalf("task preview %q site %+v", k.PreviewURL, k.Site) } r.mergeFromCard("w-m", id, base, cand, merged) var pub wire.Card r.wait("the publish card", func(c *Conversation) bool { for _, k := range c.Cards { if k.Kind == wire.CardPublish && k.TaskID == id { pub = k return true } } return false }) shape(t, "api/card-publish.json", pub) // The app is minted for the project and named on the card. if pub.Site == nil || !regexp.MustCompile(`^site-sample-[a-z2-7]{6}$`).MatchString(pub.Site.App) { t.Fatalf("minted app %+v", pub.Site) } app := pub.Site.App if pub.State != wire.CardOpen || pub.Name != "Quick website" || !slices.Equal(pub.Options, []string{wire.ChoicePublish, wire.ChoiceNotNow}) || pub.Site == nil || *pub.Site != (wire.CardSite{App: app, SHA: merged, State: wire.SiteAsked}) || pub.Question != "Publish Quick website to "+app+" on Carloku in account oficina? This first publish creates the app and a deploy key for it using your CARLOS login on your runner." { t.Fatalf("publish card %+v %+v", pub, pub.Site) } k, _ := r.client.Task(ctx, id) if k.PreviewURL != "" || k.Site == nil || k.Site.State != wire.SiteAsked || k.Site.App != app || k.Site.SHA != merged { t.Fatalf("merged task preview %q site %+v", k.PreviewURL, k.Site) } if r.heldKinds(wire.FrameDispatch) != 0 { t.Fatal("published before anyone answered") } // Only the creator answers; a stale revision or another choice is refused. mate := personToolRig(t, r, "mate@example.com", equipo.RoleOwner) if _, err := mate.client.Answer(ctx, pub.ID, wire.ChoicePublish, pub.Revision); Status(err) != http.StatusNotFound { t.Fatalf("teammate answered: %v", err) } if _, err := r.client.Answer(ctx, pub.ID, wire.ChoicePublish, pub.Revision+1); Status(err) != http.StatusConflict { t.Fatalf("stale answer: %v", err) } if _, err := r.client.Answer(ctx, pub.ID, "deploy", pub.Revision); Status(err) != http.StatusUnprocessableEntity { t.Fatalf("other choice: %v", err) } out, err := r.client.Answer(ctx, pub.ID, wire.ChoicePublish, pub.Revision) if err != nil || out.Card.State != wire.CardAnswered || out.Card.Choice != wire.ChoicePublish || out.Card.Site == nil || out.Card.Site.State != wire.SitePublishing { t.Fatalf("publish %+v %v", out.Card, err) } d := r.publishDispatch() dest := wire.SiteDestination(wire.FlagshipConsole, "bcdfg", "oficina", app) if d.CandidateSHA != merged || d.Person != Owner || d.Repo != "amadan.net/oficina/sample" || d.Publish == nil || d.Attempt != 1 || !strings.HasPrefix(d.Publish.Place, "pl_") || !regexp.MustCompile(`^eq-sample-[a-z2-7]{6}-[a-z2-7]{4}$`).MatchString(d.Publish.DeployName) { t.Fatalf("publish dispatch %+v %+v", d, d.Publish) } if want := (wire.PublishDispatch{App: app, Into: "main", Console: wire.FlagshipConsole, Account: "bcdfg", AccountName: "oficina", Place: d.Publish.Place, PlaceRevision: 1, BindingRevision: 1, Destination: dest, Mode: wire.SiteSetup, DeployName: d.Publish.DeployName}); *d.Publish != want { t.Fatalf("publish dispatch %+v\nwant %+v", *d.Publish, want) } if _, err := r.client.Answer(ctx, pub.ID, wire.ChoicePublish, out.Card.Revision); Status(err) != http.StatusConflict { t.Fatalf("answered twice: %v", err) } if refused := r.lease(r.runner, "w-start", wire.LeaseCheck{StepID: d.StepID, Attempt: d.Attempt}); refused != "" { t.Fatalf("start refused %q", refused) } if refused := r.lease(r.runner, "w-early", wire.LeaseCheck{StepID: d.StepID, Attempt: d.Attempt, Purpose: wire.LeasePurposePublish, Digest: digestA, Destination: dest}); refused != wire.RefusedPublishNotBuilt { t.Fatalf("deploy before built: %q", refused) } r.publishReport("w-built", d, wire.StepRunning, &wire.PublishResult{Phase: wire.PublishBuilt, Digest: digestA, Files: 2, Bytes: 40}) if refused := r.lease(r.runner, "w-other", wire.LeaseCheck{StepID: d.StepID, Attempt: d.Attempt, Purpose: wire.LeasePurposePublish, Digest: digestB, Destination: dest}); refused == "" { t.Fatal("another export's deploy allowed") } if refused := r.lease(r.runner, "w-elsewhere", wire.LeaseCheck{StepID: d.StepID, Attempt: d.Attempt, Purpose: wire.LeasePurposePublish, Digest: digestA, Destination: wire.SiteDestination(wire.FlagshipConsole, "kmnpq", "paulca", app)}); refused == "" { t.Fatal("a deploy to another destination allowed") } if refused := r.lease(r.runner, "w-mint-early", wire.LeaseCheck{StepID: d.StepID, Attempt: d.Attempt, Purpose: wire.LeasePurposeMint, Digest: digestA, Destination: dest}); refused == "" { t.Fatal("a setup's mint allowed before its deploy check") } if refused := r.lease(r.runner, "w-preview", wire.LeaseCheck{StepID: d.StepID, Attempt: d.Attempt, Purpose: wire.LeasePurposePreview, Digest: digestA}); refused == "" { t.Fatal("a preview check allowed on a publish step") } if refused := r.lease(r.runner, "w-deploy", wire.LeaseCheck{StepID: d.StepID, Attempt: d.Attempt, Purpose: wire.LeasePurposePublish, Digest: digestA, Destination: dest}); refused != "" { t.Fatalf("deploy refused %q", refused) } if refused := r.lease(r.runner, "w-mint", wire.LeaseCheck{StepID: d.StepID, Attempt: d.Attempt, Purpose: wire.LeasePurposeMint, Digest: digestA, Destination: dest}); refused != "" { t.Fatalf("mint refused %q", refused) } site := "https://" + app + ".bds.oncarlos.com/" for name, p := range map[string]wire.PublishResult{ "another app": {Phase: wire.PublishDone, App: "site-other", URL: "https://site-other.bds.oncarlos.com/", Digest: digestA, Outcome: wire.PublishPublished}, "another export": {Phase: wire.PublishDone, App: app, URL: site, Digest: digestB, Outcome: wire.PublishPublished}, "a foreign URL": {Phase: wire.PublishDone, App: app, URL: "https://evil.example/", Digest: digestA, Outcome: wire.PublishPublished}, "no outcome": {Phase: wire.PublishDone, App: app, URL: site, Digest: digestA}, } { r.publishReport("w-"+strings.ReplaceAll(name, " ", "-"), d, wire.StepDone, &p) if k, _ := r.client.Task(ctx, id); k.Steps[len(k.Steps)-1].State == wire.StepDone || k.Site.State != wire.SitePublishing { t.Fatalf("%s counted: %+v", name, k.Site) } } r.publishReport("w-published", d, wire.StepDone, &wire.PublishResult{Phase: wire.PublishDone, App: app, URL: site, Version: "s-eeeeeeeeeeee-x-1", Digest: digestA, Outcome: wire.PublishPublished, DeployHeld: true}) k, _ = r.client.Task(ctx, id) shape(t, "api/task-published.json", k) last := k.Steps[len(k.Steps)-1] if k.Stage != wire.StageDone || k.Site == nil || k.Site.State != wire.SitePublished || k.Site.URL != site || k.Site.At == nil || last.Specialist != wire.SpecialistPublish || last.Publish == nil || last.Publish.URL != site || last.Publish.Files != 2 { t.Fatalf("published task %+v step %+v", k.Site, last.Publish) } want := "Published [Quick website](/tasks/" + id + ") at " + site + "." r.wait("the coordinator's line", func(c *Conversation) bool { rs := c.Replies() return len(rs) > 0 && rs[len(rs)-1].Text == want }) if c, _ := r.publishCard(id); c.Site == nil || c.Site.State != wire.SitePublished || c.Site.URL != site { t.Fatalf("card after publishing %+v", c.Site) } for kind, n := range map[string]int{"publish.requested": 1, "publish.approved": 1, "publish.built": 1, "publish.published": 1} { if got := r.audits(kind); got != n { t.Fatalf("%s audited %d times", kind, got) } } if r.audits("place.proposed") != 1 || r.audits("place.confirmed") != 1 || r.audits("site.create_allowed") != 1 || r.audits("site.deploy_mint_allowed") != 1 { t.Fatal("the place and the site's setup were not audited") } if r.audits("publish.authorize") != 7 { t.Fatalf("authorize audited %d times", r.audits("publish.authorize")) } if page := r.get(r.inst.Cookie(), "/conversation", 200); !strings.Contains(page, `equipo-card="publish"`) || !strings.Contains(page, "Publishing.") { t.Fatalf("conversation page lacks the publish card") } } // TestContractPublishNotOffered: nothing is offered for a merged task // whose Review found no static site config, nor on a primary that does // not say it can publish sites (paired with none, or below protocol 16). func TestContractPublishNotOffered(t *testing.T) { r := newToolRigAt(t, wire.ProtocolCurrent) r.sitesOn(wire.ProtocolCurrent, true) base := strings.Repeat("1", 40) id, _ := r.websiteReady("n", "Fix the README", base, strings.Repeat("2", 40), false) r.mergeFromCard("n-m", id, base, strings.Repeat("2", 40), strings.Repeat("e", 40)) r.syncNow("n-sync") if c, ok := r.publishCard(id); ok { t.Fatalf("offered without a site: %+v", c) } off := newToolRigAt(t, wire.ProtocolCurrent) off.sitesOn(wire.ProtocolCurrent, false) id2, _ := off.websiteReady("o", "Quick website", base, strings.Repeat("3", 40), true) off.previewDispatch(strings.Repeat("3", 40)) off.mergeFromCard("o-m", id2, base, strings.Repeat("3", 40), strings.Repeat("f", 40)) off.syncNow("o-sync") if c, ok := off.publishCard(id2); ok { t.Fatalf("offered on a primary with no site host: %+v", c) } old := newToolRigAt(t, wire.ProtocolReadings) old.sitesOn(wire.ProtocolReadings, false) id3, _ := old.websiteReady("p", "Quick website", base, strings.Repeat("4", 40), true) old.previewDispatch(strings.Repeat("4", 40)) old.mergeFromCard("p-m", id3, base, strings.Repeat("4", 40), strings.Repeat("d", 40)) old.syncNow("p-sync") if c, ok := old.publishCard(id3); ok { t.Fatalf("offered on a protocol 15 primary: %+v", c) } } // TestContractPublishNotNow: Not now publishes nothing and says so on the // task; the creator's publish is then refused by the card. func TestContractPublishNotNow(t *testing.T) { r := newToolRigAt(t, wire.ProtocolCurrent) r.sitesOn(wire.ProtocolCurrent, true) base, cand := strings.Repeat("1", 40), strings.Repeat("2", 40) id, _ := r.websiteReady("x", "Quick website", base, cand, true) r.previewDispatch(cand) r.mergeFromCard("x-m", id, base, cand, strings.Repeat("e", 40)) var pub wire.Card r.wait("the publish card", func(c *Conversation) bool { for _, k := range c.Cards { if k.Kind == wire.CardPublish && k.TaskID == id { pub = k return true } } return false }) out, err := r.client.Answer(r.ctx, pub.ID, wire.ChoiceNotNow, pub.Revision) if err != nil || out.Card.State != wire.CardAnswered || out.Card.Site.State != wire.SiteDeclined { t.Fatalf("not now %+v %v", out.Card, err) } if k, _ := r.client.Task(r.ctx, id); k.Site == nil || k.Site.State != wire.SiteDeclined { t.Fatalf("declined site %+v", k.Site) } if r.heldKinds(wire.FrameDispatch) != 0 || r.audits("publish.declined") != 1 { t.Fatal("not now published, or was not audited") } } // TestContractPublishNameTaken: a publish the runner refused because the // account already holds the app's name is a failure the card shows; the // creator is told, and not asked again. func TestContractPublishNameTaken(t *testing.T) { r := newToolRigAt(t, wire.ProtocolCurrent) r.sitesOn(wire.ProtocolCurrent, true) base, cand := strings.Repeat("1", 40), strings.Repeat("2", 40) id, _ := r.websiteReady("y", "Quick website", base, cand, true) r.previewDispatch(cand) r.mergeFromCard("y-m", id, base, cand, strings.Repeat("e", 40)) var pub wire.Card r.wait("the publish card", func(c *Conversation) bool { for _, k := range c.Cards { if k.Kind == wire.CardPublish && k.TaskID == id { pub = k return true } } return false }) if _, err := r.client.Answer(r.ctx, pub.ID, wire.ChoicePublish, pub.Revision); err != nil { t.Fatal(err) } d := r.publishDispatch() r.publishReport("y-built", d, wire.StepRunning, &wire.PublishResult{Phase: wire.PublishBuilt, Digest: digestA, Files: 2, Bytes: 40}) r.step("y-taken", wire.StepReport{TaskID: d.TaskID, StepID: d.StepID, Attempt: d.Attempt, State: wire.StepFailed, Reason: "publish_app_taken", CandidateSHA: d.CandidateSHA, Termination: true, Findings: []wire.Finding{}}) c, _ := r.publishCard(id) if c.ID != pub.ID || c.Site == nil || c.Site.State != wire.SiteFailed { t.Fatalf("card after a taken name %+v %+v", c, c.Site) } if k, _ := r.client.Task(r.ctx, id); k.Site == nil || k.Site.State != wire.SiteFailed { t.Fatalf("task site %+v", k.Site) } want := "Could not publish [Quick website](/tasks/" + id + "): Carloku already has an app called " + d.Publish.App + ", so I left it alone." r.wait("the coordinator's line", func(c *Conversation) bool { rs := c.Replies() return len(rs) > 0 && rs[len(rs)-1].Text == want }) }