oficina / equipo Public

feat: select allowed connections for each person's tasks

codex agent, operated by paul@keymail.dev pushed by claude agent, operated by paul@keymail.dev 2df98718d55f1c32546b61c0958b973371bd97b1 parent 44c2293
14 files changed, +1,771 −5
  • .rastrillo/budgets.txt +1 −1
  • internal/equipo/app.go +3 −0
  • internal/equipo/connection_handlers.go +71 −0
  • internal/equipo/connection_isolation.go +145 −0
  • internal/equipo/connection_models.go +100 −0
  • internal/equipo/connection_selection.go +242 −0
  • internal/equipo/connections.go +349 −0
  • internal/equipo/migrations/0011_connections.sql +42 −0
  • internal/equipo/migrations/schema.sql +42 −0
  • internal/equipo/models.go +1 −1
  • internal/equipo/roster.go +5 −0
  • internal/equipo/runners.go +9 −0
  • internal/equipo/store.go +4 −3
  • internal/equipotest/connections_test.go +757 −0

CI failed — run details

diff --git a/.rastrillo/budgets.txt b/.rastrillo/budgets.txt
index 9bb98b50..0022aae2 100644
--- a/.rastrillo/budgets.txt
+++ b/.rastrillo/budgets.txt
@@ -12,4 +12,4 @@
size internal/equipo/team 7600 - Preserve the plan-mandated core layout; Tasks 2-4 add recovery, subscription accounting, Git candidate identity, repository checks and observed isolation provenance to the copied transactional core.
perf GET /* skip Unknown private paths render 404; this fallback contains no screens.
time internal/equipo/team 15s Copied core crash, recovery and concurrency tests take about 7.7s idle and 13.6s on the loaded shared machine.
-time internal/equipotest 15s Real NoProof sign-in ceremonies wait 3s each; the package takes about 9.3s.
+time internal/equipotest 25s Task 6 keeps the mandated connections tests in this package; its focused authority, isolation, atomic-write and real-session checks took 15.5s on the shared machine, above the prior 15s allowance.
diff --git a/internal/equipo/app.go b/internal/equipo/app.go
index bb5871ed..ac2ff3f4 100644
--- a/internal/equipo/app.go
+++ b/internal/equipo/app.go
@@ -117,6 +117,9 @@ func Router(d *db.DB, cfg Config, mailer mail.Sender, logger *slog.Logger) (chi.
r.Get("/runners/enrol", a.enrolmentPage)
r.Post("/runners/enrol", a.approveEnrolment)
r.Post("/runners/{id}/revoke", a.revokeRunner)
+ r.Post("/projects/{id}/connections", a.saveConnectionChoice)
+ r.Post("/connections/{id}/acknowledge", a.acknowledgeConnection)
+ r.Post("/connections/{id}/revoke-acknowledgement", a.revokeConnectionAcknowledgement)
r.Get("/settings", a.settings)
r.Get("/specialists/{key}", a.specialist)
r.Post("/accounts", a.saveAccount)
diff --git a/internal/equipo/connection_handlers.go b/internal/equipo/connection_handlers.go
new file mode 100644
index 00000000..ad9fc7d0
--- /dev/null
+++ b/internal/equipo/connection_handlers.go
@@ -0,0 +1,71 @@
+package equipo
+
+import (
+ "net/http"
+ "strconv"
+
+ "amadan.net/rastrillo/rastrillo/auth"
+ "github.com/go-chi/chi/v5"
+)
+
+func (a *application) connectionForm(w http.ResponseWriter, r *http.Request) (Actor, int64, bool) {
+ r.Body = http.MaxBytesReader(w, r.Body, 16*1024)
+ if r.ParseForm() != nil {
+ a.failure(w, r, ErrInvalid)
+ return Actor{}, 0, false
+ }
+ id, ok := auth.From(r)
+ if !ok {
+ a.failure(w, r, ErrForbidden)
+ return Actor{}, 0, false
+ }
+ revision, err := strconv.ParseInt(r.PostForm.Get("revision"), 10, 64)
+ if err != nil || revision < 0 {
+ a.failure(w, r, ErrInvalid)
+ return Actor{}, 0, false
+ }
+ return Actor{Address: id.Address}, revision, true
+}
+func (a *application) saveConnectionChoice(w http.ResponseWriter, r *http.Request) {
+ actor, revision, ok := a.connectionForm(w, r)
+ if !ok {
+ return
+ }
+ project, err := strconv.ParseInt(chi.URLParam(r, "id"), 10, 64)
+ if err != nil {
+ a.failure(w, r, ErrInvalid)
+ return
+ }
+ choice := ConnectionChoice{ProjectID: project, Revision: revision, ConnectionIDs: r.PostForm["connection_id"], PinnedID: r.PostForm.Get("pinned_id")}
+ if err := a.store.SaveConnectionChoice(r.Context(), actor, choice); err != nil {
+ a.failure(w, r, err)
+ return
+ }
+ http.Redirect(w, r, "/connections", http.StatusSeeOther)
+}
+func (a *application) acknowledgeConnection(w http.ResponseWriter, r *http.Request) {
+ actor, revision, ok := a.connectionForm(w, r)
+ if !ok {
+ return
+ }
+ if r.PostForm.Get("acknowledge") != "unconfined" {
+ a.failure(w, r, ErrInvalid)
+ return
+ }
+ if err := a.store.AcknowledgeUnconfined(r.Context(), actor, chi.URLParam(r, "id"), revision); err != nil {
+ a.failure(w, r, err)
+ return
+ }
+ http.Redirect(w, r, "/connections", http.StatusSeeOther)
+}
+func (a *application) revokeConnectionAcknowledgement(w http.ResponseWriter, r *http.Request) {
+ actor, revision, ok := a.connectionForm(w, r)
+ if !ok {
+ return
+ }
+ if err := a.store.RevokeIsolationAcknowledgement(r.Context(), actor, chi.URLParam(r, "id"), revision); err != nil {
+ a.failure(w, r, err)
+ return
+ }
+ http.Redirect(w, r, "/connections", http.StatusSeeOther)
+}
diff --git a/internal/equipo/connection_isolation.go b/internal/equipo/connection_isolation.go
new file mode 100644
index 00000000..896c01bb
--- /dev/null
+++ b/internal/equipo/connection_isolation.go
@@ -0,0 +1,145 @@
+package equipo
+
+import (
+ "context"
+ "crypto/rand"
+ "encoding/json"
+ "errors"
+ "time"
+
+ "gorm.io/gorm"
+)
+
+func unconfinedException(r ConnectionReport) bool {
+ // This exception is for the observed unsupported adapter contract. A new
+ // server/provider version needs a new capability decision, not a wildcard.
+ return r.Provider == "codex" && r.ProviderVersion == "0.165.0" && r.PaseoVersion == "0.14.0"
+}
+func (s *Store) acknowledgementAt(tx *gorm.DB, c connectionRecord, r ConnectionReport) (IsolationAcknowledgement, error) {
+ var rows []isolationAcknowledgementRecord
+ if err := tx.Where("connection_id = ? AND revoked_at IS NULL", c.ID).Order("acknowledged_at DESC").Find(&rows).Error; err != nil {
+ return IsolationAcknowledgement{}, storeError(err)
+ }
+ for _, a := range rows {
+ if a.ConnectionRevision != c.Revision || a.Provider != r.Provider || a.ProviderVersion != r.ProviderVersion || a.PaseoVersion != r.PaseoVersion || a.IsolationConfigHash != r.IsolationConfigHash {
+ continue
+ }
+ m, err := memberAt(tx, a.Owner)
+ if errors.Is(err, ErrNotFound) {
+ continue
+ }
+ if err != nil {
+ return IsolationAcknowledgement{}, err
+ }
+ if m.Active && m.Role == RoleOwner && m.Revision == a.OwnerRevision {
+ return a.IsolationAcknowledgement, nil
+ }
+ }
+ return IsolationAcknowledgement{}, ErrForbidden
+}
+func (s *Store) AcknowledgeUnconfined(ctx context.Context, actor Actor, id string, revision int64) error {
+ return s.write(ctx, func(tx *gorm.DB) error {
+ if err := requireOwner(tx, actor); err != nil {
+ return err
+ }
+ owner, err := memberAt(tx, actor.Address)
+ if err != nil {
+ return err
+ }
+ var c connectionRecord
+ if err := tx.Where("id = ?", id).First(&c).Error; err != nil {
+ return storeError(err)
+ }
+ if c.Revision != revision {
+ return ErrConflict
+ }
+ if err := decodeConnection(&c); err != nil {
+ return err
+ }
+ if len(c.Reports) == 0 {
+ return ErrInvalid
+ }
+ r := c.Reports[0]
+ now := s.runnerClock.Now().UTC()
+ if s.confined(r) || !unconfinedException(r) || !routingValid(r) || !r.Available || !freshConnection(c, now) {
+ return ErrForbidden
+ }
+ if _, err := currentRunnerMember(tx, c.Person); err != nil {
+ return err
+ }
+ instance, err := runnerInstance(tx)
+ if err != nil {
+ return err
+ }
+ if _, err := runnerAt(tx, instance, c.RunnerID); err != nil {
+ return err
+ }
+ if err := tx.Model(&isolationAcknowledgementRecord{}).Where("connection_id = ? AND revoked_at IS NULL", id).Select("RevokedAt").Updates(&isolationAcknowledgementRecord{RevokedAt: &now}).Error; err != nil {
+ return storeError(err)
+ }
+ ack := isolationAcknowledgementRecord{IsolationAcknowledgement: IsolationAcknowledgement{ID: rand.Text(), ConnectionID: id, Owner: owner.Address, Provider: r.Provider, ProviderVersion: r.ProviderVersion, PaseoVersion: r.PaseoVersion, IsolationConfigHash: r.IsolationConfigHash, AcknowledgedAt: now, ConnectionRevision: c.Revision}, OwnerRevision: owner.Revision}
+ if err := tx.Create(&ack).Error; err != nil {
+ return storeError(err)
+ }
+ // Enabling exposure also requires propagation to work already on this runner.
+ if err := invalidateConnection(tx, c, "isolation_acknowledged", now); err != nil {
+ return err
+ }
+ return isolationAudit(tx, actor, "connection.isolation.acknowledge", ack.IsolationAcknowledgement, now)
+ })
+}
+func isolationAudit(tx *gorm.DB, actor Actor, kind string, a IsolationAcknowledgement, now time.Time) error {
+ data, _ := json.Marshal(a)
+ return storeError(tx.Create(&AuditEvent{Actor: normalizeAddress(actor.Address), Kind: kind, RecordID: string(data), At: now}).Error)
+}
+func (s *Store) RevokeIsolationAcknowledgement(ctx context.Context, actor Actor, id string, revision int64) error {
+ return s.write(ctx, func(tx *gorm.DB) error {
+ if err := requireOwner(tx, actor); err != nil {
+ return err
+ }
+ var c connectionRecord
+ if err := tx.Where("id = ?", id).First(&c).Error; err != nil {
+ return storeError(err)
+ }
+ if c.Revision != revision {
+ return ErrConflict
+ }
+ var rows []isolationAcknowledgementRecord
+ if err := tx.Where("connection_id = ? AND revoked_at IS NULL", id).Find(&rows).Error; err != nil {
+ return storeError(err)
+ }
+ if len(rows) == 0 {
+ return ErrNotFound
+ }
+ now := s.runnerClock.Now().UTC()
+ if err := tx.Model(&isolationAcknowledgementRecord{}).Where("connection_id = ? AND revoked_at IS NULL", id).Select("RevokedAt").Updates(&isolationAcknowledgementRecord{RevokedAt: &now}).Error; err != nil {
+ return storeError(err)
+ }
+ if err := invalidateConnection(tx, c, "isolation_revoked", now); err != nil {
+ return err
+ }
+ for _, a := range rows {
+ if err := isolationAudit(tx, actor, "connection.isolation.revoke", a.IsolationAcknowledgement, now); err != nil {
+ return err
+ }
+ }
+ return nil
+ })
+}
+
+func lapseOwnerAcknowledgements(tx *gorm.DB, owner string, now time.Time) error {
+ var rows []isolationAcknowledgementRecord
+ if err := tx.Where("owner = ? AND revoked_at IS NULL", owner).Find(&rows).Error; err != nil {
+ return storeError(err)
+ }
+ for _, a := range rows {
+ var c connectionRecord
+ if err := tx.Where("id = ?", a.ConnectionID).First(&c).Error; err != nil {
+ return storeError(err)
+ }
+ if err := invalidateConnection(tx, c, "acknowledging_owner_changed", now); err != nil {
+ return err
+ }
+ }
+ return storeError(tx.Model(&isolationAcknowledgementRecord{}).Where("owner = ? AND revoked_at IS NULL", owner).Select("RevokedAt").Updates(&isolationAcknowledgementRecord{RevokedAt: &now}).Error)
+}
diff --git a/internal/equipo/connection_models.go b/internal/equipo/connection_models.go
new file mode 100644
index 00000000..f8f58de6
--- /dev/null
+++ b/internal/equipo/connection_models.go
@@ -0,0 +1,100 @@
+package equipo
+
+import (
+ "slices"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/equipo/team"
+)
+
+// ConnectionRouting is an assertion by the authenticated runner about its
+// operator-managed binding file and supported provider routing. It contains
+// opaque account identity and a home hash, never credentials or home paths.
+type ConnectionRouting struct {
+ BindingID, AccountID, ObservedAccountID, CredentialHomeHash string
+ AccountPinned, NoFailover, TimelineRecovery, ProcessOwnership bool
+}
+
+type ConnectionReport struct {
+ LocalID, Provider, ProviderVersion, PaseoVersion, Family, Model, AccountLabel, Kind, UnavailableReason, IsolationConfigHash string
+ Available, ReadIsolation, AllowanceKnown bool
+ AllowanceRemaining int64
+ Routing ConnectionRouting
+}
+
+type Connection struct {
+ ID string `gorm:"primaryKey"`
+ RunnerID string `gorm:"uniqueIndex:connection_local"`
+ Person string `gorm:"index:connection_person"`
+ LocalID string `gorm:"uniqueIndex:connection_local"`
+ Revision int64
+ LastSeen time.Time
+ Reports []ConnectionReport `gorm:"-"`
+}
+
+type connectionRecord struct {
+ Connection `gorm:"embedded"`
+ ReportsJSON string
+ SecurityHash string
+}
+
+func (connectionRecord) TableName() string { return "connections" }
+
+type ConnectionChoice struct {
+ ProjectID, Revision int64
+ ConnectionIDs []string
+ PinnedID string
+}
+
+type connectionChoiceRecord struct {
+ Person string `gorm:"primaryKey"`
+ ProjectID int64 `gorm:"primaryKey;autoIncrement:false"`
+ Revision int64
+ ConnectionIDsJSON string
+ PinnedID string
+}
+
+func (connectionChoiceRecord) TableName() string { return "connection_choices" }
+
+type IsolationAcknowledgement struct {
+ ID string `gorm:"primaryKey"`
+ ConnectionID string `gorm:"index:connection_ack"`
+ Owner, Provider, ProviderVersion, PaseoVersion, IsolationConfigHash string
+ AcknowledgedAt time.Time
+ ConnectionRevision int64
+}
+type isolationAcknowledgementRecord struct {
+ IsolationAcknowledgement `gorm:"embedded"`
+ OwnerRevision int64
+ RevokedAt *time.Time
+}
+
+func (isolationAcknowledgementRecord) TableName() string { return "isolation_acknowledgements" }
+
+// ConnectionInvalidation is a durable request for the assignment service to
+// fence pending work and contain affected attempts before reuse. Selection is
+// not a dispatch reservation; Task 8 must recheck inside admission.
+type ConnectionInvalidation struct {
+ ID int64
+ ConnectionID string `gorm:"index:connection_invalidation"`
+ Revision int64
+ Reason string
+ At time.Time
+}
+
+type Selection struct {
+ ConnectionID, RunnerID, Person, Provider, Family, Model, AccountLabel, AccountID string
+ Revision, ChoiceRevision, SpecialistRevision int64
+ Reason string
+ MaxConcurrent int
+ AllowanceKnown bool
+ AllowanceRemaining int64
+ Isolation team.IsolationSnapshot
+}
+
+// WithVerifiedIsolationTuples captures a copy at construction. Reports cannot
+// extend this release-owned list. The production default is empty.
+func WithVerifiedIsolationTuples(tuples []team.IsolationTuple) StoreOption {
+ captured := slices.Clone(tuples)
+ return func(s *Store) { s.verifiedIsolation = slices.Clone(captured) }
+}
diff --git a/internal/equipo/connection_selection.go b/internal/equipo/connection_selection.go
new file mode 100644
index 00000000..39a57cd6
--- /dev/null
+++ b/internal/equipo/connection_selection.go
@@ -0,0 +1,242 @@
+package equipo
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "slices"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/equipo/team"
+ "gorm.io/gorm"
+)
+
+func freshConnection(c connectionRecord, now time.Time) bool {
+ return !c.LastSeen.After(now) && now.Sub(c.LastSeen) < 90*time.Second
+}
+func (s *Store) eligible(tx *gorm.DB, c connectionRecord, r ConnectionReport, now time.Time) (bool, IsolationAcknowledgement, error) {
+ if !r.Available || !freshConnection(c, now) || !routingValid(r) {
+ return false, IsolationAcknowledgement{}, nil
+ }
+ instance, err := runnerInstance(tx)
+ if err != nil {
+ return false, IsolationAcknowledgement{}, err
+ }
+ _, err = runnerAt(tx, instance, c.RunnerID)
+ if errors.Is(err, ErrForbidden) {
+ return false, IsolationAcknowledgement{}, nil
+ }
+ if err != nil {
+ return false, IsolationAcknowledgement{}, err
+ }
+ if s.confined(r) {
+ return true, IsolationAcknowledgement{}, nil
+ }
+ if !unconfinedException(r) {
+ return false, IsolationAcknowledgement{}, nil
+ }
+ a, err := s.acknowledgementAt(tx, c, r)
+ if errors.Is(err, ErrForbidden) {
+ return false, a, nil
+ }
+ return err == nil, a, err
+}
+func specialistAllows(sp Specialist, r ConnectionReport) bool {
+ return sp.ModelSelection == "best_fit" || sp.ModelSelection == "fixed" && sp.Provider == r.Provider && sp.ModelFamily == r.Family && sp.Model == r.Model
+}
+func knownFamily(s string) bool { return s == "claude" || s == "gpt" }
+func specialistAt(tx *gorm.DB, key string) (Specialist, error) {
+ var sp Specialist
+ if err := tx.Where("key = ?", key).First(&sp).Error; err != nil {
+ return sp, storeError(err)
+ }
+ if sp.MaxConcurrent <= 0 {
+ return sp, ErrUnavailable
+ }
+ // Containment-pending attempts occupy capacity even after stop is requested.
+ capabilities := []string{key}
+ if key == "engineering" {
+ capabilities = []string{"reproduce", "implement", "reconcile"}
+ }
+ var live int64
+ if err := tx.Table("attempts").Joins("JOIN steps ON steps.id = attempts.step_id").Where("attempts.containment = ? AND steps.capability IN ?", "pending", capabilities).Count(&live).Error; err != nil {
+ return sp, storeError(err)
+ }
+ if live >= int64(sp.MaxConcurrent) {
+ return sp, ErrUnavailable
+ }
+ return sp, nil
+}
+
+// SelectConnection is an instance eligibility snapshot. It creates neither a
+// job nor a lease; admission must repeat these checks in its write transaction.
+func (s *Store) SelectConnection(ctx context.Context, person string, projectID int64, specialist, excludedFamily string) (Selection, error) {
+ var result Selection
+ err := s.write(ctx, func(tx *gorm.DB) error {
+ var err error
+ result, err = s.selectConnectionAt(tx, person, projectID, specialist, excludedFamily)
+ return err
+ })
+ if err != nil {
+ return Selection{}, err
+ }
+ return result, nil
+}
+
+// The assignment service can reuse this check in its admission transaction.
+func (s *Store) selectConnectionAt(tx *gorm.DB, person string, projectID int64, specialist, excludedFamily string) (Selection, error) {
+ var result Selection
+ err := func() error {
+ m, err := currentRunnerMember(tx, person)
+ if err != nil {
+ return err
+ }
+ var project Project
+ if err := tx.First(&project, projectID).Error; err != nil {
+ return storeError(err)
+ }
+ choice, ids, err := choiceAt(tx, m.Address, projectID)
+ if err != nil {
+ return err
+ }
+ sp, err := specialistAt(tx, specialist)
+ if err != nil {
+ return err
+ }
+ if specialist == "review" && !knownFamily(excludedFamily) {
+ return ErrUnavailable
+ }
+ var rows []connectionRecord
+ if err := tx.Where("person = ? AND id IN ?", m.Address, ids).Order("id").Find(&rows).Error; err != nil {
+ return storeError(err)
+ }
+ for i := range rows {
+ if err := decodeConnection(&rows[i]); err != nil {
+ return err
+ }
+ }
+ now := s.runnerClock.Now().UTC()
+ pin := choice.PinnedID
+ // A builder-family pin cannot choose the reviewer. Within the other family,
+ // a pin still waits rather than silently moving to another account.
+ if excludedFamily != "" {
+ for _, c := range rows {
+ if c.ID == pin && len(c.Reports) > 0 && c.Reports[0].Family == excludedFamily {
+ pin = ""
+ }
+ }
+ }
+ for _, c := range rows {
+ if pin != "" && c.ID != pin {
+ continue
+ }
+ for _, r := range c.Reports {
+ if !knownFamily(r.Family) || r.Family == excludedFamily || !specialistAllows(sp, r) {
+ continue
+ }
+ ok, _, err := s.eligible(tx, c, r, now)
+ if err != nil {
+ return err
+ }
+ if !ok {
+ continue
+ }
+ if specialist == "engineering" {
+ review, err := specialistAt(tx, "review")
+ if err != nil {
+ return err
+ }
+ found := false
+ for _, other := range rows {
+ if other.RunnerID != c.RunnerID {
+ continue
+ }
+ for _, rr := range other.Reports {
+ if !knownFamily(rr.Family) || rr.Family == r.Family || !specialistAllows(review, rr) {
+ continue
+ }
+ ok, _, err := s.eligible(tx, other, rr, now)
+ if err != nil {
+ return err
+ }
+ if ok {
+ found = true
+ }
+ }
+ }
+ if !found {
+ continue
+ }
+ }
+ snapshot, err := s.isolationSnapshot(tx, c, r)
+ if err != nil {
+ return err
+ }
+ reason := "first_allowed"
+ if pin != "" {
+ reason = "pinned"
+ }
+ result = Selection{ConnectionID: c.ID, RunnerID: c.RunnerID, Person: m.Address, Provider: r.Provider, Family: r.Family, Model: r.Model, AccountLabel: r.AccountLabel, AccountID: r.Routing.AccountID, Revision: c.Revision, ChoiceRevision: choice.Revision, SpecialistRevision: sp.Revision, Reason: reason, MaxConcurrent: sp.MaxConcurrent, AllowanceKnown: r.AllowanceKnown, AllowanceRemaining: r.AllowanceRemaining, Isolation: snapshot}
+ return nil
+ }
+ }
+ return ErrUnavailable
+ }()
+ if err != nil {
+ return Selection{}, err
+ }
+ return result, nil
+}
+func (s *Store) isolationSnapshot(tx *gorm.DB, c connectionRecord, r ConnectionReport) (team.IsolationSnapshot, error) {
+ snapshot := team.IsolationSnapshot{Status: "confined", ObservedTuples: []team.IsolationTuple{reportTuple(r)}}
+ if !s.confined(r) {
+ snapshot.Status = "unconfined"
+ }
+ var choices []connectionChoiceRecord
+ if err := tx.Where("person = ?", c.Person).Find(&choices).Error; err != nil {
+ return snapshot, storeError(err)
+ }
+ enabled := map[string]bool{}
+ for _, choice := range choices {
+ var ids []string
+ if err := json.Unmarshal([]byte(choice.ConnectionIDsJSON), &ids); err != nil {
+ return snapshot, storeError(err)
+ }
+ for _, id := range ids {
+ enabled[id] = true
+ }
+ }
+ var rows []connectionRecord
+ if err := tx.Where("runner_id = ? AND person = ?", c.RunnerID, c.Person).Order("id").Find(&rows).Error; err != nil {
+ return snapshot, storeError(err)
+ }
+ for _, row := range rows {
+ if !enabled[row.ID] {
+ continue
+ }
+ if err := decodeConnection(&row); err != nil {
+ return snapshot, err
+ }
+ for _, rr := range row.Reports {
+ if s.confined(rr) {
+ continue
+ }
+ a, err := s.acknowledgementAt(tx, row, rr)
+ if errors.Is(err, ErrForbidden) {
+ continue
+ }
+ if err != nil {
+ return snapshot, err
+ }
+ snapshot.RunnerTainted = true
+ if !slices.Contains(snapshot.AcknowledgementIDs, a.ID) {
+ snapshot.AcknowledgementIDs = append(snapshot.AcknowledgementIDs, a.ID)
+ }
+ if !slices.Contains(snapshot.ObservedTuples, reportTuple(rr)) {
+ snapshot.ObservedTuples = append(snapshot.ObservedTuples, reportTuple(rr))
+ }
+ }
+ }
+ slices.Sort(snapshot.AcknowledgementIDs)
+ return snapshot, nil
+}
diff --git a/internal/equipo/connections.go b/internal/equipo/connections.go
new file mode 100644
index 00000000..93cd2499
--- /dev/null
+++ b/internal/equipo/connections.go
@@ -0,0 +1,349 @@
+package equipo
+
+import (
+ "context"
+ "crypto/rand"
+ "crypto/sha256"
+ "encoding/hex"
+ "encoding/json"
+ "errors"
+ "slices"
+ "sort"
+ "strings"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/equipo/team"
+ "amadan.net/oficina/equipo/internal/runnerproto"
+ "gorm.io/gorm"
+)
+
+func reportTuple(r ConnectionReport) team.IsolationTuple {
+ return team.IsolationTuple{Provider: r.Provider, ProviderVersion: r.ProviderVersion, PaseoVersion: r.PaseoVersion, IsolationConfigHash: r.IsolationConfigHash}
+}
+func (s *Store) confined(r ConnectionReport) bool {
+ return r.ReadIsolation && slices.Contains(s.verifiedIsolation, reportTuple(r))
+}
+func hexHash(s string) bool {
+ b, err := hex.DecodeString(s)
+ return err == nil && len(b) == 32 && s == strings.ToLower(s)
+}
+func routingValid(r ConnectionReport) bool {
+ v := r.Routing
+ return v.BindingID != "" && v.AccountID != "" && v.AccountID == v.ObservedAccountID && hexHash(v.CredentialHomeHash) && v.AccountPinned && v.NoFailover && v.TimelineRecovery && v.ProcessOwnership
+}
+func reportValid(r ConnectionReport) bool {
+ if !((r.Provider == "claude" && r.Family == "claude") || (r.Provider == "codex" && r.Family == "gpt")) {
+ return false
+ }
+ if r.LocalID == "" || r.Provider == "" || r.ProviderVersion == "" || r.PaseoVersion == "" || r.Family == "" || r.Model == "" || !hexHash(r.IsolationConfigHash) || (r.Kind != "subscription" && r.Kind != "api") || r.AllowanceRemaining < 0 {
+ return false
+ }
+ for _, v := range []string{r.LocalID, r.Provider, r.ProviderVersion, r.PaseoVersion, r.Family, r.Model, r.AccountLabel, r.UnavailableReason, r.Routing.BindingID, r.Routing.AccountID, r.Routing.ObservedAccountID} {
+ if len(v) > 256 || strings.ContainsAny(v, "\x00\r\n") {
+ return false
+ }
+ }
+ return routingValid(r)
+}
+func sameProfile(a, b ConnectionReport) bool {
+ return a.LocalID == b.LocalID && a.Provider == b.Provider && a.Family == b.Family && a.Kind == b.Kind && a.Routing.BindingID == b.Routing.BindingID && a.Routing.AccountID == b.Routing.AccountID
+}
+func securityHash(r ConnectionReport) string {
+ // Models and allowance changes do not change the security binding. Every
+ // model in one profile must have the same effective security configuration.
+ r.Model = ""
+ r.AccountLabel = ""
+ r.Available = false
+ r.UnavailableReason = ""
+ r.AllowanceKnown = false
+ r.AllowanceRemaining = 0
+ data, _ := json.Marshal(r)
+ sum := sha256.Sum256(data)
+ return hex.EncodeToString(sum[:])
+}
+func decodeConnection(c *connectionRecord) error {
+ return storeError(json.Unmarshal([]byte(c.ReportsJSON), &c.Reports))
+}
+func runnerPrincipalAt(tx *gorm.DB, p RunnerPrincipal, now time.Time) (runnerRecord, error) {
+ instance, err := runnerInstance(tx)
+ if err != nil {
+ return runnerRecord{}, err
+ }
+ r, err := runnerAt(tx, instance, p.RunnerID)
+ if err != nil {
+ return r, err
+ }
+ if r.Person != p.Person {
+ return r, ErrForbidden
+ }
+ if _, err := currentRunnerMember(tx, r.Person); err != nil {
+ return r, err
+ }
+ var c runnerCredentialRecord
+ if err := tx.Where("id = ?", p.CredentialID).First(&c).Error; err != nil {
+ return r, storeError(err)
+ }
+ if c.RunnerID != r.ID || c.Person != r.Person || c.InstanceID != instance || c.MachineKeyHash != r.MachineKeyHash || c.Audience != runnerproto.RunnerAudience || c.RevokedAt != nil || !now.Before(c.ExpiresAt) {
+ return r, ErrForbidden
+ }
+ return r, nil
+}
+func invalidateConnection(tx *gorm.DB, c connectionRecord, reason string, now time.Time) error {
+ return storeError(tx.Create(&ConnectionInvalidation{ConnectionID: c.ID, Revision: c.Revision, Reason: reason, At: now}).Error)
+}
+
+func (s *Store) ReportConnections(ctx context.Context, principal RunnerPrincipal, reports []ConnectionReport) error {
+ if len(reports) > 256 {
+ return ErrInvalid
+ }
+ invalid := false
+ groups := map[string][]ConnectionReport{}
+ for _, r := range reports {
+ if !reportValid(r) {
+ invalid = true
+ }
+ r.ReadIsolation = s.confined(r)
+ if !r.AllowanceKnown {
+ r.AllowanceRemaining = 0
+ }
+ for _, prior := range groups[r.LocalID] {
+ if prior.Model == r.Model || !sameProfile(prior, r) || securityHash(prior) != securityHash(r) {
+ invalid = true
+ }
+ }
+ groups[r.LocalID] = append(groups[r.LocalID], r)
+ }
+ err := s.write(ctx, func(tx *gorm.DB) error {
+ now := s.runnerClock.Now().UTC()
+ runner, err := runnerPrincipalAt(tx, principal, now)
+ if err != nil {
+ return err
+ }
+ var existing []connectionRecord
+ if err := tx.Where("runner_id = ?", runner.ID).Find(&existing).Error; err != nil {
+ return storeError(err)
+ }
+ byLocal := map[string]connectionRecord{}
+ for _, c := range existing {
+ if err := decodeConnection(&c); err != nil {
+ return err
+ }
+ byLocal[c.LocalID] = c
+ }
+ for local, rows := range groups {
+ if c, exists := byLocal[local]; exists && (c.Person != runner.Person || len(c.Reports) == 0 || !sameProfile(c.Reports[0], rows[0])) {
+ invalid = true
+ }
+ }
+ if invalid {
+ for _, c := range byLocal {
+ c.Revision++
+ for i := range c.Reports {
+ c.Reports[i].Available = false
+ }
+ data, _ := json.Marshal(c.Reports)
+ c.ReportsJSON = string(data)
+ if err := tx.Model(&connectionRecord{}).Where("id = ?", c.ID).Select("Revision", "ReportsJSON").Updates(&c).Error; err != nil {
+ return storeError(err)
+ }
+ if err := invalidateConnection(tx, c, "report_rejected", now); err != nil {
+ return err
+ }
+ }
+ return appendAudit(tx, Actor{Address: runner.Person}, "connection.report.rejected", runner.ID)
+ }
+ locals := make([]string, 0, len(groups))
+ for local := range groups {
+ locals = append(locals, local)
+ }
+ sort.Strings(locals)
+ for _, local := range locals {
+ rows := groups[local]
+ slices.SortFunc(rows, func(a, b ConnectionReport) int { return strings.Compare(a.Model, b.Model) })
+ c, exists := byLocal[local]
+ if !exists {
+ c = connectionRecord{Connection: Connection{ID: rand.Text(), RunnerID: runner.ID, Person: runner.Person, LocalID: local, Revision: 1}}
+ }
+ hash := securityHash(rows[0])
+ changed := exists && c.SecurityHash != hash
+ if changed {
+ c.Revision++
+ if err := invalidateConnection(tx, c, "security_changed", now); err != nil {
+ return err
+ }
+ }
+ if exists && !changed {
+ for _, prior := range c.Reports {
+ present := false
+ for _, next := range rows {
+ if next.Model == prior.Model && next.Available {
+ present = true
+ }
+ }
+ if prior.Available && !present {
+ if err := invalidateConnection(tx, c, "model_unavailable", now); err != nil {
+ return err
+ }
+ break
+ }
+ }
+ }
+ c.SecurityHash = hash
+ c.LastSeen = now
+ data, _ := json.Marshal(rows)
+ c.ReportsJSON = string(data)
+ if exists {
+ if err := tx.Model(&connectionRecord{}).Where("id = ?", c.ID).Select("Revision", "LastSeen", "ReportsJSON", "SecurityHash").Updates(&c).Error; err != nil {
+ return storeError(err)
+ }
+ } else if err := tx.Create(&c).Error; err != nil {
+ return storeError(err)
+ }
+ }
+ // Each report is a complete discovery snapshot for this runner. Missing
+ // profiles remain as unavailable records so pins and history keep identity.
+ for _, c := range existing {
+ if _, ok := groups[c.LocalID]; ok {
+ continue
+ }
+ if err := decodeConnection(&c); err != nil {
+ return err
+ }
+ changed := false
+ for i := range c.Reports {
+ if c.Reports[i].Available {
+ changed = true
+ }
+ c.Reports[i].Available = false
+ }
+ if changed {
+ if err := invalidateConnection(tx, c, "profile_missing", now); err != nil {
+ return err
+ }
+ }
+ data, _ := json.Marshal(c.Reports)
+ c.ReportsJSON = string(data)
+ if err := tx.Model(&connectionRecord{}).Where("id = ?", c.ID).Select("ReportsJSON").Updates(&c).Error; err != nil {
+ return storeError(err)
+ }
+ }
+ return appendAudit(tx, Actor{Address: runner.Person}, "connection.report", runner.ID)
+ })
+ if err != nil {
+ return err
+ }
+ if invalid {
+ return ErrInvalid
+ }
+ return nil
+}
+
+func (s *Store) Connections(ctx context.Context, actor Actor) ([]Connection, error) {
+ var result []Connection
+ err := s.write(ctx, func(tx *gorm.DB) error {
+ m, err := currentRunnerMember(tx, actor.Address)
+ if err != nil {
+ return err
+ }
+ var rows []connectionRecord
+ if err := tx.Where("person = ?", m.Address).Order("id").Find(&rows).Error; err != nil {
+ return storeError(err)
+ }
+ for _, c := range rows {
+ if err := decodeConnection(&c); err != nil {
+ return err
+ }
+ result = append(result, c.Connection)
+ }
+ return nil
+ })
+ if err != nil {
+ return nil, err
+ }
+ return result, nil
+}
+func choiceAt(tx *gorm.DB, person string, project int64) (connectionChoiceRecord, []string, error) {
+ var c connectionChoiceRecord
+ if err := tx.Where("person = ? AND project_id = ?", person, project).First(&c).Error; err != nil {
+ return c, nil, storeError(err)
+ }
+ var ids []string
+ err := json.Unmarshal([]byte(c.ConnectionIDsJSON), &ids)
+ return c, ids, storeError(err)
+}
+func (s *Store) SaveConnectionChoice(ctx context.Context, actor Actor, choice ConnectionChoice) error {
+ if choice.ProjectID <= 0 || choice.Revision < 0 || len(choice.ConnectionIDs) > 256 {
+ return ErrInvalid
+ }
+ ids := slices.Clone(choice.ConnectionIDs)
+ sort.Strings(ids)
+ for i, id := range ids {
+ if id == "" || (i > 0 && ids[i-1] == id) {
+ return ErrInvalid
+ }
+ }
+ if choice.PinnedID != "" && !slices.Contains(ids, choice.PinnedID) {
+ return ErrInvalid
+ }
+ return s.write(ctx, func(tx *gorm.DB) error {
+ m, err := currentRunnerMember(tx, actor.Address)
+ if err != nil {
+ return err
+ }
+ var project Project
+ if err := tx.First(&project, choice.ProjectID).Error; err != nil {
+ return storeError(err)
+ }
+ old, oldIDs, err := choiceAt(tx, m.Address, project.ID)
+ exists := err == nil
+ if err != nil && !errors.Is(err, ErrNotFound) {
+ return err
+ }
+ if old.Revision != choice.Revision {
+ return ErrConflict
+ }
+ for _, id := range ids {
+ var c connectionRecord
+ if err := tx.Where("id = ?", id).First(&c).Error; err != nil {
+ return storeError(err)
+ }
+ if c.Person != m.Address {
+ return ErrForbidden
+ }
+ }
+ raw, _ := json.Marshal(ids)
+ c := connectionChoiceRecord{Person: m.Address, ProjectID: project.ID, Revision: old.Revision + 1, ConnectionIDsJSON: string(raw), PinnedID: choice.PinnedID}
+ if exists {
+ if err := tx.Model(&connectionChoiceRecord{}).Where("person = ? AND project_id = ?", m.Address, project.ID).Select("Revision", "ConnectionIDsJSON", "PinnedID").Updates(&c).Error; err != nil {
+ return storeError(err)
+ }
+ } else if err := tx.Create(&c).Error; err != nil {
+ return storeError(err)
+ }
+ for _, id := range ids {
+ if !slices.Contains(oldIDs, id) {
+ var row connectionRecord
+ if err := tx.Where("id = ?", id).First(&row).Error; err != nil {
+ return storeError(err)
+ }
+ if err := invalidateConnection(tx, row, "connection_enabled", s.runnerClock.Now().UTC()); err != nil {
+ return err
+ }
+ }
+ }
+ for _, id := range oldIDs {
+ if !slices.Contains(ids, id) || old.PinnedID != choice.PinnedID {
+ var row connectionRecord
+ if err := tx.Where("id = ?", id).First(&row).Error; err != nil {
+ return storeError(err)
+ }
+ if err := invalidateConnection(tx, row, "choice_changed", s.runnerClock.Now().UTC()); err != nil {
+ return err
+ }
+ }
+ }
+ choice.Revision = c.Revision
+ auditChoice, _ := json.Marshal(choice)
+ return appendAudit(tx, actor, "connection.choice", string(auditChoice))
+ })
+}
diff --git a/internal/equipo/migrations/0011_connections.sql b/internal/equipo/migrations/0011_connections.sql
new file mode 100644
index 00000000..fcad8e5b
--- /dev/null
+++ b/internal/equipo/migrations/0011_connections.sql
@@ -0,0 +1,42 @@
+CREATE TABLE connections (
+ id text PRIMARY KEY,
+ runner_id text,
+ person text,
+ local_id text,
+ revision integer,
+ last_seen datetime,
+ reports_json text,
+ security_hash text
+);
+CREATE UNIQUE INDEX connection_local ON connections(runner_id, local_id);
+CREATE INDEX connection_person ON connections(person);
+CREATE TABLE connection_choices (
+ person text,
+ project_id integer,
+ revision integer,
+ connection_ids_json text,
+ pinned_id text,
+ PRIMARY KEY(person, project_id)
+);
+CREATE TABLE isolation_acknowledgements (
+ id text PRIMARY KEY,
+ connection_id text,
+ owner text,
+ provider text,
+ provider_version text,
+ paseo_version text,
+ isolation_config_hash text,
+ acknowledged_at datetime,
+ connection_revision integer,
+ owner_revision integer,
+ revoked_at datetime
+);
+CREATE INDEX connection_ack ON isolation_acknowledgements(connection_id);
+CREATE TABLE connection_invalidations (
+ id integer PRIMARY KEY AUTOINCREMENT,
+ connection_id text,
+ revision integer,
+ reason text,
+ at datetime
+);
+CREATE INDEX connection_invalidation ON connection_invalidations(connection_id);
diff --git a/internal/equipo/migrations/schema.sql b/internal/equipo/migrations/schema.sql
index f20f7de1..3ee022bc 100644
--- a/internal/equipo/migrations/schema.sql
+++ b/internal/equipo/migrations/schema.sql
@@ -259,3 +259,45 @@ CREATE TABLE runner_rates (
window_start datetime,
count integer
);
+CREATE TABLE connections (
+ id text PRIMARY KEY,
+ runner_id text,
+ person text,
+ local_id text,
+ revision integer,
+ last_seen datetime,
+ reports_json text,
+ security_hash text
+);
+CREATE UNIQUE INDEX connection_local ON connections(runner_id, local_id);
+CREATE INDEX connection_person ON connections(person);
+CREATE TABLE connection_choices (
+ person text,
+ project_id integer,
+ revision integer,
+ connection_ids_json text,
+ pinned_id text,
+ PRIMARY KEY(person, project_id)
+);
+CREATE TABLE isolation_acknowledgements (
+ id text PRIMARY KEY,
+ connection_id text,
+ owner text,
+ provider text,
+ provider_version text,
+ paseo_version text,
+ isolation_config_hash text,
+ acknowledged_at datetime,
+ connection_revision integer,
+ owner_revision integer,
+ revoked_at datetime
+);
+CREATE INDEX connection_ack ON isolation_acknowledgements(connection_id);
+CREATE TABLE connection_invalidations (
+ id integer PRIMARY KEY AUTOINCREMENT,
+ connection_id text,
+ revision integer,
+ reason text,
+ at datetime
+);
+CREATE INDEX connection_invalidation ON connection_invalidations(connection_id);
diff --git a/internal/equipo/models.go b/internal/equipo/models.go
index a27928fa..8a480ca7 100644
--- a/internal/equipo/models.go
+++ b/internal/equipo/models.go
@@ -2,7 +2,7 @@ package equipo
import "time"
-var Models = append([]any{&Team{}, &Member{}, &AuditEvent{}, &Account{}, &Project{}, &DecisionOwner{}, &projectRequest{}, &budgetRecord{}, &Specialist{}, &runnerRecord{}, &runnerEnrolment{}, &runnerCredentialRecord{}, &runnerRate{}}, executionModels...)
+var Models = append([]any{&Team{}, &Member{}, &AuditEvent{}, &Account{}, &Project{}, &DecisionOwner{}, &projectRequest{}, &budgetRecord{}, &Specialist{}, &runnerRecord{}, &runnerEnrolment{}, &runnerCredentialRecord{}, &runnerRate{}, &connectionRecord{}, &connectionChoiceRecord{}, &isolationAcknowledgementRecord{}, &ConnectionInvalidation{}}, executionModels...)
type Role string
diff --git a/internal/equipo/roster.go b/internal/equipo/roster.go
index fc048adb..733a2c92 100644
--- a/internal/equipo/roster.go
+++ b/internal/equipo/roster.go
@@ -146,6 +146,11 @@ func (s *Store) SetMember(ctx context.Context, actor Actor, address string, role
} else if err := tx.Create(&member).Error; err != nil {
return storeError(err)
}
+ if exists && old.Role == RoleOwner && (!active || role != RoleOwner) {
+ if err := lapseOwnerAcknowledgements(tx, address, s.runnerClock.Now().UTC()); err != nil {
+ return err
+ }
+ }
if !active {
if err := revokePersonRunners(tx, address, s.runnerClock.Now().UTC()); err != nil {
return err
diff --git a/internal/equipo/runners.go b/internal/equipo/runners.go
index 5c138e23..50f60c18 100644
--- a/internal/equipo/runners.go
+++ b/internal/equipo/runners.go
@@ -115,6 +115,15 @@ func (s *Store) RotateRunnerCredential(ctx context.Context, token string) (runne
}
func revokeRunnerAt(tx *gorm.DB, id string, now time.Time) error {
+ var connections []connectionRecord
+ if err := tx.Where("runner_id = ?", id).Find(&connections).Error; err != nil {
+ return storeError(err)
+ }
+ for _, c := range connections {
+ if err := invalidateConnection(tx, c, "runner_revoked", now); err != nil {
+ return err
+ }
+ }
updated := tx.Model(&runnerRecord{}).Where("id = ? AND revoked_at IS NULL", id).Select("RevokedAt", "Revision").Updates(map[string]any{"RevokedAt": now, "Revision": gorm.Expr("revision + 1")})
if updated.Error != nil {
return storeError(updated.Error)
diff --git a/internal/equipo/store.go b/internal/equipo/store.go
index a15886ba..8bdb3ee7 100644
--- a/internal/equipo/store.go
+++ b/internal/equipo/store.go
@@ -43,9 +43,10 @@ func (e *refusal) Unwrap() error { return e.kind }
// Store grants no access by itself. Mutators must check the trusted Actor
// against the current roster and append an AuditEvent in their transaction.
type Store struct {
- db *db.DB
- execution *Execution
- runnerClock team.Clock
+ db *db.DB
+ execution *Execution
+ runnerClock team.Clock
+ verifiedIsolation []team.IsolationTuple
}
type StoreOption func(*Store)
diff --git a/internal/equipotest/connections_test.go b/internal/equipotest/connections_test.go
new file mode 100644
index 00000000..cee688c6
--- /dev/null
+++ b/internal/equipotest/connections_test.go
@@ -0,0 +1,757 @@
+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"
+ "gorm.io/gorm"
+ "gorm.io/gorm/clause"
+)
+
+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, PaseoVersion: "0.14.0", 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, PaseoVersion: r.PaseoVersion, 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])}))
+ 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) ack(t *testing.T) {
+ t.Helper()
+ if err := f.s.AcknowledgeUnconfined(connectionContext, ownerActor, f.ids["codex"], 1); 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.ack(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.ack(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.denied(t, "engineering", "")
+ f.ack(t)
+ 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.AcknowledgeUnconfined(connectionContext, ownerActor, remote, 1); err != nil {
+ t.Fatal(err)
+ }
+ 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.ack(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.ack(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 TestUnconfinedConnectionRequiresAcknowledgement(t *testing.T) {
+ f := connectionStore(t)
+ f.choice(t, f.ids["codex"])
+ f.denied(t, "product", "")
+ rows, _ := f.s.Connections(connectionContext, ownerActor)
+ for _, row := range rows {
+ if row.LocalID == "codex" && row.Reports[0].ReadIsolation {
+ t.Fatal("unlisted claimed isolation persisted")
+ }
+ }
+ for _, actor := range []equipo.Actor{{Address: "member@example.com"}, {Address: "forged-owner@example.com"}} {
+ if err := f.s.AcknowledgeUnconfined(connectionContext, actor, f.ids["codex"], 1); err == nil {
+ t.Fatal("nonowner acknowledged")
+ }
+ }
+ if err := f.s.AcknowledgeUnconfined(connectionContext, ownerActor, f.ids["claude"], 1); err == nil {
+ t.Fatal("wrong connection acknowledged")
+ }
+ f.ack(t)
+ r := f.selectOK(t, "product", "")
+ if r.Isolation.Status != "unconfined" || !r.Isolation.RunnerTainted || len(r.Isolation.AcknowledgementIDs) != 1 || len(r.Isolation.ObservedTuples) != 1 {
+ t.Fatalf("missing unconfined provenance: %+v", r)
+ }
+ // Acknowledgement applies across projects, while opt-in remains personal.
+ a := equipo.Account{ID: f.project.AccountID}
+ p := projectInput(a)
+ p.Repository = "amadan.net/oficina/other"
+ p.AppName = "other"
+ p = saveProject(t, f.s, p, projectOwners(), "other")
+ if _, err := f.s.SelectConnection(connectionContext, ownerAddress, p.ID, "product", ""); err == nil {
+ t.Fatal("ack implied opt-in")
+ }
+ if err := f.s.SaveConnectionChoice(connectionContext, ownerActor, equipo.ConnectionChoice{ProjectID: p.ID, ConnectionIDs: []string{f.ids["claude"]}}); err != nil {
+ t.Fatal(err)
+ }
+ r, err := f.s.SelectConnection(connectionContext, ownerAddress, p.ID, "product", "")
+ if err != nil || r.Isolation.Status != "confined" || !r.Isolation.RunnerTainted {
+ t.Fatalf("runner-wide taint missing: %+v %v", r, err)
+ }
+ var event equipo.AuditEvent
+ if err = f.d.G.Where("kind = ?", "connection.isolation.acknowledge").First(&event).Error; err != nil {
+ t.Fatal(err)
+ }
+ if event.Actor != ownerAddress || !event.At.Equal(f.clock.Now()) {
+ t.Fatal("ack audit actor/time")
+ }
+ for _, value := range []string{f.ids["codex"], "0.165.0", "0.14.0", "codex", strings.Repeat("a", 64)} {
+ if !strings.Contains(event.RecordID, value) {
+ t.Fatal("ack audit missing tuple", value)
+ }
+ }
+ if strings.Contains(event.RecordID, "opaque-") || strings.Contains(event.RecordID, "Bearer") {
+ t.Fatal("credentials or account identity in audit")
+ }
+}
+func TestIsolationAcknowledgementLapses(t *testing.T) {
+ for _, change := range []string{"provider", "provider_version", "daemon", "config", "revision", "revoke", "demote", "remove", "roster_failure", "preflight"} {
+ t.Run(change, func(t *testing.T) {
+ f := connectionStore(t)
+ setMember(t, f.s, "ack@example.com", equipo.RoleOwner, true)
+ if err := f.s.AcknowledgeUnconfined(connectionContext, equipo.Actor{Address: "ack@example.com"}, f.ids["codex"], 1); err != nil {
+ t.Fatal(err)
+ }
+ f.choice(t, f.ids["codex"])
+ f.selectOK(t, "product", "")
+ switch change {
+ case "provider", "provider_version", "daemon", "config":
+ r := f.reports[1]
+ switch change {
+ case "provider":
+ r.Provider = "claude"
+ case "provider_version":
+ r.ProviderVersion = "0.166.0"
+ case "daemon":
+ r.PaseoVersion = "0.15.0"
+ case "config":
+ r.IsolationConfigHash = strings.Repeat("c", 64)
+ }
+ f.reports[1] = r
+ if err := f.s.ReportConnections(connectionContext, f.principal, f.reports); err != nil {
+ if change != "provider" {
+ t.Fatal(err)
+ }
+ }
+ case "revision":
+ mustSQL(t, f.d, "UPDATE connections SET revision=revision+1 WHERE id=?", f.ids["codex"])
+ case "revoke":
+ if err := f.s.RevokeIsolationAcknowledgement(connectionContext, ownerActor, f.ids["codex"], 1); err != nil {
+ t.Fatal(err)
+ }
+ case "demote":
+ setMember(t, f.s, "ack@example.com", equipo.RoleMember, true)
+ case "remove":
+ setMember(t, f.s, "ack@example.com", equipo.RoleOwner, false)
+ case "roster_failure":
+ mustSQL(t, f.d, "ALTER TABLE members RENAME TO members_unavailable")
+ case "preflight":
+ f.reports[0].ReadIsolation = false
+ if err := f.s.ReportConnections(connectionContext, f.principal, f.reports); err != nil {
+ t.Fatal(err)
+ }
+ 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.denied(t, "product", "")
+ })
+ }
+ t.Run("heartbeat_and_atomic_audit", func(t *testing.T) {
+ f := connectionStore(t)
+ f.ack(t)
+ f.choice(t, f.ids["codex"])
+ f.clock.Advance(time.Second)
+ if err := f.s.ReportConnections(connectionContext, f.principal, f.reports); err != nil {
+ t.Fatal(err)
+ }
+ f.selectOK(t, "product", "")
+ mustSQL(t, f.d, "CREATE TRIGGER fail_connection_audit BEFORE INSERT ON audit_events BEGIN SELECT RAISE(ABORT, 'audit offline'); END")
+ if err := f.s.RevokeIsolationAcknowledgement(connectionContext, ownerActor, f.ids["codex"], 1); err == nil {
+ t.Fatal("revocation succeeded without audit")
+ }
+ f.selectOK(t, "product", "")
+ })
+}
+
+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 != 303 {
+ t.Fatalf("owner acknowledgement failed %d", res.StatusCode)
+ }
+ var ack equipo.IsolationAcknowledgement
+ if err := f.d.G.Table("isolation_acknowledgements").First(&ack).Error; err != nil {
+ t.Fatal(err)
+ }
+ if ack.Owner != ownerAddress || ack.ProviderVersion != "0.165.0" {
+ t.Fatal("form supplied authority or tuple")
+ }
+ 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 != 403 {
+ t.Fatal("forged current-owner form accepted", res.StatusCode)
+ }
+ if err := f.s.AcknowledgeUnconfined(connectionContext, equipo.Actor{Address: "second@example.com"}, f.ids["codex"], 1); err != nil {
+ t.Fatal(err)
+ }
+ res = clientPost(t, c, server.URL+"/connections/"+f.ids["codex"]+"/revoke-acknowledgement", testOrigin, form)
+ res.Body.Close()
+ if res.StatusCode != 403 {
+ 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", "owner_role", "owner_active", "owner_revision", "verified_list", "claude_exception"} {
+ t.Run(change, func(t *testing.T) {
+ f := connectionStore(t)
+ f.ack(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','product',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)
+ if err := f.s.AcknowledgeUnconfined(connectionContext, equipo.Actor{Address: "ack@example.com"}, f.ids["codex"], 1); err != nil {
+ t.Fatal(err)
+ }
+ 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))
+ if change == "claude_exception" {
+ if err := f.s.AcknowledgeUnconfined(connectionContext, ownerActor, f.ids["claude"], 1); err == nil {
+ t.Fatal("Claude exception accepted")
+ }
+ }
+ }
+ 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 TestIsolationAcknowledgementBindingGuards(t *testing.T) {
+ for _, field := range []string{"connection_id", "provider", "provider_version", "paseo_version", "isolation_config_hash", "connection_revision"} {
+ t.Run(field, func(t *testing.T) {
+ f := connectionStore(t)
+ f.ack(t)
+ f.choice(t, f.ids["codex"])
+ f.selectOK(t, "product", "")
+ value := any("wrong")
+ if field == "connection_revision" {
+ value = int64(99)
+ }
+ mustSQL(t, f.d, "UPDATE isolation_acknowledgements SET "+field+" = ?", value)
+ f.denied(t, "product", "")
+ })
+ }
+ t.Run("wrong_revision", func(t *testing.T) {
+ f := connectionStore(t)
+ if err := f.s.AcknowledgeUnconfined(connectionContext, ownerActor, f.ids["codex"], 2); !errors.Is(err, equipo.ErrConflict) {
+ t.Fatal("stale acknowledgement accepted")
+ }
+ f.ack(t)
+ if err := f.s.RevokeIsolationAcknowledgement(connectionContext, ownerActor, f.ids["codex"], 2); !errors.Is(err, equipo.ErrConflict) {
+ t.Fatal("stale revocation accepted")
+ }
+ })
+ t.Run("different_connection", func(t *testing.T) {
+ f := connectionStore(t)
+ other := connectionReport("other-codex", "codex", "gpt", "gpt-5")
+ reports := append(f.reports, other)
+ if err := f.s.ReportConnections(connectionContext, f.principal, reports); err != nil {
+ t.Fatal(err)
+ }
+ rows, _ := f.s.Connections(connectionContext, ownerActor)
+ for _, r := range rows {
+ if r.LocalID == other.LocalID {
+ if err := f.s.AcknowledgeUnconfined(connectionContext, ownerActor, r.ID, 1); err != nil {
+ t.Fatal(err)
+ }
+ }
+ }
+ f.choice(t, f.ids["codex"])
+ f.denied(t, "product", "")
+ })
+ t.Run("removed_owner_does_not_revive", func(t *testing.T) {
+ f := connectionStore(t)
+ setMember(t, f.s, "ack@example.com", equipo.RoleOwner, true)
+ if err := f.s.AcknowledgeUnconfined(connectionContext, equipo.Actor{Address: "ack@example.com"}, f.ids["codex"], 1); err != nil {
+ t.Fatal(err)
+ }
+ f.choice(t, f.ids["codex"])
+ setMember(t, f.s, "ack@example.com", equipo.RoleMember, true)
+ setMember(t, f.s, "ack@example.com", equipo.RoleOwner, true)
+ f.denied(t, "product", "")
+ if scalar(t, f.d, "SELECT count(*) FROM connection_invalidations WHERE reason='acknowledging_owner_changed'") != 1 {
+ t.Fatal("owner change did not request containment")
+ }
+ })
+}
+
+func TestConnectionsAtomicWrites(t *testing.T) {
+ for _, operation := range []string{"report", "choice", "acknowledge"} {
+ 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"]}})
+ case "acknowledge":
+ err = f.s.AcknowledgeUnconfined(connectionContext, ownerActor, f.ids["codex"], 1)
+ }
+ 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)
+ f.ack(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 TestUnconfinedConnectionExceptionVersions(t *testing.T) {
+ for _, field := range []string{"provider", "daemon"} {
+ t.Run(field, func(t *testing.T) {
+ f := connectionStore(t)
+ if field == "provider" {
+ f.reports[1].ProviderVersion = "0.166.0"
+ } else {
+ f.reports[1].PaseoVersion = "0.15.0"
+ }
+ if err := f.s.ReportConnections(connectionContext, f.principal, f.reports); err != nil {
+ t.Fatal(err)
+ }
+ if scalar(t, f.d, "SELECT revision FROM connections WHERE id=?", f.ids["codex"]) != 2 {
+ t.Fatal("security change did not advance revision")
+ }
+ if err := f.s.AcknowledgeUnconfined(connectionContext, ownerActor, f.ids["codex"], 2); err == nil {
+ t.Fatal("new adapter version inherited exception")
+ }
+ })
+ }
+}
+
+func TestIsolationAcknowledgementOwnerLookupFailure(t *testing.T) {
+ f := connectionStore(t)
+ setMember(t, f.s, "ack@example.com", equipo.RoleOwner, true)
+ if err := f.s.AcknowledgeUnconfined(connectionContext, equipo.Actor{Address: "ack@example.com"}, f.ids["codex"], 1); err != nil {
+ t.Fatal(err)
+ }
+ f.choice(t, f.ids["codex"])
+ reached := false
+ if err := f.d.G.Callback().Query().Before("gorm:query").Register("test:ack_owner_failure", func(tx *gorm.DB) {
+ if tx.Statement.Table != "members" {
+ return
+ }
+ where, ok := tx.Statement.Clauses["WHERE"].Expression.(clause.Where)
+ if !ok {
+ return
+ }
+ for _, expression := range where.Exprs {
+ if expr, ok := expression.(clause.Expr); ok {
+ for _, value := range expr.Vars {
+ if value == "ack@example.com" {
+ reached = true
+ tx.AddError(errors.New("owner lookup offline"))
+ }
+ }
+ }
+ }
+ }); err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { f.d.G.Callback().Query().Remove("test:ack_owner_failure") })
+ f.denied(t, "product", "")
+ if !reached {
+ t.Fatal("owner lookup failure not reached")
+ }
+}