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{Project: team.ProjectID(p.ID), 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) { t.Parallel() 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) { t.Parallel() 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.Project = team.ProjectID(other.ID) 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) { t.Parallel() _, _, 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) { t.Parallel() _, 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) { t.Parallel() 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.GrantVersion || second.Version != first.Version || 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) { t.Parallel() 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) { t.Parallel() 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.DefaultBranch = "trunk" want = team.ErrGrantRevoked 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) { t.Parallel() 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) { t.Parallel() 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.Project = team.ProjectID(other.ID) 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) } }