package equipotest import ( "context" "errors" "net/http" "net/http/httptest" "net/url" "strconv" "strings" "testing" "time" "amadan.net/oficina/equipo/internal/equipo" "amadan.net/oficina/equipo/internal/equipo/team" ) var connectionContext = context.Background() func connectionReport(local, provider, family, model string) equipo.ConnectionReport { version := "2.1.312" if provider == "codex" { version = "0.165.0" } return equipo.ConnectionReport{LocalID: local, Provider: provider, ProviderVersion: version, LauncherVersion: "direct-v2", BwrapVersion: "0.11.0", PolicyVersion: "policy-v2", Family: family, Model: model, AccountLabel: "shared@example.com", Kind: "subscription", Available: true, ReadIsolation: true, IsolationConfigHash: strings.Repeat("a", 64), Routing: equipo.ConnectionRouting{BindingID: local, AccountID: "opaque-" + local, ObservedAccountID: "opaque-" + local, CredentialHomeHash: strings.Repeat("b", 64), AccountPinned: true, NoFailover: true, TimelineRecovery: true, ProcessOwnership: true}} } func connectionTuple(r equipo.ConnectionReport) team.IsolationTuple { return team.IsolationTuple{Provider: r.Provider, ProviderVersion: r.ProviderVersion, LauncherVersion: r.LauncherVersion, BwrapVersion: r.BwrapVersion, PolicyVersion: r.PolicyVersion, IsolationConfigHash: r.IsolationConfigHash} } type connectionFixture struct { enrolFixture principal equipo.RunnerPrincipal project equipo.Project reports []equipo.ConnectionReport ids map[string]string } func connectionStore(t *testing.T) connectionFixture { t.Helper() f := enrolStore(t) reports := []equipo.ConnectionReport{connectionReport("claude", "claude", "claude", "sonnet"), connectionReport("codex", "codex", "gpt", "gpt-5")} f.s = equipo.NewStore(f.d, equipo.WithRunnerClock(f.clock), equipo.WithVerifiedIsolationTuples([]team.IsolationTuple{connectionTuple(reports[0]), connectionTuple(reports[1])})) setMember(t, f.s, "member@example.com", equipo.RoleMember, true) a, err := f.s.SaveAccount(connectionContext, ownerActor, equipo.Account{Label: "Connections"}) if err != nil { t.Fatal(err) } project := saveProject(t, f.s, projectInput(a), projectOwners(), "connection-project") code, key := beginDevice(t, f.s) approveDevice(t, f.s, code, ownerAddress) credential := claimDevice(t, f.s, code, key) p, err := f.s.AuthenticateRunner(connectionContext, credential.Token) if err != nil { t.Fatal(err) } if err := f.s.ReportConnections(connectionContext, p, reports); err != nil { t.Fatal(err) } rows, err := f.s.Connections(connectionContext, ownerActor) if err != nil { t.Fatal(err) } ids := map[string]string{} for _, row := range rows { ids[row.LocalID] = row.ID } return connectionFixture{f, p, project, reports, ids} } func (f connectionFixture) choice(t *testing.T, pin string) { t.Helper() if err := f.s.SaveConnectionChoice(connectionContext, ownerActor, equipo.ConnectionChoice{ProjectID: f.project.ID, ConnectionIDs: []string{f.ids["claude"], f.ids["codex"]}, PinnedID: pin}); err != nil { t.Fatal(err) } } func (f connectionFixture) selectOK(t *testing.T, specialist, excluded string) equipo.Selection { t.Helper() result, err := f.s.SelectConnection(connectionContext, ownerAddress, f.project.ID, specialist, excluded) if err != nil { t.Fatal(err) } return result } func (f connectionFixture) denied(t *testing.T, specialist, excluded string) { t.Helper() r, err := f.s.SelectConnection(connectionContext, ownerAddress, f.project.ID, specialist, excluded) if err == nil || r.ConnectionID != "" { t.Fatalf("ineligible selection accepted: %+v %v", r, err) } } func TestConnectionsBelongToPersonAndMachine(t *testing.T) { f := connectionStore(t) f.choice(t, "") code, key := beginDevice(t, f.s) approveDevice(t, f.s, code, "member@example.com") c := claimDevice(t, f.s, code, key) p, err := f.s.AuthenticateRunner(connectionContext, c.Token) if err != nil { t.Fatal(err) } if err = f.s.ReportConnections(connectionContext, p, f.reports); err != nil { t.Fatal(err) } rows, err := f.s.Connections(connectionContext, equipo.Actor{Address: p.Person}) if err != nil || len(rows) != 2 { t.Fatalf("personal rows %v %v", rows, err) } for _, r := range rows { if r.Person != p.Person || r.RunnerID != p.RunnerID || r.ID == f.ids[r.LocalID] { t.Fatal("shared label or local ID shared identity") } } if err = f.s.SaveConnectionChoice(connectionContext, equipo.Actor{Address: p.Person}, equipo.ConnectionChoice{ProjectID: f.project.ID, ConnectionIDs: []string{f.ids["claude"]}}); err == nil { t.Fatal("other person's connection enabled") } if _, err = f.s.SelectConnection(connectionContext, p.Person, f.project.ID, "product", ""); err == nil { t.Fatal("selection crossed person") } wrongPerson := f.principal wrongPerson.Person = p.Person if err := f.s.ReportConnections(connectionContext, wrongPerson, f.reports); err == nil { t.Fatal("principal person not rechecked") } forged := p forged.RunnerID = f.principal.RunnerID if err = f.s.ReportConnections(connectionContext, forged, f.reports); err == nil { t.Fatal("forged principal reported") } mustSQL(t, f.d, "UPDATE runner_credentials SET revoked_at = ? WHERE id = ?", f.clock.Now(), p.CredentialID) if err = f.s.ReportConnections(connectionContext, p, f.reports); err == nil { t.Fatal("cached revoked principal reported") } } func TestConnectionSelection(t *testing.T) { f := connectionStore(t) f.denied(t, "engineering", "") f.choice(t, "") selected := f.selectOK(t, "engineering", "") want := f.ids["claude"] if f.ids["codex"] < want { want = f.ids["codex"] } if selected.ConnectionID != want || selected.Reason != "first_allowed" || selected.AllowanceKnown || selected.MaxConcurrent != 1 { t.Fatalf("fallback or unknown allowance: %+v", selected) } specs, _ := f.s.Specialists(connectionContext) for _, sp := range specs { if sp.Key == "engineering" { sp.ModelSelection = "fixed" sp.Provider = "claude" sp.ModelFamily = "claude" sp.Model = "sonnet" if err := f.s.SaveSpecialist(connectionContext, ownerActor, sp); err != nil { t.Fatal(err) } } } if got := f.selectOK(t, "engineering", ""); got.Model != "sonnet" { t.Fatal("fixed model ignored") } f.reports = append(f.reports, connectionReport("claude", "claude", "claude", "aaa")) if err := f.s.ReportConnections(connectionContext, f.principal, f.reports); err != nil { t.Fatal(err) } if got := f.selectOK(t, "product", ""); got.ConnectionID == f.ids["claude"] && got.Model != "aaa" { t.Fatal("unstable model order") } if got := f.selectOK(t, "engineering", ""); got.Model != "sonnet" { t.Fatal("fixed model lost") } f.clock.Advance(90 * time.Second) f.denied(t, "product", "") if err := f.s.ReportConnections(connectionContext, f.principal, f.reports); err != nil { t.Fatal(err) } f.selectOK(t, "product", "") } func TestReviewWaitsForOtherFamily(t *testing.T) { f := connectionStore(t) f.choice(t, "") f.selectOK(t, "engineering", "") r := f.selectOK(t, "review", "claude") if r.Family != "gpt" { t.Fatal("review repeated family") } f.reports[1].Available = false if err := f.s.ReportConnections(connectionContext, f.principal, f.reports); err != nil { t.Fatal(err) } f.denied(t, "review", "claude") f.denied(t, "engineering", "") code, key := beginDevice(t, f.s) approveDevice(t, f.s, code, ownerAddress) c := claimDevice(t, f.s, code, key) p, _ := f.s.AuthenticateRunner(connectionContext, c.Token) if err := f.s.ReportConnections(connectionContext, p, []equipo.ConnectionReport{connectionReport("remote", "codex", "gpt", "gpt-5")}); err != nil { t.Fatal(err) } rows, _ := f.s.Connections(connectionContext, ownerActor) var remote string for _, row := range rows { if row.LocalID == "remote" { remote = row.ID } } if err := f.s.SaveConnectionChoice(connectionContext, ownerActor, equipo.ConnectionChoice{ProjectID: f.project.ID, Revision: 1, ConnectionIDs: []string{f.ids["claude"], remote}}); err != nil { t.Fatal(err) } f.denied(t, "engineering", "") } func TestAccountFailoverSelection(t *testing.T) { for _, which := range []string{"observed", "binding", "family", "no_failover", "pin_home", "timeline", "process"} { t.Run(which, func(t *testing.T) { f := connectionStore(t) f.choice(t, f.ids["claude"]) r := f.reports[0] switch which { case "observed": r.Routing.ObservedAccountID = "other" case "binding": r.Routing.AccountID = "other" r.Routing.ObservedAccountID = "other" case "family": r.Family = "gpt" case "no_failover": r.Routing.NoFailover = false case "pin_home": r.Routing.AccountPinned = false case "timeline": r.Routing.TimelineRecovery = false case "process": r.Routing.ProcessOwnership = false } if err := f.s.ReportConnections(connectionContext, f.principal, []equipo.ConnectionReport{r}); err == nil { t.Fatal("unsafe routing accepted") } f.denied(t, "product", "") if scalar(t, f.d, "SELECT count(*) FROM connection_invalidations WHERE connection_id = ?", f.ids["claude"]) == 0 { t.Fatal("unsafe report did not request containment") } }) } f := connectionStore(t) f.choice(t, f.ids["claude"]) if got := f.selectOK(t, "product", ""); got.ConnectionID != f.ids["claude"] || got.Reason != "pinned" { t.Fatal("pin ignored") } f.reports[0].Available = false if err := f.s.ReportConnections(connectionContext, f.principal, f.reports); err != nil { t.Fatal(err) } f.denied(t, "product", "") if err := f.s.ReportConnections(connectionContext, f.principal, f.reports[1:]); err != nil { t.Fatal(err) } f.denied(t, "product", "") } func TestProjectAccountNoDeleteAndASCIILabels(t *testing.T) { f := connectionStore(t) if _, err := f.s.SaveAccount(connectionContext, ownerActor, equipo.Account{Label: " CONNECTIONS "}); !errors.Is(err, equipo.ErrConflict) { t.Fatalf("ASCII duplicate accepted: %v", err) } for _, label := range []string{"Équipe", "équipe"} { if _, err := f.s.SaveAccount(connectionContext, ownerActor, equipo.Account{Label: label}); err != nil { t.Fatal("changed non-ASCII semantics", err) } } h, err := equipo.App(f.d, testConfig(testOrigin), &capturingMailer{}, nil) if err != nil { t.Fatal(err) } n := scalar(t, f.d, "SELECT count(*) FROM audit_events") for _, path := range []string{"/accounts/1", "/projects/1"} { req := httptest.NewRequest(http.MethodDelete, path, nil) req.Header.Set("Origin", testOrigin) w := httptest.NewRecorder() h.ServeHTTP(w, req) if w.Code < 400 && w.Code != 303 { t.Fatal("DELETE accepted") } } if scalar(t, f.d, "SELECT count(*) FROM audit_events") != n || scalar(t, f.d, "SELECT count(*) FROM projects") != 1 || scalar(t, f.d, "SELECT count(*) FROM accounts") != 3 { t.Fatal("DELETE changed records") } } func TestConnectionsHTTPAuthority(t *testing.T) { t.Parallel() f := connectionStore(t) m := &capturingMailer{} h, err := equipo.App(f.d, testConfig(testOrigin), m, nil) if err != nil { t.Fatal(err) } server := httptest.NewServer(h) t.Cleanup(server.Close) c := signinClient(t, server.URL) signinEmail(t, c, server.URL, testOrigin, m, ownerAddress) target := server.URL + "/connections/" + f.ids["codex"] + "/acknowledge" form := url.Values{"revision": {"1"}, "acknowledge": {"unconfined"}, "owner": {"forged@example.com"}, "provider_version": {"forged"}} res := clientPost(t, c, target, "http://wrong.invalid", form) res.Body.Close() if res.StatusCode != 403 { t.Fatalf("CSRF accepted %d", res.StatusCode) } res = clientPost(t, c, target, testOrigin, form) res.Body.Close() if res.StatusCode != 404 { t.Fatalf("retired consent route accepted: %d", res.StatusCode) } if scalar(t, f.d, "SELECT count(*) FROM isolation_acknowledgements") != 0 { t.Fatal("retired consent created authority") } choiceURL := server.URL + "/projects/" + strconv.FormatInt(f.project.ID, 10) + "/connections" res = clientPost(t, c, choiceURL, testOrigin, url.Values{"revision": {"0"}, "connection_id": {f.ids["codex"]}, "person": {"member@example.com"}}) res.Body.Close() if res.StatusCode != 303 { t.Fatal("choice handler failed", res.StatusCode) } if scalar(t, f.d, "SELECT count(*) FROM connection_choices WHERE person = ?", ownerAddress) != 1 { t.Fatal("form supplied choice person") } n := scalar(t, f.d, "SELECT count(*) FROM audit_events") for _, path := range []string{"/accounts/1", "/projects/1"} { req, _ := http.NewRequest(http.MethodDelete, server.URL+path, nil) req.Header.Set("Origin", testOrigin) res, err := c.Do(req) if err != nil { t.Fatal(err) } res.Body.Close() if res.StatusCode < 400 { t.Fatal("authenticated DELETE accepted") } } if scalar(t, f.d, "SELECT count(*) FROM audit_events") != n { t.Fatal("authenticated DELETE audited") } setMember(t, f.s, "second@example.com", equipo.RoleOwner, true) member, _ := f.s.Member(connectionContext, ownerAddress) if err := f.s.SetMember(connectionContext, equipo.Actor{Address: "second@example.com"}, ownerAddress, equipo.RoleMember, true, member.Revision); err != nil { t.Fatal(err) } form.Set("owner", "second@example.com") form.Set("actor", "second@example.com") res = clientPost(t, c, target, testOrigin, form) res.Body.Close() if res.StatusCode != 404 { t.Fatal("forged current-owner form accepted", res.StatusCode) } res = clientPost(t, c, server.URL+"/connections/"+f.ids["codex"]+"/revoke-acknowledgement", testOrigin, form) res.Body.Close() if res.StatusCode != 404 { t.Fatal("member revoked acknowledgement") } } func TestConnectionSelectionGuards(t *testing.T) { for _, change := range []string{"person", "roster", "runner_revoked", "future_clock", "missing_pin", "fixed_model", "capacity", "capacity_error", "verified_list", "claude_exception"} { t.Run(change, func(t *testing.T) { f := connectionStore(t) f.choice(t, f.ids["codex"]) f.selectOK(t, "product", "") switch change { case "person": mustSQL(t, f.d, "UPDATE connections SET person='other@example.com' WHERE id=?", f.ids["codex"]) case "roster": mustSQL(t, f.d, "UPDATE members SET active=0 WHERE address=?", ownerAddress) case "runner_revoked": if err := f.s.RevokeRunner(connectionContext, ownerActor, f.principal.RunnerID, 1); err != nil { t.Fatal(err) } if scalar(t, f.d, "SELECT count(*) FROM connection_invalidations WHERE reason='runner_revoked'") != 2 { t.Fatal("runner revocation did not request connection containment") } case "future_clock": f.clock.Advance(-time.Second) case "missing_pin": mustSQL(t, f.d, "UPDATE connection_choices SET pinned_id='missing'") case "fixed_model": mustSQL(t, f.d, "UPDATE specialists SET model_selection='fixed', provider='codex', model_family='gpt', model='unavailable' WHERE key='product'") case "capacity": // Seed only the core rows used by this read-only capacity guard. No execution is opened. mustSQL(t, f.d, `INSERT INTO jobs (id,account,parent,depth,requester,target,evidence,policy_version,policy,grant_ref,grant_version,grant_epoch,grant_observed_at,state,wait,revision,outcome,created_at,updated_at) VALUES(1,'team',0,0,'person','{}','{}',2,'{}','grant',1,1,'','active','{}',1,'','','')`) mustSQL(t, f.d, `INSERT INTO steps(id,job_id,key,capability,version,depends_on,state,fence,holder,attempts) VALUES(1,1,'product','scope',1,'[]','running',1,1,1)`) mustSQL(t, f.d, `INSERT INTO attempts(id,job_id,step_id,number,runner,workspace,fence,lease_deadline,state,containment,stop_requested,stop_acked,provider,model,effort,outcome,created_at,updated_at) VALUES(1,1,1,1,'runner','work',1,'','active','pending','','','codex','gpt-5','','','','')`) case "capacity_error": mustSQL(t, f.d, "ALTER TABLE attempts RENAME TO attempts_unavailable") case "owner_role": mustSQL(t, f.d, "UPDATE members SET role='member' WHERE address=?", ownerAddress) case "owner_active": setMember(t, f.s, "ack@example.com", equipo.RoleOwner, true) mustSQL(t, f.d, "UPDATE members SET active=0 WHERE address='ack@example.com'") case "owner_revision": mustSQL(t, f.d, "UPDATE members SET revision=revision+1 WHERE address=?", ownerAddress) case "verified_list", "claude_exception": if err := f.s.SaveConnectionChoice(connectionContext, ownerActor, equipo.ConnectionChoice{ProjectID: f.project.ID, Revision: 1, ConnectionIDs: []string{f.ids["claude"]}}); err != nil { t.Fatal(err) } f.s = equipo.NewStore(f.d, equipo.WithRunnerClock(f.clock)) } f.denied(t, "product", "") }) } t.Run("immutable_tuples", func(t *testing.T) { f := connectionStore(t) tuples := []team.IsolationTuple{connectionTuple(f.reports[0])} option := equipo.WithVerifiedIsolationTuples(tuples) tuples[0] = connectionTuple(f.reports[1]) f.s = equipo.NewStore(f.d, equipo.WithRunnerClock(f.clock), option) f.choice(t, f.ids["codex"]) f.denied(t, "product", "") }) } func TestConnectionsAtomicWrites(t *testing.T) { for _, operation := range []string{"report", "choice"} { t.Run(operation, func(t *testing.T) { f := connectionStore(t) n := scalar(t, f.d, "SELECT count(*) FROM audit_events") requests := scalar(t, f.d, "SELECT count(*) FROM connection_invalidations") mustSQL(t, f.d, "CREATE TRIGGER fail_connection_audit BEFORE INSERT ON audit_events BEGIN SELECT RAISE(ABORT, 'audit offline'); END") var err error switch operation { case "report": f.reports[1].IsolationConfigHash = strings.Repeat("c", 64) err = f.s.ReportConnections(connectionContext, f.principal, f.reports) case "choice": err = f.s.SaveConnectionChoice(connectionContext, ownerActor, equipo.ConnectionChoice{ProjectID: f.project.ID, ConnectionIDs: []string{f.ids["codex"]}}) } if err == nil { t.Fatal("write succeeded without audit") } if scalar(t, f.d, "SELECT count(*) FROM audit_events") != n || scalar(t, f.d, "SELECT count(*) FROM connection_invalidations") != requests || scalar(t, f.d, "SELECT revision FROM connections WHERE id=?", f.ids["codex"]) != 1 || scalar(t, f.d, "SELECT count(*) FROM isolation_acknowledgements") != 0 || scalar(t, f.d, "SELECT count(*) FROM connection_choices") != 0 { t.Fatal("failed audit left mutation") } }) } } func TestConnectionSelectionModelAndAllowance(t *testing.T) { f := connectionStore(t) f.choice(t, f.ids["claude"]) f.reports = append(f.reports, connectionReport("claude", "claude", "claude", "aaa")) f.reports[0].AllowanceKnown = true f.reports[0].AllowanceRemaining = 15 if err := f.s.ReportConnections(connectionContext, f.principal, f.reports); err != nil { t.Fatal(err) } got := f.selectOK(t, "product", "") if got.Model != "aaa" || got.AllowanceKnown { t.Fatal("model order or unknown allowance") } mustSQL(t, f.d, "UPDATE specialists SET model_selection='fixed',provider='claude',model_family='claude',model='sonnet' WHERE key='product'") got = f.selectOK(t, "product", "") if !got.AllowanceKnown || got.AllowanceRemaining != 15 { t.Fatal("known allowance lost") } rows, err := f.s.Connections(connectionContext, ownerActor) if err != nil { t.Fatal(err) } for _, r := range rows { if r.Revision != 1 { t.Fatal("models or allowance changed security revision") } } if err := f.s.SaveConnectionChoice(connectionContext, ownerActor, equipo.ConnectionChoice{ProjectID: f.project.ID, Revision: 0, ConnectionIDs: []string{f.ids["claude"]}}); !errors.Is(err, equipo.ErrConflict) { t.Fatal("stale choice accepted") } } func TestConnectionSelectionOptIn(t *testing.T) { f := connectionStore(t) if err := f.s.SaveConnectionChoice(connectionContext, ownerActor, equipo.ConnectionChoice{ProjectID: f.project.ID, ConnectionIDs: []string{f.ids["claude"]}}); err != nil { t.Fatal(err) } mustSQL(t, f.d, "UPDATE specialists SET model_selection='fixed',provider='codex',model_family='gpt',model='gpt-5' WHERE key='product'") f.denied(t, "product", "") } func setDirectAvailable(s *equipo.Store, p equipo.RunnerPrincipal, reports []equipo.ConnectionReport, available bool) error { r := append([]equipo.ConnectionReport(nil), reports...) r[1].Available = available return s.ReportConnections(connectionContext, p, r) }