oficina / equipo Public

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

Plain git — no account needed to clone.

Download

Download this file

1package plan3test
2
3import (
4 "context"
5 "crypto/ed25519"
6 "crypto/rand"
7 "encoding/base64"
8 "encoding/json"
9 "fmt"
10 "io"
11 "net/http/httptest"
12 "net/url"
13 "os"
14 "path/filepath"
15 "regexp"
16 "strings"
17 "testing"
18 "time"
19
20 "amadan.net/oficina/equipo/internal/equipo"
21 "amadan.net/oficina/equipo/internal/equipo/personapi"
22 "amadan.net/oficina/equipo/internal/runner"
23 "amadan.net/oficina/equipo/internal/runner/provider"
24 runnersetup "amadan.net/oficina/equipo/internal/runner/setup"
25 "amadan.net/oficina/equipo/internal/runnerproto"
26 "amadan.net/oficina/equipo/internal/taskplan"
27)
28
29func TestCoordinatorAcceptance3B(t *testing.T) {
30 t.Run("onboarding_to_plan", acceptanceOnboarding)
31 t.Run("sourced_recommendation", func(t *testing.T) { planReadDelivery(t, false) })
32 t.Run("device_answer", acceptanceDeviceAnswer)
33}
34
35func acceptanceOnboarding(t *testing.T) {
36 f := newFixture(t)
37 in, secret := issueInvite(t, f, invitee.Address)
38 inviteSession(t, f, invitee)
39 request := func(method, path, body, key, rev string) *httptest.ResponseRecorder {
40 t.Helper()
41 w := apiRequest(t, f, invitee, method, "/api/v1"+path, body, key, rev)
42 expectHTTP(t, w, 200)
43 return w
44 }
45 request("POST", "/invites/"+in.ID+"/accept", jsonBody(t, personapi.AcceptInviteInput{Secret: secret}), "accept", `"1"`)
46 welcome := request("POST", "/onboarding/advance", `{"step":"welcome"}`, "welcome", `"1"`)
47 // A new application/router resumes persisted setup, including lost-response replay.
48 notificationRouter(t, f, equipo.NewStore(f.DB))
49 replay := request("POST", "/onboarding/advance", `{"step":"welcome"}`, "welcome", `"1"`)
50 if welcome.Body.String() != replay.Body.String() {
51 t.Fatal("interrupted onboarding lost its saved result")
52 }
53
54 credential := acceptancePair(t, f, invitee)
55 server := httptest.NewServer(f.Store.RunnerHandler())
56 t.Cleanup(server.Close)
57 journal, err := runner.OpenJournal(ctx, filepath.Join(t.TempDir(), "state", "runner.db"))
58 must(t, err)
59 t.Cleanup(func() { must(t, journal.Close()) })
60 client, err := runner.NewHTTPInstance(server.URL, journal, credential)
61 must(t, err)
62 root := filepath.Join(t.TempDir(), "accounts")
63 saved := map[string]provider.Binding{}
64 for i, family := range []string{"claude", "claude", "codex"} {
65 w := request("POST", "/account-setups", fmt.Sprintf(`{"runner_id":%q,"provider":%q,"label":%q}`, credential.RunnerID, family, fmt.Sprint("Personal ", i)), fmt.Sprint("setup-", i), "")
66 setup := apiValue[map[string]any](t, w)
67 id := setup["id"].(string)
68 if setup["command"] != "equipo-runner account login --setup "+id {
69 t.Fatal("missing interactive setup command", setup)
70 }
71 binary := acceptanceLoginCLI(t, family, fmt.Sprintf("account-%d@example.test", i))
72 driver := provider.NewLoginDriver(provider.LoginOptions{ClaudePath: binary, CodexPath: binary, Input: strings.NewReader("TERMINAL-SECRET\n"), Output: io.Discard, ErrorOutput: io.Discard})
73 login := &runnersetup.AccountLogin{Root: root, RunnerID: credential.RunnerID, Instance: client, Driver: driver,
74 Probe: driver.(interface {
75 Probe(context.Context, provider.Binding) (provider.Identity, error)
76 }).Probe,
77 Save: func(_ context.Context, s runnerproto.AccountSetup, b provider.Binding) error {
78 if s.RunnerID != credential.RunnerID || b.ID != id || b.AccountID != fmt.Sprintf("account-%d@example.test", i) {
79 return fmt.Errorf("wrong personal identity")
80 }
81 saved[id] = b
82 return nil
83 },
84 }
85 must(t, runnersetup.RunAccountLogin(ctx, login, id))
86 result := request("GET", "/account-setups/"+id, "", "", "")
87 if apiValue[map[string]any](t, result)["state"] != "connected" {
88 t.Fatal("terminal login not reported")
89 }
90 expectHTTP(t, apiRequest(t, f, owner, "GET", "/api/v1/account-setups/"+id, "", "", ""), 404)
91 }
92 events, err := journal.Pending(ctx, 100)
93 must(t, err)
94 if len(events) != 0 {
95 t.Fatal("terminal login entered the runner journal", len(events))
96 }
97 homes, identities := map[string]bool{}, map[string]bool{}
98 for _, b := range saved {
99 stat, err := os.Stat(b.Home)
100 must(t, err)
101 if stat.Mode().Perm() != 0700 || homes[b.Home] || identities[b.Expected.HomeID] || b.Expected.HomeID == "" {
102 t.Fatal("accounts share a home or identity")
103 }
104 homes[b.Home], identities[b.Expected.HomeID] = true, true
105 }
106 if len(saved) != 3 || f.count(t, "SELECT count(*) FROM connections WHERE person=?", invitee.Address) != 3 {
107 t.Fatal("login replaced a personal account")
108 }
109 // Sign-in is not a certificate. Ordinary runner reports must still prove availability.
110 connections := request("GET", "/connections", "", "", "")
111 for _, secret := range []string{"TERMINAL-SECRET", "CREDENTIAL-SECRET", root} {
112 if strings.Contains(connections.Body.String(), secret) {
113 t.Fatal("credential leaked in person API")
114 }
115 if f.count(t, "SELECT count(*) FROM audit_events WHERE CAST(record_id AS TEXT) LIKE ?", "%"+secret+"%") != 0 {
116 t.Fatal("credential leaked in audit")
117 }
118 }
119
120 state, err := f.Store.Onboarding(ctx, invitee)
121 must(t, err)
122 _, err = f.Store.ChooseOnboardingProvider(ctx, invitee, "claude", equipo.Mutation{RequestID: "provider", Revision: state.Revision})
123 must(t, err)
124 currentState := request("GET", "/onboarding", "", "", "")
125 request("POST", "/onboarding/advance", `{"step":"account"}`, "account", currentState.Header().Get("ETag"))
126 currentState = request("GET", "/onboarding", "", "", "")
127 expectHTTP(t, apiRequest(t, f, invitee, "POST", "/api/v1/onboarding/advance", `{"step":"runner"}`, "uncertified-runner", currentState.Header().Get("ETag")), 409)
128 // Availability is simulated only after proving sign-in itself grants none.
129 var rows []struct{ ID, ReportsJSON string }
130 must(t, f.DB.G.Table("connections").Where("person=?", invitee.Address).Find(&rows).Error)
131 for _, row := range rows {
132 var reports []equipo.ConnectionReport
133 must(t, json.Unmarshal([]byte(row.ReportsJSON), &reports))
134 for i := range reports {
135 reports[i].Available = true
136 reports[i].ReadIsolation = true
137 }
138 raw, err := json.Marshal(reports)
139 must(t, err)
140 f.exec(t, "UPDATE connections SET reports_json=?,last_seen=? WHERE id=?", string(raw), time.Now(), row.ID)
141 }
142 request("POST", "/onboarding/advance", `{"step":"runner"}`, "runner", currentState.Header().Get("ETag"))
143
144 installed := apiValue[personapi.Specialist](t, request("POST", "/templates/qa/install", `{"version":1}`, "specialist", ""))
145 installed.Name = "Our acceptance QA"
146 request("PATCH", "/specialists/"+installed.ID, jsonBody(t, installed.SpecialistInput), "specialist-edit", `"1"`)
147 request("GET", "/specialists/"+installed.ID+"/template-diff", "", "", "")
148 current := apiValue[personapi.Specialist](t, request("GET", "/specialists/"+installed.ID, "", "", ""))
149 if current.Name != installed.Name || current.Revision != 2 {
150 t.Fatal("template preview silently updated specialist")
151 }
152 pb := apiValue[personapi.Playbook](t, request("POST", "/templates/playbook_bug/install", `{"version":1}`, "playbook", ""))
153 pb.Name, pb.Kind = "Bounded feature", "feature"
154 pb.Steps[0].Action, pb.Steps[0].Specialist = "scope", "product"
155 request("PATCH", "/playbooks/"+pb.ID, jsonBody(t, pb.PlaybookInput), "playbook-edit", `"1"`)
156 request("GET", "/playbooks/"+pb.ID+"/template-diff", "", "", "")
157 now := apiValue[personapi.Playbook](t, request("GET", "/playbooks/"+pb.ID, "", "", ""))
158 if now.Name != pb.Name || now.Revision != 2 {
159 t.Fatal("template preview silently updated playbook")
160 }
161 task := f.createTask(t)
162 must(t, f.DB.G.Create(&equipo.DecisionOwner{ProjectID: task.ProjectID, Decision: "work", Address: invitee.Address}).Error)
163 f.planConnections(t, task.ProjectID)
164 notificationRouter(t, f, f.Store)
165 var ids []string
166 for _, row := range rows {
167 var reports []equipo.ConnectionReport
168 must(t, json.Unmarshal([]byte(row.ReportsJSON), &reports))
169 var template string
170 must(t, f.DB.Writer().QueryRow("SELECT reports_json FROM connections WHERE id=?", reports[0].Provider).Scan(&template))
171 var certified []equipo.ConnectionReport
172 must(t, json.Unmarshal([]byte(template), &certified))
173 certified[0].LocalID = reports[0].LocalID
174 certified[0].Routing.BindingID = reports[0].LocalID
175 b := saved[reports[0].LocalID]
176 certified[0].Routing.AccountID = b.AccountID
177 certified[0].Routing.ObservedAccountID = b.AccountID
178 raw, err := json.Marshal(certified)
179 must(t, err)
180 f.exec(t, "UPDATE connections SET reports_json=? WHERE id=?", string(raw), row.ID)
181 ids = append(ids, row.ID)
182 }
183 rawIDs, err := json.Marshal(ids)
184 must(t, err)
185 f.exec(t, "INSERT INTO connection_choices(person,project_id,revision,connection_ids_json,pinned_id,mode) VALUES(?,?,1,?,'','best_fit')", invitee.Address, task.ProjectID, string(rawIDs))
186 // The project owner chooses the shared default; invitation grants no owner powers.
187 must(t, f.Store.SetPlaybookDefault(ctx, owner, task.ProjectID, taskplan.Feature, pb.ID, equipo.Mutation{RequestID: "default"}))
188 plan, err := f.Store.ProposePlan(ctx, invitee, taskplan.Plan{Kind: taskplan.Feature, ProjectID: task.ProjectID}, equipo.Mutation{RequestID: "feature"})
189 must(t, err)
190 if plan.PlaybookID != pb.ID || plan.PlaybookRevision != 2 {
191 t.Fatal("feature ignored selected playbook")
192 }
193 for _, action := range []string{"review", "checks", "person"} {
194 found := false
195 for _, step := range plan.Steps {
196 if step.Action == action {
197 found = step.Required
198 }
199 }
200 if !found {
201 t.Fatal("mandatory publishing step absent", action)
202 }
203 }
204 request("POST", "/tasks/"+plan.TaskID+"/plan/approve", `{}`, "approve", `"1"`)
205 if f.count(t, "SELECT count(*) FROM notification_outbox WHERE resource_id=? AND resource_revision=1 AND recipient=?", plan.TaskID, invitee.Address) != 0 {
206 t.Fatal("own proposal or approval created a notification")
207 }
208 request("POST", "/tasks/"+plan.TaskID+"/plan/approve", `{}`, "approve", `"1"`)
209 if f.count(t, "SELECT count(*) FROM audit_events WHERE kind='plan.approve' AND actor=?", invitee.Address) != 1 {
210 t.Fatal("approval replay duplicated effect")
211 }
212 request("POST", "/teams/links", `{"origin":"https://other.example.test","name":"Other team"}`, "team-link", "")
213 teams := request("GET", "/teams", "", "", "")
214 if !strings.Contains(teams.Body.String(), "other.example.test") {
215 t.Fatal("remembered team missing")
216 }
217 page := f.get(t, invitee, "/onboarding")
218 expectHTTP(t, page, 200)
219 for _, word := range []string{"Mac", "coming later", "Hosted by Equipo"} {
220 if !strings.Contains(page.Body.String(), word) {
221 t.Fatal("unsupported runner claim", word)
222 }
223 }
224 expectHTTP(t, inviteRequest(t, f, invitee, "POST", "/onboarding/hosted", nil, nil), 404)
225}
226
227func acceptancePair(t *testing.T, f *fixture, actor equipo.Actor) runnerproto.RunnerCredential {
228 t.Helper()
229 pub, key, err := ed25519.GenerateKey(rand.Reader)
230 must(t, err)
231 c, err := f.Store.BeginEnrolment(ctx, base64.RawURLEncoding.EncodeToString(pub), "Acceptance Linux machine")
232 must(t, err)
233 page := f.get(t, actor, "/runners/enrol?user_code="+c.UserCode)
234 if strings.Contains(page.Body.String(), `value="`+c.UserCode+`"`) {
235 t.Fatal("pairing link prefilled typed code")
236 }
237 form := url.Values{"user_code": {c.UserCode}, "action": {"inspect"}}
238 page = inviteRequest(t, f, actor, "POST", "/runners/enrol", form, nil)
239 expectHTTP(t, page, 200)
240 if !strings.Contains(page.Body.String(), "Acceptance Linux machine") || !strings.Contains(page.Body.String(), time.Now().UTC().Format("2 Jan 2006")) {
241 t.Fatal("pairing omitted machine label or server time")
242 }
243 proof := regexp.MustCompile(`name="confirmation" value="([^"]+)"`).FindStringSubmatch(page.Body.String())
244 if len(proof) != 2 {
245 t.Fatal("missing inspected pairing proof")
246 }
247 form.Set("confirmation", proof[1])
248 form.Set("action", "approve")
249 expectHTTP(t, inviteRequest(t, f, actor, "POST", "/runners/enrol", form, nil), 303)
250 p := runnerproto.ExchangeProof{EnrolmentID: c.EnrolmentID, Challenge: c.Challenge, ExchangeNonce: base64.RawURLEncoding.EncodeToString(make([]byte, 32))}
251 p.Signature = base64.RawURLEncoding.EncodeToString(ed25519.Sign(key, runnerproto.EnrolmentProofMessage(c.InstanceID, p)))
252 credential, err := f.Store.ExchangeEnrolment(ctx, c.DeviceSecret, p)
253 must(t, err)
254 if credential.Person != actor.Address {
255 t.Fatal("pairing attached another person")
256 }
257 return credential
258}
259
260func acceptanceDeviceAnswer(t *testing.T) {
261 f, _, _, _, q := nativeConversationFixture(t)
262 notificationRouter(t, f, f.Store)
263 device := approvedDevice(t, f)
264 sub := notificationSubscription(t, f, device)
265 page := notificationFeed(t, f, device, sub.Cursor)
266 var eventID string
267 for _, n := range page.Items {
268 if n.ResourceID == q.ID {
269 eventID = n.ID
270 }
271 }
272 if eventID == "" {
273 t.Fatal("native question notification absent")
274 }
275 current := deviceRequest(t, f, device.Token, "GET", "/api/v1/questions/"+q.ID, "", "", "")
276 expectHTTP(t, current, 200)
277 body := `{"kind":"native","behavior":"allow","updated_input":{"answers":{"Which?":"Blue"}}}`
278 for range 2 {
279 expectHTTP(t, deviceRequest(t, f, device.Token, "POST", "/api/v1/questions/"+q.ID+"/answer", body, "answer", current.Header().Get("ETag")), 200)
280 }
281 if f.count(t, "SELECT count(*) FROM audit_events WHERE kind='question.answer' AND record_id=?", q.ID) != 1 {
282 t.Fatal("device answer effect duplicated")
283 }
284 again := notificationFeed(t, f, device, sub.Cursor)
285 if len(again.Items) != len(page.Items) {
286 t.Fatal("answer duplicated question notification")
287 }
288 f.exec(t, "UPDATE notification_subscriptions SET expires_at=? WHERE id=?", time.Now().Add(-time.Second), sub.ID)
289 expectHTTP(t, deviceRequest(t, f, device.Token, "GET", "/api/v1/notifications?cursor="+url.QueryEscape(sub.Cursor), "", "", ""), 410)
290 if f.Store.AllowNotificationSubscription(ctx, owner, sub.ID) {
291 t.Fatal("expired subscription remains live")
292 }
293}
294
295func acceptanceLoginCLI(t *testing.T, name, account string) string {
296 t.Helper()
297 binary := filepath.Join(t.TempDir(), name)
298 script := `#!/bin/sh
299set -eu
300umask 077
301case "$*" in
302 '--version') echo 'VERSION'; exit 0 ;;
303 'auth login --help'|'login --device-auth --help') exit 0 ;;
304 'auth status --json') test -f "$HOME/.credentials.json"; printf '%s' '{"loggedIn":true,"authMethod":"claude.ai","email":"ACCOUNT"}'; exit 0 ;;
305 'app-server --strict-config --listen stdio://')
306 test -f "$HOME/auth.json"
307 IFS= read -r line
308 printf '{"id":"1","result":{"userAgent":"equipo/0.165.0 fixture","codexHome":"%s"}}\n' "$CODEX_HOME"
309 IFS= read -r line
310 IFS= read -r line
311 printf '%s\n' '{"id":"2","result":{"account":{"type":"chatgpt","email":"ACCOUNT"}}}'
312 exit 0 ;;
313 'auth login') test "$HOME" = "$CLAUDE_CONFIG_DIR"; test "$HOME" = "$CLAUDE_SECURESTORAGE_CONFIG_DIR"; file=.credentials.json ;;
314 'login --device-auth') test "$HOME" = "$CODEX_HOME"; file=auth.json ;;
315 *) exit 9 ;;
316esac
317IFS= read -r code
318test "$code" = TERMINAL-SECRET
319printf '%s' '{"token":"CREDENTIAL-SECRET"}' > "$HOME/$file"
320`
321 version := "codex-cli 0.165.0"
322 if name == "claude" {
323 version = "2.1.312 (Claude Code)"
324 }
325 must(t, os.WriteFile(binary, []byte(strings.NewReplacer("VERSION", version, "ACCOUNT", account).Replace(script)), 0700))
326 return binary
327}
328