| 1 | package equipotest |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "encoding/base64" |
| 6 | "encoding/json" |
| 7 | "errors" |
| 8 | "fmt" |
| 9 | "path/filepath" |
| 10 | "strings" |
| 11 | "testing" |
| 12 | "time" |
| 13 | |
| 14 | "amadan.net/oficina/equipo/internal/equipo" |
| 15 | "amadan.net/oficina/equipo/internal/equipo/team" |
| 16 | "amadan.net/rastrillo/rastrillo/db" |
| 17 | "gorm.io/gorm" |
| 18 | ) |
| 19 | |
| 20 | var authorityOps = []team.Operation{team.OpJobContinue, team.OpAttemptContinue, team.OpProviderCall, team.OpForgePublish} |
| 21 | |
| 22 | func authorityFixture(t *testing.T) (*equipo.Store, *db.DB, equipo.Project, *team.FakeClock, *equipo.RosterAuthority, team.AdmissionRequest) { |
| 23 | t.Helper() |
| 24 | s, d, account := projectStore(t) |
| 25 | p := saveProject(t, s, projectInput(account), []equipo.DecisionOwner{{Decision: "work", Address: "member@example.com"}, {Decision: "merge", Address: ownerAddress}}, "authority-project") |
| 26 | var id string |
| 27 | if err := d.Writer().QueryRow("SELECT id FROM teams").Scan(&id); err != nil { |
| 28 | t.Fatal(err) |
| 29 | } |
| 30 | clock := team.NewFakeClock(time.Date(2026, 11, 1, 12, 0, 0, 0, time.UTC)) |
| 31 | auth := equipo.NewAuthority(s, clock) |
| 32 | req := team.AdmissionRequest{Project: team.ProjectID(p.ID), Grant: equipo.GrantRef(p.ID, "member@example.com"), Account: team.AccountID(id), Operation: team.OpJobContinue, |
| 33 | Target: team.TargetBinding{Kind: team.TargetRepository, Repository: p.Repository, App: p.AppName, Ref: "review/task-6", DefaultRef: p.DefaultBranch, BaseRevision: "base"}} |
| 34 | return s, d, p, clock, auth, req |
| 35 | } |
| 36 | |
| 37 | func requireAdmission(t *testing.T, auth *equipo.RosterAuthority, req team.AdmissionRequest) team.Admission { |
| 38 | t.Helper() |
| 39 | got, err := auth.Introspect(context.Background(), req) |
| 40 | if err != nil { |
| 41 | t.Fatalf("valid request refused: %v", err) |
| 42 | } |
| 43 | if got.Grant != req.Grant { |
| 44 | t.Fatalf("grant changed: %+v", got) |
| 45 | } |
| 46 | return got |
| 47 | } |
| 48 | func requireRevoked(t *testing.T, auth *equipo.RosterAuthority, req team.AdmissionRequest) { |
| 49 | t.Helper() |
| 50 | got, err := auth.Introspect(context.Background(), req) |
| 51 | if !errors.Is(err, team.ErrGrantRevoked) || errors.Is(err, team.ErrAuthorityUnavailable) { |
| 52 | t.Fatalf("uncovered request admitted or treated as outage: %v", err) |
| 53 | } |
| 54 | if got != (team.Admission{}) { |
| 55 | t.Fatalf("failed request returned admission: %+v", got) |
| 56 | } |
| 57 | } |
| 58 | |
| 59 | func TestAuthorityUsesLiveRoster(t *testing.T) { |
| 60 | t.Parallel() |
| 61 | s, d, p, _, auth, req := authorityFixture(t) |
| 62 | for _, address := range []string{"member@example.com", ownerAddress} { |
| 63 | for _, op := range authorityOps { |
| 64 | r := req |
| 65 | r.Grant = equipo.GrantRef(p.ID, address) |
| 66 | r.Operation = op |
| 67 | requireAdmission(t, auth, r) |
| 68 | } |
| 69 | } |
| 70 | setMember(t, s, "routing@example.com", equipo.RoleMember, true) |
| 71 | owners := []equipo.DecisionOwner{{Decision: "work", Address: "member@example.com"}} |
| 72 | for _, decision := range []string{"merge", "copy", "design", "product"} { |
| 73 | owners = append(owners, equipo.DecisionOwner{Decision: decision, Address: "routing@example.com"}) |
| 74 | } |
| 75 | p = saveProject(t, s, p, owners, "routing") |
| 76 | for _, address := range []string{"routing@example.com", "outsider@example.com"} { |
| 77 | r := req |
| 78 | r.Grant = equipo.GrantRef(p.ID, address) |
| 79 | for _, op := range authorityOps { |
| 80 | r.Operation = op |
| 81 | requireRevoked(t, auth, r) |
| 82 | } |
| 83 | } |
| 84 | p = saveProject(t, s, p, projectOwners(), "reassign") |
| 85 | requireRevoked(t, auth, req) |
| 86 | p = saveProject(t, s, p, []equipo.DecisionOwner{{Decision: "work", Address: ownerAddress}, {Decision: "merge", Address: ownerAddress}}, "unassign") |
| 87 | setMember(t, s, "member@example.com", equipo.RoleMember, false) |
| 88 | requireRevoked(t, auth, req) |
| 89 | // A stale assignment must not restore an inactive member's authority. |
| 90 | if err := d.G.Model(&equipo.DecisionOwner{}).Where("project_id = ? AND decision = ?", p.ID, "work").Update("address", "member@example.com").Error; err != nil { |
| 91 | t.Fatal(err) |
| 92 | } |
| 93 | requireRevoked(t, auth, req) |
| 94 | setMember(t, s, "second@example.com", equipo.RoleOwner, true) |
| 95 | r := req |
| 96 | r.Grant = equipo.GrantRef(p.ID, "second@example.com") |
| 97 | requireAdmission(t, auth, r) |
| 98 | setMember(t, s, "second@example.com", equipo.RoleMember, true) |
| 99 | requireRevoked(t, auth, r) |
| 100 | setMember(t, s, "second@example.com", equipo.RoleMember, false) |
| 101 | requireRevoked(t, auth, r) |
| 102 | } |
| 103 | |
| 104 | func TestAuthorityRejectsMismatchedTarget(t *testing.T) { |
| 105 | t.Parallel() |
| 106 | s, _, p, _, auth, req := authorityFixture(t) |
| 107 | other := p |
| 108 | other.ID = 0 |
| 109 | other.Revision = 0 |
| 110 | other.Repository = "amadan.net/oficina/other" |
| 111 | other = saveProject(t, s, other, projectOwners(), "other") |
| 112 | cases := []struct { |
| 113 | name string |
| 114 | change func(*team.AdmissionRequest) |
| 115 | }{ |
| 116 | {"unknown project", func(r *team.AdmissionRequest) { r.Grant = equipo.GrantRef(999, ownerAddress) }}, |
| 117 | {"another project grant", func(r *team.AdmissionRequest) { |
| 118 | r.Project = team.ProjectID(other.ID) |
| 119 | r.Grant = equipo.GrantRef(other.ID, ownerAddress) |
| 120 | }}, |
| 121 | {"wrong team", func(r *team.AdmissionRequest) { r.Account = "another-team" }}, |
| 122 | {"label account", func(r *team.AdmissionRequest) { r.Account = team.AccountID(fmt.Sprint(p.AccountID)) }}, |
| 123 | {"wrong repository", func(r *team.AdmissionRequest) { r.Target.Repository = other.Repository }}, |
| 124 | {"repository alias", func(r *team.AdmissionRequest) { r.Target.Repository = "https://" + p.Repository }}, |
| 125 | {"repository traversal", func(r *team.AdmissionRequest) { r.Target.Repository = "amadan.net/oficina/../shop" }}, |
| 126 | {"wrong app", func(r *team.AdmissionRequest) { r.Target.App = "other" }}, |
| 127 | {"missing app", func(r *team.AdmissionRequest) { r.Target.App = "" }}, |
| 128 | {"business", func(r *team.AdmissionRequest) { |
| 129 | r.Target = team.TargetBinding{Kind: team.TargetBusiness, Subject: "ledger"} |
| 130 | }}, |
| 131 | {"unknown kind", func(r *team.AdmissionRequest) { r.Target.Kind = "unknown" }}, |
| 132 | {"mixed target", func(r *team.AdmissionRequest) { r.Target.Subject = "ledger" }}, |
| 133 | {"empty base", func(r *team.AdmissionRequest) { r.Target.BaseRevision = "" }}, |
| 134 | {"wrong default", func(r *team.AdmissionRequest) { r.Target.DefaultRef = "other" }}, |
| 135 | {"default branch", func(r *team.AdmissionRequest) { r.Target.Ref = p.DefaultBranch }}, |
| 136 | {"forged default", func(r *team.AdmissionRequest) { r.Target.DefaultRef = "other"; r.Target.Ref = p.DefaultBranch }}, |
| 137 | } |
| 138 | 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"} { |
| 139 | cases = append(cases, struct { |
| 140 | name string |
| 141 | change func(*team.AdmissionRequest) |
| 142 | }{"invalid ref " + branch, func(r *team.AdmissionRequest) { r.Target.Ref = branch }}) |
| 143 | } |
| 144 | for _, op := range authorityOps { |
| 145 | t.Run(string(op), func(t *testing.T) { |
| 146 | good := req |
| 147 | good.Operation = op |
| 148 | requireAdmission(t, auth, good) |
| 149 | for _, tc := range cases { |
| 150 | t.Run(tc.name, func(t *testing.T) { r := good; tc.change(&r); requireRevoked(t, auth, r) }) |
| 151 | } |
| 152 | }) |
| 153 | } |
| 154 | for _, op := range []team.Operation{"", "unknown", "forge.merge", team.OpTrackerPublish} { |
| 155 | r := req |
| 156 | r.Operation = op |
| 157 | requireRevoked(t, auth, r) |
| 158 | } |
| 159 | } |
| 160 | |
| 161 | func TestAuthorityGrantReferences(t *testing.T) { |
| 162 | t.Parallel() |
| 163 | _, _, p, _, auth, req := authorityFixture(t) |
| 164 | ref := equipo.GrantRef(p.ID, " MEMBER@Example.com ") |
| 165 | if ref != req.Grant { |
| 166 | t.Fatal("address not canonical") |
| 167 | } |
| 168 | raw, err := base64.RawURLEncoding.DecodeString(ref) |
| 169 | if err != nil { |
| 170 | t.Fatal(err) |
| 171 | } |
| 172 | var fields map[string]any |
| 173 | if err := json.Unmarshal(raw, &fields); err != nil { |
| 174 | t.Fatal(err) |
| 175 | } |
| 176 | if len(fields) != 3 || fields["version"] != float64(1) || fields["project_id"] != float64(p.ID) || fields["address"] != "member@example.com" { |
| 177 | t.Fatalf("unexpected reference content: %s", raw) |
| 178 | } |
| 179 | badJSON := []string{ |
| 180 | `null`, `{}`, `{"version":2,"project_id":1,"address":"member@example.com"}`, |
| 181 | `{"version":1,"project_id":0,"address":"member@example.com"}`, |
| 182 | `{"version":1,"project_id":-1,"address":"member@example.com"}`, |
| 183 | `{"version":1,"project_id":1,"address":" MEMBER@example.com "}`, |
| 184 | `{"version":1,"project_id":1,"address":"invalid"}`, |
| 185 | string(raw) + `{}`, strings.TrimSuffix(string(raw), "}") + `,"role":"owner"}`, |
| 186 | strings.TrimSuffix(string(raw), "}") + `,"address":"member@example.com"}`, |
| 187 | } |
| 188 | badRefs := []string{"", "unknown", "%", ref + "=", ref + "\n", equipo.GrantRef(-1, ownerAddress), equipo.GrantRef(p.ID, "invalid")} |
| 189 | for _, value := range badJSON { |
| 190 | badRefs = append(badRefs, base64.RawURLEncoding.EncodeToString([]byte(value))) |
| 191 | } |
| 192 | for _, bad := range badRefs { |
| 193 | r := req |
| 194 | r.Grant = bad |
| 195 | requireRevoked(t, auth, r) |
| 196 | } |
| 197 | } |
| 198 | |
| 199 | func TestAuthorityFailureIsNotRevocation(t *testing.T) { |
| 200 | t.Parallel() |
| 201 | _, d, _, clock, auth, req := authorityFixture(t) |
| 202 | for _, table := range []string{"teams", "projects", "members", "decision_owners"} { |
| 203 | t.Run(table, func(t *testing.T) { |
| 204 | name := "authority_failure" |
| 205 | if err := d.G.Callback().Query().Before("gorm:query").Register(name, func(tx *gorm.DB) { |
| 206 | if tx.Statement.Table == table { |
| 207 | tx.AddError(errors.New("injected read failure")) |
| 208 | } |
| 209 | }); err != nil { |
| 210 | t.Fatal(err) |
| 211 | } |
| 212 | defer d.G.Callback().Query().Remove(name) |
| 213 | got, err := auth.Introspect(context.Background(), req) |
| 214 | if !errors.Is(err, team.ErrAuthorityUnavailable) || errors.Is(err, team.ErrGrantRevoked) || got != (team.Admission{}) { |
| 215 | t.Fatalf("outage treated as revocation or admission: %+v %v", got, err) |
| 216 | } |
| 217 | }) |
| 218 | } |
| 219 | ctx, cancel := context.WithCancel(context.Background()) |
| 220 | cancel() |
| 221 | if _, err := auth.Introspect(ctx, req); !errors.Is(err, team.ErrAuthorityUnavailable) || errors.Is(err, team.ErrGrantRevoked) { |
| 222 | t.Fatal("cancelled lookup", err) |
| 223 | } |
| 224 | for _, broken := range []*equipo.RosterAuthority{nil, equipo.NewAuthority(nil, clock), equipo.NewAuthority(equipo.NewStore(nil), clock)} { |
| 225 | if _, err := broken.Introspect(context.Background(), req); !errors.Is(err, team.ErrAuthorityUnavailable) { |
| 226 | t.Fatal("missing store", err) |
| 227 | } |
| 228 | } |
| 229 | requireAdmission(t, auth, req) |
| 230 | } |
| 231 | |
| 232 | func TestAuthoritySnapshotChanges(t *testing.T) { |
| 233 | t.Parallel() |
| 234 | s, d, p, clock, auth, req := authorityFixture(t) |
| 235 | beforeAudit := scalar(t, d, "SELECT count(*) FROM audit_events") |
| 236 | first := requireAdmission(t, auth, req) |
| 237 | 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 { |
| 238 | t.Fatalf("bad snapshot or TTL: %+v", first) |
| 239 | } |
| 240 | p.Name = "Changed" |
| 241 | p = saveProject(t, s, p, []equipo.DecisionOwner{{Decision: "work", Address: "member@example.com"}, {Decision: "merge", Address: ownerAddress}}, "revision") |
| 242 | clock.Advance(time.Second) |
| 243 | second := requireAdmission(t, auth, req) |
| 244 | 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 { |
| 245 | t.Fatalf("project edit snapshot: %+v", second) |
| 246 | } |
| 247 | setMember(t, s, "new@example.com", equipo.RoleMember, true) |
| 248 | third := requireAdmission(t, auth, req) |
| 249 | if third.Epoch != second.Epoch+1 || third.Version != second.Version { |
| 250 | t.Fatalf("roster edit snapshot: %+v", third) |
| 251 | } |
| 252 | if scalar(t, d, "SELECT count(*) FROM audit_events") != beforeAudit+2 { |
| 253 | t.Fatal("introspection wrote audit records") |
| 254 | } |
| 255 | } |
| 256 | |
| 257 | func TestAuthorityReadsOneSnapshot(t *testing.T) { |
| 258 | t.Parallel() |
| 259 | s, d, p, _, auth, req := authorityFixture(t) |
| 260 | changed := false |
| 261 | var changedProject equipo.Project |
| 262 | if err := d.G.Callback().Query().After("gorm:query").Register("authority_snapshot", func(tx *gorm.DB) { |
| 263 | if tx.Statement.Table != "projects" || changed { |
| 264 | return |
| 265 | } |
| 266 | changed = true |
| 267 | changedProject = saveProject(t, s, p, projectOwners(), "concurrent-reassign") |
| 268 | }); err != nil { |
| 269 | t.Fatal(err) |
| 270 | } |
| 271 | defer d.G.Callback().Query().Remove("authority_snapshot") |
| 272 | adm := requireAdmission(t, auth, req) |
| 273 | if !changed || adm.Version != p.Revision || changedProject.Revision != p.Revision+1 { |
| 274 | t.Fatal("snapshot did not span concurrent edit", adm) |
| 275 | } |
| 276 | requireRevoked(t, auth, req) |
| 277 | } |
| 278 | |
| 279 | func TestAuthorityCoreIntegration(t *testing.T) { |
| 280 | t.Parallel() |
| 281 | for _, change := range []string{"project revision", "roster epoch", "work reassigned"} { |
| 282 | t.Run(change, func(t *testing.T) { |
| 283 | ctx := context.Background() |
| 284 | s, _, p, clock, auth, req := authorityFixture(t) |
| 285 | 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()}}) |
| 286 | if err != nil { |
| 287 | t.Fatal(err) |
| 288 | } |
| 289 | t.Cleanup(func() { |
| 290 | if err := core.Close(); err != nil { |
| 291 | t.Error(err) |
| 292 | } |
| 293 | }) |
| 294 | if _, err := core.Resume(ctx); err != nil { |
| 295 | t.Fatal(err) |
| 296 | } |
| 297 | 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, |
| 298 | Evidence: team.EvidenceRequirement{Predicate: team.PredicateSoftwareFix, ExpectedSymptom: "fixture", CheckDefinitionHash: "fixture"}, Policy: team.DefaultPolicy(1000000, team.Rates{Version: 1, CallMicrosPer: 1}), Steps: team.SoftwareSteps(false)}) |
| 299 | if err != nil { |
| 300 | t.Fatal(err) |
| 301 | } |
| 302 | scope := team.Scope{Account: req.Account, Job: job.ID} |
| 303 | h, err := core.Claim(ctx, scope, "reproduce", "fixture", "fixture-workspace") |
| 304 | if err != nil { |
| 305 | t.Fatal(err) |
| 306 | } |
| 307 | if _, err := core.Renew(ctx, scope, h); err != nil { |
| 308 | t.Fatal(err) |
| 309 | } |
| 310 | want := team.ErrGrantStale |
| 311 | switch change { |
| 312 | case "project revision": |
| 313 | p.DefaultBranch = "trunk" |
| 314 | want = team.ErrGrantRevoked |
| 315 | saveProject(t, s, p, []equipo.DecisionOwner{{Decision: "work", Address: "member@example.com"}, {Decision: "merge", Address: ownerAddress}}, "edit") |
| 316 | case "roster epoch": |
| 317 | setMember(t, s, "new@example.com", equipo.RoleMember, true) |
| 318 | case "work reassigned": |
| 319 | saveProject(t, s, p, projectOwners(), "reassign") |
| 320 | want = team.ErrGrantRevoked |
| 321 | } |
| 322 | if _, err := core.Renew(ctx, scope, h); !errors.Is(err, want) { |
| 323 | t.Fatalf("changed authority did not block next admission: %v, want %v", err, want) |
| 324 | } |
| 325 | }) |
| 326 | } |
| 327 | } |
| 328 | |
| 329 | func TestAuthorityProjectOwnershipIsLocal(t *testing.T) { |
| 330 | t.Parallel() |
| 331 | s, d, p, _, auth, req := authorityFixture(t) |
| 332 | other := p |
| 333 | other.ID, other.Revision = 0, 0 |
| 334 | other.AppName = "other" |
| 335 | other = saveProject(t, s, other, projectOwners(), "other-app") |
| 336 | r := req |
| 337 | r.Grant = equipo.GrantRef(other.ID, "member@example.com") |
| 338 | r.Target.App = other.AppName |
| 339 | requireRevoked(t, auth, r) |
| 340 | requireAdmission(t, auth, req) |
| 341 | if err := d.G.Where("project_id = ? AND decision = ?", p.ID, "work").Delete(&equipo.DecisionOwner{}).Error; err != nil { |
| 342 | t.Fatal(err) |
| 343 | } |
| 344 | requireRevoked(t, auth, req) |
| 345 | r = req |
| 346 | r.Grant = equipo.GrantRef(p.ID, ownerAddress) |
| 347 | requireAdmission(t, auth, r) |
| 348 | } |
| 349 | |
| 350 | func TestAuthorityProjectKinds(t *testing.T) { |
| 351 | t.Parallel() |
| 352 | s, _, p, _, auth, req := authorityFixture(t) |
| 353 | for _, kind := range []equipo.ProjectKind{equipo.ProjectRepository, equipo.ProjectWebsite} { |
| 354 | other := p |
| 355 | other.ID, other.Revision = 0, 0 |
| 356 | other.Repository = "amadan.net/oficina/" + string(kind) |
| 357 | other.Kind, other.AppName = kind, "" |
| 358 | other = saveProject(t, s, other, projectOwners(), string(kind)) |
| 359 | r := req |
| 360 | r.Project = team.ProjectID(other.ID) |
| 361 | r.Grant = equipo.GrantRef(other.ID, ownerAddress) |
| 362 | r.Target.Repository, r.Target.App = other.Repository, "" |
| 363 | for _, op := range authorityOps { |
| 364 | r.Operation = op |
| 365 | requireAdmission(t, auth, r) |
| 366 | } |
| 367 | r.Target.App = "invented" |
| 368 | requireRevoked(t, auth, r) |
| 369 | } |
| 370 | } |
| 371 | |