oficina / equipo Public

feat: authorize core work from the instance roster

codex agent, operated by paul@keymail.dev pushed by claude agent, operated by paul@keymail.dev 47fb6d89a03d362ad1ea53a02345da3eb67f7d6f parent a421e62
2 files changed, +496 −0
  • internal/equipo/authority.go +140 −0
  • internal/equipotest/authority_test.go +356 −0

CI cancelled — superseded by a newer push — run details

diff --git a/internal/equipo/authority.go b/internal/equipo/authority.go
new file mode 100644
index 00000000..f814ad63
--- /dev/null
+++ b/internal/equipo/authority.go
@@ -0,0 +1,140 @@
+package equipo
+
+import (
+ "context"
+ "database/sql"
+ "encoding/base64"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/equipo/team"
+ "gorm.io/gorm"
+ "gorm.io/plugin/dbresolver"
+)
+
+type RosterAuthority struct {
+ store *Store
+ clock team.Clock
+}
+
+var _ team.Authority = (*RosterAuthority)(nil)
+
+func NewAuthority(store *Store, clock team.Clock) *RosterAuthority {
+ if clock == nil {
+ clock = team.RealClock{}
+ }
+ return &RosterAuthority{store: store, clock: clock}
+}
+
+type grantReference struct {
+ Version int `json:"version"`
+ ProjectID int64 `json:"project_id"`
+ Address string `json:"address"`
+}
+
+// GrantRef identifies a project and person; it is not a credential. The trusted
+// job-creation adapter must derive it and Requester from the verified session.
+// Possession of a ref never authorizes an HTTP request.
+func GrantRef(projectID int64, address string) string {
+ address = normalizeAddress(address)
+ if projectID <= 0 || !validAddress(address) {
+ return ""
+ }
+ data, _ := json.Marshal(grantReference{Version: 1, ProjectID: projectID, Address: address})
+ return base64.RawURLEncoding.EncodeToString(data)
+}
+
+func parseGrantReference(ref string) (grantReference, error) {
+ var grant grantReference
+ data, err := base64.RawURLEncoding.Strict().DecodeString(ref)
+ if err != nil || json.Unmarshal(data, &grant) != nil || grant.Version != 1 || grant.ProjectID <= 0 || !validAddress(grant.Address) {
+ return grantReference{}, team.ErrGrantRevoked
+ }
+ // One encoding rejects extra fields, duplicate keys and address aliases.
+ if ref != GrantRef(grant.ProjectID, grant.Address) {
+ return grantReference{}, team.ErrGrantRevoked
+ }
+ return grant, nil
+}
+
+func (a *RosterAuthority) Introspect(ctx context.Context, req team.AdmissionRequest) (team.Admission, error) {
+ if a == nil || a.store == nil || a.store.db == nil || a.store.db.G == nil || a.clock == nil {
+ return team.Admission{}, team.ErrAuthorityUnavailable
+ }
+ if err := ctx.Err(); err != nil {
+ return team.Admission{}, fmt.Errorf("%w: %w", team.ErrAuthorityUnavailable, err)
+ }
+ grant, err := parseGrantReference(req.Grant)
+ if err != nil {
+ return team.Admission{}, err
+ }
+ switch req.Operation {
+ case team.OpJobContinue, team.OpAttemptContinue, team.OpProviderCall, team.OpForgePublish:
+ default:
+ return team.Admission{}, team.ErrGrantRevoked
+ }
+ if req.Target.Kind != team.TargetRepository || req.Target.Subject != "" || req.Target.BaseRevision == "" {
+ return team.Admission{}, team.ErrGrantRevoked
+ }
+ var admission team.Admission
+ err = a.store.db.G.WithContext(ctx).Clauses(dbresolver.Read).Transaction(func(tx *gorm.DB) error {
+ var instance Team
+ if err := tx.First(&instance).Error; err != nil {
+ return err
+ }
+ if req.Account != team.AccountID(instance.ID) {
+ return team.ErrGrantRevoked
+ }
+ var project Project
+ if err := tx.First(&project, grant.ProjectID).Error; err != nil {
+ return err
+ }
+ repository, err := canonicalRepository(req.Target.Repository)
+ if err != nil || repository != req.Target.Repository || repository != project.Repository || req.Target.App != project.AppName {
+ return team.ErrGrantRevoked
+ }
+ savedDefault, err := CanonicalBranch(project.DefaultBranch)
+ if err != nil {
+ return team.ErrGrantRevoked
+ }
+ targetDefault, err := CanonicalBranch(req.Target.DefaultRef)
+ if err != nil || targetDefault != savedDefault {
+ return team.ErrGrantRevoked
+ }
+ ref, err := CanonicalBranch(req.Target.Ref)
+ if err != nil || ref == savedDefault {
+ return team.ErrGrantRevoked
+ }
+ member, err := memberAt(tx, grant.Address)
+ if err != nil {
+ return err
+ }
+ if !member.Active {
+ return team.ErrGrantRevoked
+ }
+ if member.Role != RoleOwner {
+ if member.Role != RoleMember {
+ return team.ErrGrantRevoked
+ }
+ var owner DecisionOwner
+ if err := tx.Where("project_id = ? AND decision = ?", project.ID, "work").First(&owner).Error; err != nil {
+ return err
+ }
+ if owner.Address != member.Address {
+ return team.ErrGrantRevoked
+ }
+ }
+ now := a.clock.Now()
+ admission = team.Admission{Grant: req.Grant, Version: project.Revision, Epoch: instance.RosterEpoch, IssuedAt: now, ExpiresAt: now.Add(5 * time.Second)}
+ return nil
+ }, &sql.TxOptions{ReadOnly: true})
+ if err != nil {
+ if errors.Is(err, team.ErrGrantRevoked) || errors.Is(err, gorm.ErrRecordNotFound) || errors.Is(err, ErrNotFound) {
+ return team.Admission{}, team.ErrGrantRevoked
+ }
+ return team.Admission{}, fmt.Errorf("%w: %w", team.ErrAuthorityUnavailable, err)
+ }
+ return admission, nil
+}
diff --git a/internal/equipotest/authority_test.go b/internal/equipotest/authority_test.go
new file mode 100644
index 00000000..5f0b9970
--- /dev/null
+++ b/internal/equipotest/authority_test.go
@@ -0,0 +1,356 @@
+package equipotest
+
+import (
+ "context"
+ "encoding/base64"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "path/filepath"
+ "strings"
+ "testing"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/equipo"
+ "amadan.net/oficina/equipo/internal/equipo/team"
+ "amadan.net/rastrillo/rastrillo/db"
+ "gorm.io/gorm"
+)
+
+var authorityOps = []team.Operation{team.OpJobContinue, team.OpAttemptContinue, team.OpProviderCall, team.OpForgePublish}
+
+func authorityFixture(t *testing.T) (*equipo.Store, *db.DB, equipo.Project, *team.FakeClock, *equipo.RosterAuthority, team.AdmissionRequest) {
+ t.Helper()
+ s, d, account := projectStore(t)
+ p := saveProject(t, s, projectInput(account), []equipo.DecisionOwner{{Decision: "work", Address: "member@example.com"}, {Decision: "merge", Address: ownerAddress}}, "authority-project")
+ var id string
+ if err := d.Writer().QueryRow("SELECT id FROM teams").Scan(&id); err != nil {
+ t.Fatal(err)
+ }
+ clock := team.NewFakeClock(time.Date(2026, 11, 1, 12, 0, 0, 0, time.UTC))
+ auth := equipo.NewAuthority(s, clock)
+ req := team.AdmissionRequest{Grant: equipo.GrantRef(p.ID, "member@example.com"), Account: team.AccountID(id), Operation: team.OpJobContinue,
+ Target: team.TargetBinding{Kind: team.TargetRepository, Repository: p.Repository, App: p.AppName, Ref: "review/task-6", DefaultRef: p.DefaultBranch, BaseRevision: "base"}}
+ return s, d, p, clock, auth, req
+}
+
+func requireAdmission(t *testing.T, auth *equipo.RosterAuthority, req team.AdmissionRequest) team.Admission {
+ t.Helper()
+ got, err := auth.Introspect(context.Background(), req)
+ if err != nil {
+ t.Fatalf("valid request refused: %v", err)
+ }
+ if got.Grant != req.Grant {
+ t.Fatalf("grant changed: %+v", got)
+ }
+ return got
+}
+func requireRevoked(t *testing.T, auth *equipo.RosterAuthority, req team.AdmissionRequest) {
+ t.Helper()
+ got, err := auth.Introspect(context.Background(), req)
+ if !errors.Is(err, team.ErrGrantRevoked) || errors.Is(err, team.ErrAuthorityUnavailable) {
+ t.Fatalf("uncovered request admitted or treated as outage: %v", err)
+ }
+ if got != (team.Admission{}) {
+ t.Fatalf("failed request returned admission: %+v", got)
+ }
+}
+
+func TestAuthorityUsesLiveRoster(t *testing.T) {
+ s, d, p, _, auth, req := authorityFixture(t)
+ for _, address := range []string{"member@example.com", ownerAddress} {
+ for _, op := range authorityOps {
+ r := req
+ r.Grant = equipo.GrantRef(p.ID, address)
+ r.Operation = op
+ requireAdmission(t, auth, r)
+ }
+ }
+ setMember(t, s, "routing@example.com", equipo.RoleMember, true)
+ owners := []equipo.DecisionOwner{{Decision: "work", Address: "member@example.com"}}
+ for _, decision := range []string{"merge", "copy", "design", "product"} {
+ owners = append(owners, equipo.DecisionOwner{Decision: decision, Address: "routing@example.com"})
+ }
+ p = saveProject(t, s, p, owners, "routing")
+ for _, address := range []string{"routing@example.com", "outsider@example.com"} {
+ r := req
+ r.Grant = equipo.GrantRef(p.ID, address)
+ for _, op := range authorityOps {
+ r.Operation = op
+ requireRevoked(t, auth, r)
+ }
+ }
+ p = saveProject(t, s, p, projectOwners(), "reassign")
+ requireRevoked(t, auth, req)
+ p = saveProject(t, s, p, []equipo.DecisionOwner{{Decision: "work", Address: ownerAddress}, {Decision: "merge", Address: ownerAddress}}, "unassign")
+ setMember(t, s, "member@example.com", equipo.RoleMember, false)
+ requireRevoked(t, auth, req)
+ // A stale assignment must not restore an inactive member's authority.
+ if err := d.G.Model(&equipo.DecisionOwner{}).Where("project_id = ? AND decision = ?", p.ID, "work").Update("address", "member@example.com").Error; err != nil {
+ t.Fatal(err)
+ }
+ requireRevoked(t, auth, req)
+ setMember(t, s, "second@example.com", equipo.RoleOwner, true)
+ r := req
+ r.Grant = equipo.GrantRef(p.ID, "second@example.com")
+ requireAdmission(t, auth, r)
+ setMember(t, s, "second@example.com", equipo.RoleMember, true)
+ requireRevoked(t, auth, r)
+ setMember(t, s, "second@example.com", equipo.RoleMember, false)
+ requireRevoked(t, auth, r)
+}
+
+func TestAuthorityRejectsMismatchedTarget(t *testing.T) {
+ s, _, p, _, auth, req := authorityFixture(t)
+ other := p
+ other.ID = 0
+ other.Revision = 0
+ other.Repository = "amadan.net/oficina/other"
+ other = saveProject(t, s, other, projectOwners(), "other")
+ cases := []struct {
+ name string
+ change func(*team.AdmissionRequest)
+ }{
+ {"unknown project", func(r *team.AdmissionRequest) { r.Grant = equipo.GrantRef(999, ownerAddress) }},
+ {"another project grant", func(r *team.AdmissionRequest) { r.Grant = equipo.GrantRef(other.ID, ownerAddress) }},
+ {"wrong team", func(r *team.AdmissionRequest) { r.Account = "another-team" }},
+ {"label account", func(r *team.AdmissionRequest) { r.Account = team.AccountID(fmt.Sprint(p.AccountID)) }},
+ {"wrong repository", func(r *team.AdmissionRequest) { r.Target.Repository = other.Repository }},
+ {"repository alias", func(r *team.AdmissionRequest) { r.Target.Repository = "https://" + p.Repository }},
+ {"repository traversal", func(r *team.AdmissionRequest) { r.Target.Repository = "amadan.net/oficina/../shop" }},
+ {"wrong app", func(r *team.AdmissionRequest) { r.Target.App = "other" }},
+ {"missing app", func(r *team.AdmissionRequest) { r.Target.App = "" }},
+ {"business", func(r *team.AdmissionRequest) {
+ r.Target = team.TargetBinding{Kind: team.TargetBusiness, Subject: "ledger"}
+ }},
+ {"unknown kind", func(r *team.AdmissionRequest) { r.Target.Kind = "unknown" }},
+ {"mixed target", func(r *team.AdmissionRequest) { r.Target.Subject = "ledger" }},
+ {"empty base", func(r *team.AdmissionRequest) { r.Target.BaseRevision = "" }},
+ {"wrong default", func(r *team.AdmissionRequest) { r.Target.DefaultRef = "other" }},
+ {"default branch", func(r *team.AdmissionRequest) { r.Target.Ref = p.DefaultBranch }},
+ {"forged default", func(r *team.AdmissionRequest) { r.Target.DefaultRef = "other"; r.Target.Ref = p.DefaultBranch }},
+ }
+ for _, branch := range []string{"", "refs/heads/review/task-6", "HEAD", "release/stable ", "review/../stable", "review//x", "review/x.lock", "review/x~1", "review/x\n"} {
+ cases = append(cases, struct {
+ name string
+ change func(*team.AdmissionRequest)
+ }{"invalid ref " + branch, func(r *team.AdmissionRequest) { r.Target.Ref = branch }})
+ }
+ for _, op := range authorityOps {
+ t.Run(string(op), func(t *testing.T) {
+ good := req
+ good.Operation = op
+ requireAdmission(t, auth, good)
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) { r := good; tc.change(&r); requireRevoked(t, auth, r) })
+ }
+ })
+ }
+ for _, op := range []team.Operation{"", "unknown", "forge.merge", team.OpTrackerPublish} {
+ r := req
+ r.Operation = op
+ requireRevoked(t, auth, r)
+ }
+}
+
+func TestAuthorityGrantReferences(t *testing.T) {
+ _, _, p, _, auth, req := authorityFixture(t)
+ ref := equipo.GrantRef(p.ID, " MEMBER@Example.com ")
+ if ref != req.Grant {
+ t.Fatal("address not canonical")
+ }
+ raw, err := base64.RawURLEncoding.DecodeString(ref)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var fields map[string]any
+ if err := json.Unmarshal(raw, &fields); err != nil {
+ t.Fatal(err)
+ }
+ if len(fields) != 3 || fields["version"] != float64(1) || fields["project_id"] != float64(p.ID) || fields["address"] != "member@example.com" {
+ t.Fatalf("unexpected reference content: %s", raw)
+ }
+ badJSON := []string{
+ `null`, `{}`, `{"version":2,"project_id":1,"address":"member@example.com"}`,
+ `{"version":1,"project_id":0,"address":"member@example.com"}`,
+ `{"version":1,"project_id":-1,"address":"member@example.com"}`,
+ `{"version":1,"project_id":1,"address":" MEMBER@example.com "}`,
+ `{"version":1,"project_id":1,"address":"invalid"}`,
+ string(raw) + `{}`, strings.TrimSuffix(string(raw), "}") + `,"role":"owner"}`,
+ strings.TrimSuffix(string(raw), "}") + `,"address":"member@example.com"}`,
+ }
+ badRefs := []string{"", "unknown", "%", ref + "=", ref + "\n", equipo.GrantRef(-1, ownerAddress), equipo.GrantRef(p.ID, "invalid")}
+ for _, value := range badJSON {
+ badRefs = append(badRefs, base64.RawURLEncoding.EncodeToString([]byte(value)))
+ }
+ for _, bad := range badRefs {
+ r := req
+ r.Grant = bad
+ requireRevoked(t, auth, r)
+ }
+}
+
+func TestAuthorityFailureIsNotRevocation(t *testing.T) {
+ _, d, _, clock, auth, req := authorityFixture(t)
+ for _, table := range []string{"teams", "projects", "members", "decision_owners"} {
+ t.Run(table, func(t *testing.T) {
+ name := "authority_failure"
+ if err := d.G.Callback().Query().Before("gorm:query").Register(name, func(tx *gorm.DB) {
+ if tx.Statement.Table == table {
+ tx.AddError(errors.New("injected read failure"))
+ }
+ }); err != nil {
+ t.Fatal(err)
+ }
+ defer d.G.Callback().Query().Remove(name)
+ got, err := auth.Introspect(context.Background(), req)
+ if !errors.Is(err, team.ErrAuthorityUnavailable) || errors.Is(err, team.ErrGrantRevoked) || got != (team.Admission{}) {
+ t.Fatalf("outage treated as revocation or admission: %+v %v", got, err)
+ }
+ })
+ }
+ ctx, cancel := context.WithCancel(context.Background())
+ cancel()
+ if _, err := auth.Introspect(ctx, req); !errors.Is(err, team.ErrAuthorityUnavailable) || errors.Is(err, team.ErrGrantRevoked) {
+ t.Fatal("cancelled lookup", err)
+ }
+ for _, broken := range []*equipo.RosterAuthority{nil, equipo.NewAuthority(nil, clock), equipo.NewAuthority(equipo.NewStore(nil), clock)} {
+ if _, err := broken.Introspect(context.Background(), req); !errors.Is(err, team.ErrAuthorityUnavailable) {
+ t.Fatal("missing store", err)
+ }
+ }
+ requireAdmission(t, auth, req)
+}
+
+func TestAuthoritySnapshotChanges(t *testing.T) {
+ s, d, p, clock, auth, req := authorityFixture(t)
+ beforeAudit := scalar(t, d, "SELECT count(*) FROM audit_events")
+ first := requireAdmission(t, auth, req)
+ if first.Version != p.Revision || first.Epoch != scalar(t, d, "SELECT roster_epoch FROM teams") || first.IssuedAt != clock.Now() || first.ExpiresAt.Sub(first.IssuedAt) != 5*time.Second {
+ t.Fatalf("bad snapshot or TTL: %+v", first)
+ }
+ p.Name = "Changed"
+ p = saveProject(t, s, p, []equipo.DecisionOwner{{Decision: "work", Address: "member@example.com"}, {Decision: "merge", Address: ownerAddress}}, "revision")
+ clock.Advance(time.Second)
+ second := requireAdmission(t, auth, req)
+ if second.Version != p.Revision || second.Version != first.Version+1 || second.Epoch != first.Epoch || second.IssuedAt != clock.Now() || second.ExpiresAt.Sub(second.IssuedAt) != 5*time.Second {
+ t.Fatalf("project edit snapshot: %+v", second)
+ }
+ setMember(t, s, "new@example.com", equipo.RoleMember, true)
+ third := requireAdmission(t, auth, req)
+ if third.Epoch != second.Epoch+1 || third.Version != second.Version {
+ t.Fatalf("roster edit snapshot: %+v", third)
+ }
+ if scalar(t, d, "SELECT count(*) FROM audit_events") != beforeAudit+2 {
+ t.Fatal("introspection wrote audit records")
+ }
+}
+
+func TestAuthorityReadsOneSnapshot(t *testing.T) {
+ s, d, p, _, auth, req := authorityFixture(t)
+ changed := false
+ var changedProject equipo.Project
+ if err := d.G.Callback().Query().After("gorm:query").Register("authority_snapshot", func(tx *gorm.DB) {
+ if tx.Statement.Table != "projects" || changed {
+ return
+ }
+ changed = true
+ changedProject = saveProject(t, s, p, projectOwners(), "concurrent-reassign")
+ }); err != nil {
+ t.Fatal(err)
+ }
+ defer d.G.Callback().Query().Remove("authority_snapshot")
+ adm := requireAdmission(t, auth, req)
+ if !changed || adm.Version != p.Revision || changedProject.Revision != p.Revision+1 {
+ t.Fatal("snapshot did not span concurrent edit", adm)
+ }
+ requireRevoked(t, auth, req)
+}
+
+func TestAuthorityCoreIntegration(t *testing.T) {
+ for _, change := range []string{"project revision", "roster epoch", "work reassigned"} {
+ t.Run(change, func(t *testing.T) {
+ ctx := context.Background()
+ s, _, p, clock, auth, req := authorityFixture(t)
+ core, err := team.Open(ctx, filepath.Join(t.TempDir(), "authority-core.db"), team.Options{Clock: clock, Authority: auth, Adapters: map[team.Operation]team.Adapter{team.OpProviderCall: team.NewFakeProvider("fixture", "fixture", nil), team.OpForgePublish: team.NewFakeForge()}})
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() {
+ if err := core.Close(); err != nil {
+ t.Error(err)
+ }
+ })
+ if _, err := core.Resume(ctx); err != nil {
+ t.Fatal(err)
+ }
+ job, err := core.CreateJob(ctx, team.JobSpec{Account: req.Account, Project: team.ProjectID(p.ID), Requester: "member@example.com", GrantRef: req.Grant, Target: req.Target,
+ Evidence: team.EvidenceRequirement{Predicate: team.PredicateSoftwareFix, ExpectedSymptom: "fixture", CheckDefinitionHash: "fixture"}, Policy: team.DefaultPolicy(1000000, team.Rates{Version: 1, CallMicrosPer: 1}), Steps: team.SoftwareSteps(false)})
+ if err != nil {
+ t.Fatal(err)
+ }
+ scope := team.Scope{Account: req.Account, Job: job.ID}
+ h, err := core.Claim(ctx, scope, "reproduce", "fixture", "fixture-workspace")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err := core.Renew(ctx, scope, h); err != nil {
+ t.Fatal(err)
+ }
+ want := team.ErrGrantStale
+ switch change {
+ case "project revision":
+ p.Name = "Changed"
+ saveProject(t, s, p, []equipo.DecisionOwner{{Decision: "work", Address: "member@example.com"}, {Decision: "merge", Address: ownerAddress}}, "edit")
+ case "roster epoch":
+ setMember(t, s, "new@example.com", equipo.RoleMember, true)
+ case "work reassigned":
+ saveProject(t, s, p, projectOwners(), "reassign")
+ want = team.ErrGrantRevoked
+ }
+ if _, err := core.Renew(ctx, scope, h); !errors.Is(err, want) {
+ t.Fatalf("changed authority did not block next admission: %v, want %v", err, want)
+ }
+ })
+ }
+}
+
+func TestAuthorityProjectOwnershipIsLocal(t *testing.T) {
+ s, d, p, _, auth, req := authorityFixture(t)
+ other := p
+ other.ID, other.Revision = 0, 0
+ other.AppName = "other"
+ other = saveProject(t, s, other, projectOwners(), "other-app")
+ r := req
+ r.Grant = equipo.GrantRef(other.ID, "member@example.com")
+ r.Target.App = other.AppName
+ requireRevoked(t, auth, r)
+ requireAdmission(t, auth, req)
+ if err := d.G.Where("project_id = ? AND decision = ?", p.ID, "work").Delete(&equipo.DecisionOwner{}).Error; err != nil {
+ t.Fatal(err)
+ }
+ requireRevoked(t, auth, req)
+ r = req
+ r.Grant = equipo.GrantRef(p.ID, ownerAddress)
+ requireAdmission(t, auth, r)
+}
+
+func TestAuthorityProjectKinds(t *testing.T) {
+ s, _, p, _, auth, req := authorityFixture(t)
+ for _, kind := range []equipo.ProjectKind{equipo.ProjectRepository, equipo.ProjectWebsite} {
+ other := p
+ other.ID, other.Revision = 0, 0
+ other.Repository = "amadan.net/oficina/" + string(kind)
+ other.Kind, other.AppName = kind, ""
+ other = saveProject(t, s, other, projectOwners(), string(kind))
+ r := req
+ r.Grant = equipo.GrantRef(other.ID, ownerAddress)
+ r.Target.Repository, r.Target.App = other.Repository, ""
+ for _, op := range authorityOps {
+ r.Operation = op
+ requireAdmission(t, auth, r)
+ }
+ r.Target.App = "invented"
+ requireRevoked(t, auth, r)
+ }
+}