fix: explain refusals and reject duplicate account labels
Preserve error categories while giving roster and binding refusals their real reason. Add account-label uniqueness, exact restored-session checks, and boot, layout, usage and error-navigation guards.
16 files changed,
+318
−21
cmd/equipo/main.go+3 −1internal/equipo/app.go+4 −2internal/equipo/copy.go+14 −0internal/equipo/handlers.go+13 −1internal/equipo/migrations/0006_account_label.sql+1 −0internal/equipo/migrations/schema.sql+2 −0internal/equipo/models.go+1 −1internal/equipo/projects.go+10 −3internal/equipo/render.go+4 −1internal/equipo/roster.go+4 −4internal/equipo/store.go+15 −1internal/equipo/templates/projects.html+1 −1internal/equipo/templates/settings.html+1 −1internal/equipotest/finalfix_test.go+225 −0internal/equipotest/pages_test.go+1 −1internal/equipotest/roster_test.go+19 −4
diff --git a/cmd/equipo/main.go b/cmd/equipo/main.go| index 6fb950f4..f1cef656 100644 |
| --- a/cmd/equipo/main.go |
| +++ b/cmd/equipo/main.go |
| @@ -41,7 +41,9 @@ func run(logger *slog.Logger, started time.Time) error { |
| return err |
| } |
| equipo.Configure(&opts, mux, started) |
| - defer opts.Background.Stop() |
| + if opts.Background != nil { |
| + defer opts.Background.Stop() |
| + } |
| opts.DBPath = "" |
| return rastrillo.Serve(opts) |
| } |
diff --git a/internal/equipo/app.go b/internal/equipo/app.go| index 39c4373e..eb398b40 100644 |
| --- a/internal/equipo/app.go |
| +++ b/internal/equipo/app.go |
| @@ -148,9 +148,11 @@ func Configure(opts *rastrillo.Options, mux *http.ServeMux, started time.Time) { |
| // The root handler owns the auth instance. Start work only when serving |
| // is configured, so Router/App construction alone starts no goroutines. |
| handler, _ := mux.Handler(&http.Request{URL: &url.URL{Path: "/"}}) |
| - if a, ok := handler.(*application); ok { |
| - opts.Background = a.startBackground() |
| + a, ok := handler.(*application) |
| + if !ok || a == nil { |
| + panic(copyInvalidRoot) |
| } |
| + opts.Background = a.startBackground() |
| opts.ErrorPage = ErrorPage |
| var rec perf.Recorder |
| opts.Wrap = perf.Middleware(&rec, perf.Options{Started: started, Logger: opts.Logger}) |
diff --git a/internal/equipo/copy.go b/internal/equipo/copy.go| index f3c4844d..f0c82082 100644 |
| --- a/internal/equipo/copy.go |
| +++ b/internal/equipo/copy.go |
| @@ -2,7 +2,16 @@ package equipo |
| // COPY APPROVED BY DELEGATION (Luna pass, 2026-11-01, house rules). |
| // App-owned runtime strings belong here, including boot diagnostics. |
| +// Entries marked NEW still need the delegated copy pass. |
| const ( |
| + copyDecisionOwnerAssigned = "Reassign this person's project decisions before removing them." // NEW: delegated copy pass pending |
| + copyBindingInUse = "Another project uses this repository and app. Choose a different pair." // NEW: delegated copy pass pending |
| + copyLastOwner = "Add another owner before changing or removing the last owner." // NEW: delegated copy pass pending |
| + copyAccountLabelExists = "This account label already exists. Use it or choose another label." // NEW: delegated copy pass pending |
| + copyBootstrapOwners = "Set EQUIPO_OWNERS to valid owner email addresses before the first boot." // NEW: delegated copy pass pending |
| + copyMissingStage = "The sign-in layout is missing. Check the Rastrillo installation." // NEW: delegated copy pass pending |
| + copyInvalidRoot = "The app handler is missing. Configure the Equipo app before serving." // NEW: delegated copy pass pending |
| + |
| copyBrand = "Equipo" |
| copyRenderFailure = "Something went wrong. Try again." |
| copyMissingKey = "EQUIPO_INSTANCE_KEY is required." |
| @@ -26,6 +35,11 @@ const BootLog = "Equipo could not start." |
| // COPY APPROVED BY DELEGATION (Luna pass, 2026-11-01, house rules). |
| var pageCopy = map[string]string{ |
| + "form.decision-owner-assigned": copyDecisionOwnerAssigned, |
| + "form.binding-in-use": copyBindingInUse, |
| + "form.last-owner": copyLastOwner, |
| + "form.account-label-exists": copyAccountLabelExists, |
| + |
| "nav.account": "Account", |
| "brand": copyBrand, |
| "nav.conversation": "Conversation", |
diff --git a/internal/equipo/handlers.go b/internal/equipo/handlers.go| index edf7eb8d..9db2f101 100644 |
| --- a/internal/equipo/handlers.go |
| +++ b/internal/equipo/handlers.go |
| @@ -4,6 +4,7 @@ import ( |
| "crypto/rand" |
| "errors" |
| "net/http" |
| + "path" |
| "strconv" |
| "strings" |
| @@ -55,6 +56,14 @@ func (a *application) page(r *http.Request, key string) (pageData, error) { |
| func (a *application) failure(w http.ResponseWriter, r *http.Request, err error) { |
| status, key := http.StatusServiceUnavailable, "service.unavailable" |
| switch { |
| + case errors.Is(err, ErrDecisionOwnerAssigned): |
| + status, key = 409, "form.decision-owner-assigned" |
| + case errors.Is(err, ErrBindingInUse): |
| + status, key = 409, "form.binding-in-use" |
| + case errors.Is(err, ErrLastOwner): |
| + status, key = 403, "form.last-owner" |
| + case errors.Is(err, ErrAccountLabelExists): |
| + status, key = 409, "form.account-label-exists" |
| case errors.Is(err, ErrInvalid): |
| status, key = 422, "form.invalid" |
| case errors.Is(err, ErrConflict): |
| @@ -98,7 +107,10 @@ func (a *application) failure(w http.ResponseWriter, r *http.Request, err error) |
| } |
| } |
| if r.Method == http.MethodGet && status != 404 { |
| - back = r.URL.Path |
| + back = path.Dir(r.URL.Path) |
| + if back == "/" || back == "/specialists" { |
| + back = "/work" |
| + } |
| } |
| id, _ := auth.From(r) |
| renderStatus(w, status, "form_error", pageData{Nav: Navigation(), Key: navKey, Address: id.Address, Title: key, ErrorKey: key, Back: back, TeamName: copyBrand}) |
diff --git a/internal/equipo/migrations/0006_account_label.sql b/internal/equipo/migrations/0006_account_label.sql| new file mode 100644 |
| index 00000000..8b6a0826 |
| --- /dev/null |
| +++ b/internal/equipo/migrations/0006_account_label.sql |
| @@ -0,0 +1 @@ |
| +CREATE UNIQUE INDEX account_label ON accounts(lower(trim(label))); |
diff --git a/internal/equipo/migrations/schema.sql b/internal/equipo/migrations/schema.sql| index 0a905037..23a4314c 100644 |
| --- a/internal/equipo/migrations/schema.sql |
| +++ b/internal/equipo/migrations/schema.sql |
| @@ -9,3 +9,5 @@ CREATE INDEX idx_decision_owners_address ON decision_owners(address); |
| CREATE TABLE project_requests (actor text, operation text, request_id text, input_hash text, result text, PRIMARY KEY (actor, operation, request_id)); |
| CREATE TABLE budget_records (team_id text, revision integer, config text, PRIMARY KEY (team_id)); |
| CREATE TABLE specialists (key text, model_selection text, provider text, model_family text, model text, standing_instructions text, max_concurrent integer, revision integer, PRIMARY KEY (key)); |
| + |
| +CREATE UNIQUE INDEX account_label ON accounts(lower(trim(label))); |
diff --git a/internal/equipo/models.go b/internal/equipo/models.go| index 2374ee00..2b660dc2 100644 |
| --- a/internal/equipo/models.go |
| +++ b/internal/equipo/models.go |
| @@ -38,7 +38,7 @@ type AuditEvent struct { |
| type Account struct { |
| ID int64 |
| - Label string |
| + Label string `gorm:"uniqueIndex:account_label,expression:lower(trim(label))"` |
| Revision int64 |
| } |
diff --git a/internal/equipo/projects.go b/internal/equipo/projects.go| index 30f5462e..373399ba 100644 |
| --- a/internal/equipo/projects.go |
| +++ b/internal/equipo/projects.go |
| @@ -36,7 +36,7 @@ func (s *Store) SaveAccount(ctx context.Context, actor Actor, account Account) ( |
| if account.ID == 0 { |
| account.Revision = 1 |
| if err := tx.Create(&account).Error; err != nil { |
| - return storeError(err) |
| + return accountWriteError(err) |
| } |
| } else { |
| var old Account |
| @@ -49,7 +49,7 @@ func (s *Store) SaveAccount(ctx context.Context, actor Actor, account Account) ( |
| account.Revision++ |
| result := tx.Model(&Account{}).Where("id = ? AND revision = ?", account.ID, old.Revision).Select("Label", "Revision").Updates(&account) |
| if result.Error != nil { |
| - return storeError(result.Error) |
| + return accountWriteError(result.Error) |
| } |
| if result.RowsAffected != 1 { |
| return ErrConflict |
| @@ -63,6 +63,13 @@ func (s *Store) SaveAccount(ctx context.Context, actor Actor, account Account) ( |
| return account, nil |
| } |
| +func accountWriteError(err error) error { |
| + if errors.Is(err, gorm.ErrDuplicatedKey) { |
| + return ErrAccountLabelExists |
| + } |
| + return storeError(err) |
| +} |
| + |
| func bindingSegment(value string) bool { |
| if value == "" || value == "." || value == ".." { |
| return false |
| @@ -237,7 +244,7 @@ func (s *Store) SaveProject(ctx context.Context, actor Actor, project Project, o |
| return storeError(err) |
| } |
| if duplicates != 0 { |
| - return ErrConflict |
| + return ErrBindingInUse |
| } |
| project.Revision++ |
| if project.ID == 0 { |
diff --git a/internal/equipo/render.go b/internal/equipo/render.go| index 355e82f2..5057a2e9 100644 |
| --- a/internal/equipo/render.go |
| +++ b/internal/equipo/render.go |
| @@ -35,7 +35,10 @@ func init() { |
| "roleKey": func(k Role) string { return "role." + string(k) }, |
| }).ParseFS(ui.Templates(), "*.html")) |
| if name == "signin_page" { |
| - stage, _ := ui.Layout("stage") |
| + stage, ok := ui.Layout("stage") |
| + if !ok { |
| + panic(copyMissingStage) |
| + } |
| page = template.Must(page.Parse(string(stage))) |
| } else { |
| page = template.Must(page.ParseFS(appFS, "templates/layout.html")) |
diff --git a/internal/equipo/roster.go b/internal/equipo/roster.go| index 7db530aa..b0a3af25 100644 |
| --- a/internal/equipo/roster.go |
| +++ b/internal/equipo/roster.go |
| @@ -39,12 +39,12 @@ func (s *Store) Bootstrap(ctx context.Context, owners []string) error { |
| for _, address := range owners { |
| address = normalizeAddress(address) |
| if !validAddress(address) { |
| - return ErrInvalid |
| + return ErrBootstrapOwners |
| } |
| unique[address] = true |
| } |
| if len(unique) == 0 { |
| - return ErrInvalid |
| + return ErrBootstrapOwners |
| } |
| team = Team{ID: rand.Text(), Name: copyBrand, RosterEpoch: 1} |
| if err := tx.Create(&team).Error; err != nil { |
| @@ -116,7 +116,7 @@ func (s *Store) SetMember(ctx context.Context, actor Actor, address string, role |
| return storeError(err) |
| } |
| if owners <= 1 { |
| - return ErrForbidden |
| + return ErrLastOwner |
| } |
| } |
| if !active { |
| @@ -125,7 +125,7 @@ func (s *Store) SetMember(ctx context.Context, actor Actor, address string, role |
| return storeError(err) |
| } |
| if assigned != 0 { |
| - return ErrConflict |
| + return ErrDecisionOwnerAssigned |
| } |
| } |
| member := Member{Address: address, Role: role, Active: active, Revision: old.Revision + 1, SessionEpoch: old.SessionEpoch} |
diff --git a/internal/equipo/store.go b/internal/equipo/store.go| index d6d63485..104174d0 100644 |
| --- a/internal/equipo/store.go |
| +++ b/internal/equipo/store.go |
| @@ -22,9 +22,23 @@ var ( |
| //lint:ignore ST1005 User-facing errors preserve the reviewed sentences in copy.go. |
| ErrInvalid = errors.New(copyInvalid) |
| //lint:ignore ST1005 User-facing errors preserve the reviewed sentences in copy.go. |
| - ErrUnavailable = errors.New(copyUnavailable) |
| + ErrUnavailable = errors.New(copyUnavailable) |
| + ErrDecisionOwnerAssigned = &refusal{copyDecisionOwnerAssigned, ErrConflict} |
| + ErrBindingInUse = &refusal{copyBindingInUse, ErrConflict} |
| + ErrLastOwner = &refusal{copyLastOwner, ErrForbidden} |
| + ErrAccountLabelExists = &refusal{copyAccountLabelExists, ErrConflict} |
| + ErrBootstrapOwners = &refusal{copyBootstrapOwners, ErrInvalid} |
| ) |
| +// A refusal keeps its specific reason while preserving the error category. |
| +type refusal struct { |
| + message string |
| + kind error |
| +} |
| + |
| +func (e *refusal) Error() string { return e.message } |
| +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 } |
diff --git a/internal/equipo/templates/projects.html b/internal/equipo/templates/projects.html| index 78b17f1a..cc98dee8 100644 |
| --- a/internal/equipo/templates/projects.html |
| +++ b/internal/equipo/templates/projects.html |
| @@ -12,6 +12,6 @@ |
| </article>{{else}}<p>{{copy "projects.empty"}}</p>{{end}} |
| </div></section> |
| {{else}}<p>{{copy "projects.empty"}}</p>{{end}} |
| -<section equipo-note><h2>{{copy "budget.title"}}</h2>{{template "budget-summary" .}}<h3>{{copy "budget.usage"}}</h3><p data-usage="0">{{copy "budget.zero"}}</p></section> |
| +<section equipo-note><h2>{{copy "budget.title"}}</h2>{{template "budget-summary" .}}<h3>{{copy "budget.usage"}}</h3><p data-usage="unavailable">{{copy "budget.zero"}}</p></section> |
| {{if .Owner}}<section equipo-card><h2>{{copy "projects.add"}}</h2>{{template "project-fields" .}}</section>{{end}} |
| {{end}} |
diff --git a/internal/equipo/templates/settings.html b/internal/equipo/templates/settings.html| index 76f324bd..3982fbde 100644 |
| --- a/internal/equipo/templates/settings.html |
| +++ b/internal/equipo/templates/settings.html |
| @@ -11,6 +11,6 @@ |
| {{range .BudgetForms}}<fieldset><legend>{{.Name}}</legend>{{range .Fields}}<label>{{copy .CopyKey}}<input rst-input name="{{.Name}}" type="number" min="1" step="1" value="{{.Value}}"></label>{{end}}</fieldset>{{end}} |
| <button rst-btn="primary" type="submit">{{copy "form.save"}}</button></form> |
| {{else}}{{template "budget-summary" .}}{{end}} |
| -<h3>{{copy "budget.usage"}}</h3><p data-usage="0">{{copy "budget.zero"}}</p> |
| +<h3>{{copy "budget.usage"}}</h3><p data-usage="unavailable">{{copy "budget.zero"}}</p> |
| </section> |
| {{end}} |
diff --git a/internal/equipotest/finalfix_test.go b/internal/equipotest/finalfix_test.go| new file mode 100644 |
| index 00000000..2be496b0 |
| --- /dev/null |
| +++ b/internal/equipotest/finalfix_test.go |
| @@ -0,0 +1,225 @@ |
| +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", "/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, `<a href="/projects">Back to the form</a>`) { |
| + 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) |
| + } |
| + } |
| +} |
diff --git a/internal/equipotest/pages_test.go b/internal/equipotest/pages_test.go| index 6caa839b..67bdcd25 100644 |
| --- a/internal/equipotest/pages_test.go |
| +++ b/internal/equipotest/pages_test.go |
| @@ -328,7 +328,7 @@ func TestSettingsForms(t *testing.T) { |
| t.Fatal("project limits were not cleared") |
| } |
| body = pageBody(t, c, f.server.URL, "/projects") |
| - if !strings.Contains(body, `data-limit-set="false"`) || !strings.Contains(body, "1000") || !strings.Contains(body, `data-usage="0"`) { |
| + if !strings.Contains(body, `data-limit-set="false"`) || !strings.Contains(body, "1000") || !strings.Contains(body, `data-usage="unavailable"`) { |
| t.Fatal("limits and usage not distinct") |
| } |
| } |
diff --git a/internal/equipotest/roster_test.go b/internal/equipotest/roster_test.go| index b63de645..bc0d7e70 100644 |
| --- a/internal/equipotest/roster_test.go |
| +++ b/internal/equipotest/roster_test.go |
| @@ -11,6 +11,7 @@ import ( |
| "amadan.net/oficina/equipo/internal/equipo" |
| "amadan.net/rastrillo/rastrillo/db" |
| "amadan.net/rastrillo/rastrillo/migrate" |
| + "amadan.net/rastrillo/rastrillo/sessions" |
| ) |
| const ownerAddress = "owner@example.com" |
| @@ -163,10 +164,22 @@ func TestRosterChangesAffectExistingSession(t *testing.T) { |
| if scalar(t, f.db, "SELECT count(*) FROM sessions WHERE subject = ?", "second@example.com") != 2 { |
| t.Fatal("missing sessions") |
| } |
| - // Keep a real session row to model a mint that races the deletion. |
| - if _, err := f.db.Writer().Exec("CREATE TEMP TABLE raced_session AS SELECT * FROM sessions WHERE subject = ? LIMIT 1", "second@example.com"); err != nil { |
| + // Keep the row belonging to c's cookie, not an arbitrary session. |
| + var tokenHash string |
| + for _, cookie := range cookies { |
| + if cookie.Name == "rastrillo_session" { |
| + tokenHash = sessions.HashToken(cookie.Value) |
| + } |
| + } |
| + if tokenHash == "" { |
| + t.Fatal("missing session cookie") |
| + } |
| + if _, err := f.db.Writer().Exec("CREATE TEMP TABLE raced_session AS SELECT * FROM sessions WHERE token_hash = ?", tokenHash); err != nil { |
| t.Fatal(err) |
| } |
| + if scalar(t, f.db, "SELECT count(*) FROM raced_session") != 1 { |
| + t.Fatal("saved session does not match cookie") |
| + } |
| setMember(t, f.store, "second@example.com", equipo.RoleMember, false) |
| if scalar(t, f.db, "SELECT count(*) FROM sessions WHERE subject = ?", "second@example.com") != 0 { |
| t.Fatal("removal kept sessions") |
| @@ -177,7 +190,8 @@ func TestRosterChangesAffectExistingSession(t *testing.T) { |
| if _, err := f.db.Writer().Exec("INSERT INTO sessions SELECT * FROM raced_session"); err != nil { |
| t.Fatal(err) |
| } |
| - assertDenied(t, c, f.server.URL+"/test-private") |
| + c.Jar.SetCookies(mustURL(t, f.server.URL), cookies) |
| + assertStatus(t, c, f.server.URL+"/test-private", http.StatusForbidden) |
| assertDenied(t, c2, f.server.URL+"/test-private") |
| if _, err := f.db.Writer().Exec("DELETE FROM sessions WHERE subject = ?", "second@example.com"); err != nil { |
| t.Fatal(err) |
| @@ -188,7 +202,8 @@ func TestRosterChangesAffectExistingSession(t *testing.T) { |
| if _, err := f.db.Writer().Exec("INSERT INTO sessions SELECT * FROM raced_session"); err != nil { |
| t.Fatal(err) |
| } |
| - assertDenied(t, c, f.server.URL+"/test-private") |
| + c.Jar.SetCookies(mustURL(t, f.server.URL), cookies) |
| + assertStatus(t, c, f.server.URL+"/test-private", http.StatusForbidden) |
| assertDenied(t, c2, f.server.URL+"/test-private") |
| fresh := signinClient(t, f.server.URL) |
| signinEmail(t, fresh, f.server.URL, testOrigin, f.mail, "second@example.com") |