package equipotest import ( "context" "errors" "fmt" "html" "net/http" "net/url" "os" "path/filepath" "strings" "sync" "testing" "testing/fstest" "time" "amadan.net/oficina/equipo/internal/equipo" "amadan.net/rastrillo/rastrillo" "amadan.net/rastrillo/rastrillo/migrate" ) func TestRefusalReasons(t *testing.T) { f, c := pageOwner(t) check := func(path string, form url.Values, status int, message string) { t.Helper() res := clientPost(t, c, f.server.URL+path, testOrigin, form) body := html.UnescapeString(readBody(t, res)) if res.StatusCode != status || !strings.Contains(body, message) { t.Errorf("%s: status %d want %d; missing message %q", path, res.StatusCode, status, message) } } for _, change := range []struct{ role, active string }{{"member", "true"}, {"owner", "false"}} { check("/team/members", url.Values{"address": {ownerAddress}, "role": {change.role}, "active": {change.active}, "revision": {"1"}}, 403, "Add another owner before changing or removing the last owner.") } setMember(t, f.store, memberAddress, equipo.RoleMember, true) a, err := f.store.SaveAccount(context.Background(), ownerActor, equipo.Account{Label: "Oficina"}) if err != nil { t.Fatal(err) } p := projectInput(a) _, err = f.store.SaveProject(context.Background(), ownerActor, p, []equipo.DecisionOwner{{Decision: "work", Address: ownerAddress}, {Decision: "merge", Address: memberAddress}}, "first") if err != nil { t.Fatal(err) } check("/team/members", url.Values{"address": {memberAddress}, "role": {"member"}, "active": {"false"}, "revision": {"1"}}, 409, "Reassign this person's project decisions before removing them.") check("/projects", url.Values{"account_id": {fmt.Sprint(a.ID)}, "name": {"Duplicate"}, "kind": {"app"}, "repository": {p.Repository}, "app_name": {p.AppName}, "default_branch": {"main"}, "owner_work": {ownerAddress}, "owner_merge": {memberAddress}, "request_id": {"second"}, "revision": {"0"}}, 409, "Another project uses this repository and app. Choose a different pair.") check("/accounts", url.Values{"label": {" oficina "}, "id": {"0"}, "revision": {"0"}}, 409, "This account label already exists. Use it or choose another label.") } func TestAccountLabelDuplicates(t *testing.T) { t.Parallel() s, d, a := projectStore(t) before := scalar(t, d, "SELECT count(*) FROM audit_events") for _, label := range []string{"Oficina", " oficina ", "OFICINA"} { if _, err := s.SaveAccount(context.Background(), ownerActor, equipo.Account{Label: label}); !errors.Is(err, equipo.ErrConflict) { t.Errorf("duplicate %q: %v", label, err) } } if scalar(t, d, "SELECT count(*) FROM accounts") != 1 || scalar(t, d, "SELECT count(*) FROM audit_events") != before { t.Fatal("duplicate changed records or audit") } b, err := s.SaveAccount(context.Background(), ownerActor, equipo.Account{Label: "Other"}) if err != nil { t.Fatal(err) } b.Label = " oficina " if _, err := s.SaveAccount(context.Background(), ownerActor, b); !errors.Is(err, equipo.ErrConflict) { t.Fatal("duplicate rename", err) } // A retry of a rename to its own label is still allowed at the current revision. a.Label = " OFICINA " if _, err := s.SaveAccount(context.Background(), ownerActor, a); err != nil { t.Fatal(err) } for _, query := range []string{"INSERT INTO accounts(label, revision) VALUES (' oficina ', 1)", "UPDATE accounts SET label='oficina' WHERE label='Other'"} { if _, err := d.Writer().Exec(query); err == nil { t.Error("database accepted duplicate", query) } } } func TestBootstrapNamesOwnersSetting(t *testing.T) { t.Parallel() for _, owners := range [][]string{nil, {""}, {"not-an-address"}} { s, d := rosterStore(t) err := s.Bootstrap(context.Background(), owners) if !errors.Is(err, equipo.ErrInvalid) || !strings.Contains(err.Error(), "EQUIPO_OWNERS") { t.Errorf("boot refusal: %v", err) } if scalar(t, d, "SELECT count(*) FROM teams") != 0 { t.Fatal("invalid bootstrap persisted team") } } } func TestConfigureRejectsWrongRoot(t *testing.T) { defer func() { if recover() == nil { t.Error("Configure accepted a non-Equipo root") } }() mux := http.NewServeMux() mux.HandleFunc("/", func(http.ResponseWriter, *http.Request) {}) equipo.Configure(&rastrillo.Options{}, mux, time.Now()) } func TestUnavailableUsageAndErrorParents(t *testing.T) { f, c := pageOwner(t) for _, path := range []string{"/projects/accounts", "/settings"} { body := pageBody(t, c, f.server.URL, path) if !strings.Contains(body, `data-usage="unavailable"`) || strings.Contains(body, `data-usage="0"`) { t.Errorf("%s: unknown usage presented as zero", path) } } setMember(t, f.store, "second@example.com", equipo.RoleOwner, true) setMember(t, f.store, ownerAddress, equipo.RoleMember, true) res := clientGet(t, c, f.server.URL+"/projects/new") body := html.UnescapeString(readBody(t, res)) if res.StatusCode != 403 || !strings.Contains(body, `Back to the form`) { t.Errorf("403 has no project parent: %d", res.StatusCode) } } func TestAccountLabelMigration(t *testing.T) { t.Parallel() for _, duplicate := range []bool{false, true} { t.Run(fmt.Sprint(duplicate), func(t *testing.T) { d, _ := foundationDB(t) fs := fstest.MapFS{} paths, err := filepath.Glob("../equipo/migrations/000[1-5]_*.sql") if err != nil || len(paths) != 5 { t.Fatal("old migrations", paths, err) } for _, path := range paths { data, err := os.ReadFile(path) if err != nil { t.Fatal(err) } fs["migrations/"+filepath.Base(path)] = &fstest.MapFile{Data: data} } old := migrate.MustFromFS(fs, "equipo") if _, err := migrate.Apply(context.Background(), d, old); err != nil { t.Fatal(err) } if _, err := d.Writer().Exec("INSERT INTO accounts(id,label,revision) VALUES (1,'Oficina',3)"); err != nil { t.Fatal(err) } if duplicate { if _, err := d.Writer().Exec("INSERT INTO accounts(id,label,revision) VALUES (2,' oficina ',1)"); err != nil { t.Fatal(err) } } _, err = migrate.Apply(context.Background(), d, equipo.Schema) if duplicate { if err == nil { t.Fatal("migration silently accepted legacy duplicates") } if scalar(t, d, "SELECT count(*) FROM accounts") != 2 { t.Fatal("migration deleted legacy accounts") } // An owner can rename the duplicate on the old app before retrying. if _, err := d.Writer().Exec("UPDATE accounts SET label='Other' WHERE id=2"); err != nil { t.Fatal(err) } if _, err := migrate.Apply(context.Background(), d, equipo.Schema); err != nil { t.Fatal(err) } } else if err != nil { t.Fatal(err) } if scalar(t, d, "SELECT revision FROM accounts WHERE id=1 AND label='Oficina'") != 3 { t.Fatal("migration changed account") } if _, err := d.Writer().Exec("INSERT INTO accounts(label,revision) VALUES (' OFICINA ',1)"); err == nil { t.Fatal("migration did not enforce uniqueness") } if result, err := migrate.Apply(context.Background(), d, equipo.Schema); err != nil || len(result.Applied) != 0 { t.Fatal("migration repeated", result, err) } }) } } func TestAccountConcurrentDuplicate(t *testing.T) { t.Parallel() s, d, _ := projectStore(t) var wg sync.WaitGroup results := make(chan error, 8) for i := 0; i < 8; i++ { wg.Add(1) go func() { defer wg.Done() _, err := s.SaveAccount(context.Background(), ownerActor, equipo.Account{Label: "Concurrent"}) results <- err }() } wg.Wait() close(results) saved := 0 for err := range results { if err == nil { saved++ } else if !errors.Is(err, equipo.ErrAccountLabelExists) { t.Fatal(err) } } if saved != 1 || scalar(t, d, "SELECT count(*) FROM accounts WHERE label='Concurrent'") != 1 { t.Fatal("concurrent duplicate saved", saved) } } func TestRefusalCategories(t *testing.T) { for _, tc := range []struct{ specific, category error }{ {equipo.ErrDecisionOwnerAssigned, equipo.ErrConflict}, {equipo.ErrBindingInUse, equipo.ErrConflict}, {equipo.ErrLastOwner, equipo.ErrForbidden}, {equipo.ErrAccountLabelExists, equipo.ErrConflict}, {equipo.ErrBootstrapOwners, equipo.ErrInvalid}, } { if tc.specific == tc.category || !errors.Is(tc.specific, tc.category) { t.Errorf("lost category: %v", tc.specific) } } }