package api import ( "bytes" "context" "encoding/json" "net/http" "net/http/httptest" "sync" "testing" "github.com/Fabled-Sword/minstrel/internal/auth" ) // resetUsers wipes the entire users table (including any non-prefixed admin // row). Used only by tests that need the empty-users bootstrap path; normal // tests call seedUser which uses the TestUserPrefix prefix and is cleaned up // by dbtest.ResetDB inside testHandlers. func resetUsers(t *testing.T, h *handlers) { t.Helper() if _, err := h.pool.Exec(context.Background(), "DELETE FROM users"); err != nil { t.Fatalf("resetUsers: %v", err) } } // resetInvites wipes the user_invites table. Called by tests that seed their // own invites so subsequent runs start clean. func resetInvites(t *testing.T, h *handlers) { t.Helper() if _, err := h.pool.Exec(context.Background(), "DELETE FROM user_invites"); err != nil { t.Fatalf("resetInvites: %v", err) } } func TestRegister_FirstUserBecomesAdmin(t *testing.T) { h, _ := testHandlers(t) resetUsers(t, h) body := `{"username":"firstuser","password":"abcd1234"}` req := httptest.NewRequest(http.MethodPost, "/api/auth/register", bytes.NewReader([]byte(body))) rec := httptest.NewRecorder() h.handleRegister(rec, req) if rec.Code != http.StatusOK { t.Fatalf("status = %d, want 200; body=%s", rec.Code, rec.Body.String()) } // Verify is_admin = true on the inserted row. var isAdmin bool if err := h.pool.QueryRow(context.Background(), "SELECT is_admin FROM users WHERE username = 'firstuser'").Scan(&isAdmin); err != nil { t.Fatalf("verify: %v", err) } if !isAdmin { t.Errorf("is_admin = false; first registered user must be admin") } // Cookie set? gotCookie := false for _, c := range rec.Result().Cookies() { if c.Name == auth.SessionCookieName { gotCookie = true } } if !gotCookie { t.Errorf("session cookie not set") } } func TestRegister_DuplicateUsername_409(t *testing.T) { h, pool := testHandlers(t) resetUsers(t, h) resetInvites(t, h) // First register succeeds (empty-users state → first-admin path). body := `{"username":"taken","password":"abcd1234"}` req := httptest.NewRequest(http.MethodPost, "/api/auth/register", bytes.NewReader([]byte(body))) h.handleRegister(httptest.NewRecorder(), req) // A valid invite gets the second attempt past the invite check, to the // INSERT and its unique violation. if _, err := pool.Exec(context.Background(), `INSERT INTO user_invites (token, invited_by, expires_at) SELECT 'dup-invite', id, now() + interval '24 hours' FROM users WHERE username = 'taken'`); err != nil { t.Fatalf("seed invite: %v", err) } dup := `{"username":"taken","password":"abcd1234","invite_token":"dup-invite"}` req2 := httptest.NewRequest(http.MethodPost, "/api/auth/register", bytes.NewReader([]byte(dup))) rec2 := httptest.NewRecorder() h.handleRegister(rec2, req2) if rec2.Code != http.StatusConflict { t.Errorf("status = %d, want 409 (username_taken)", rec2.Code) } } func TestRegister_PasswordTooShort_400(t *testing.T) { h, _ := testHandlers(t) body := `{"username":"shortpw","password":"abc"}` req := httptest.NewRequest(http.MethodPost, "/api/auth/register", bytes.NewReader([]byte(body))) rec := httptest.NewRecorder() h.handleRegister(rec, req) if rec.Code != http.StatusBadRequest { t.Errorf("status = %d, want 400", rec.Code) } } func TestRegister_UsernameInvalid_400(t *testing.T) { h, _ := testHandlers(t) body := `{"username":"has spaces","password":"abcd1234"}` req := httptest.NewRequest(http.MethodPost, "/api/auth/register", bytes.NewReader([]byte(body))) rec := httptest.NewRecorder() h.handleRegister(rec, req) if rec.Code != http.StatusBadRequest { t.Errorf("status = %d, want 400", rec.Code) } } func TestRegister_FirstAdminRace(t *testing.T) { // Concurrent registrations from empty-users state. Both // usernames are different, so users.username uniqueness doesn't // arbitrate. Both will see "no users yet" and both insert as // admin. Test asserts the at-least-one-admin invariant. h, _ := testHandlers(t) resetUsers(t, h) const N = 5 var wg sync.WaitGroup for i := 0; i < N; i++ { wg.Add(1) go func(idx int) { defer wg.Done() body := json.RawMessage(`{"username":"raceuser` + string(rune('A'+idx)) + `","password":"abcd1234"}`) req := httptest.NewRequest(http.MethodPost, "/api/auth/register", bytes.NewReader(body)) rec := httptest.NewRecorder() h.handleRegister(rec, req) }(i) } wg.Wait() var adminCount int if err := h.pool.QueryRow(context.Background(), `SELECT count(*) FROM users WHERE is_admin = true`).Scan(&adminCount); err != nil { t.Fatalf("count: %v", err) } if adminCount < 1 { t.Errorf("admin count = 0; expected at least 1 (race-safety invariant violated)") } // adminCount can be > 1 — that's fine. The invariant is "at least one," // not "exactly one" (which would require serializable isolation). t.Logf("admin count after race = %d (>=1 is the invariant)", adminCount) } // With the gate on (as Mount sets it), the first account needs the setup // token from the log; a missing or wrong one is refused and creates nothing. func TestRegister_FirstUserNeedsSetupToken(t *testing.T) { h, _ := testHandlers(t) resetUsers(t, h) token, err := auth.NewSetupToken() if err != nil { t.Fatalf("mint: %v", err) } h.setupToken = token h.requireSetupToken = true register := func(body string) int { req := httptest.NewRequest(http.MethodPost, "/api/auth/register", bytes.NewReader([]byte(body))) rec := httptest.NewRecorder() h.handleRegister(rec, req) return rec.Code } if code := register(`{"username":"squatter","password":"abcd1234"}`); code != http.StatusForbidden { t.Errorf("no token: status = %d, want 403", code) } if code := register(`{"username":"squatter","password":"abcd1234","setup_token":"wrong"}`); code != http.StatusForbidden { t.Errorf("wrong token: status = %d, want 403", code) } var n int if err := h.pool.QueryRow(context.Background(), `SELECT count(*) FROM users`).Scan(&n); err != nil { t.Fatalf("count: %v", err) } if n != 0 { t.Fatalf("a refused registration created %d account(s)", n) } if code := register(`{"username":"operator","password":"abcd1234","setup_token":"` + token.Value() + `"}`); code != http.StatusOK { t.Fatalf("right token: status = %d, want 200", code) } // Once an account exists the setup token opens nothing: the second // account needs an invite, and there is no way to register without one. if code := register(`{"username":"second","password":"abcd1234","setup_token":"` + token.Value() + `"}`); code != http.StatusBadRequest { t.Errorf("second user with the setup token and no invite: status = %d, want 400", code) } } func TestSetupToken_MatchesOnlyItself(t *testing.T) { tok, err := auth.NewSetupToken() if err != nil { t.Fatalf("mint: %v", err) } if !tok.Matches(tok.Value()) { t.Error("token does not match itself") } if tok.Matches("") || tok.Matches(tok.Value()+"x") { t.Error("token matched something else") } var none *auth.SetupToken if none.Matches("") || none.Matches("anything") { t.Error("a nil token must fail closed") } } // Sign-ups racing on one invite make exactly one account: the others are // told the invite is used, and nothing of theirs is left behind. func TestRegister_OneInviteMakesOneAccountUnderARace(t *testing.T) { h, pool := testHandlers(t) resetInvites(t, h) admin := seedUser(t, pool, "raceadmin", "pw", true) token := "test-invite-race" if _, err := pool.Exec(context.Background(), `INSERT INTO user_invites (token, invited_by, expires_at) VALUES ($1, $2, now() + interval '24 hours')`, token, admin.ID, ); err != nil { t.Fatalf("seed invite: %v", err) } const N = 5 codes := make([]int, N) var wg sync.WaitGroup for i := 0; i < N; i++ { wg.Add(1) go func(idx int) { defer wg.Done() body := `{"username":"inviterace` + string(rune('A'+idx)) + `","password":"abcd1234","invite_token":"` + token + `"}` req := httptest.NewRequest(http.MethodPost, "/api/auth/register", bytes.NewReader([]byte(body))) rec := httptest.NewRecorder() h.handleRegister(rec, req) codes[idx] = rec.Code }(i) } wg.Wait() ok := 0 for _, c := range codes { switch c { case http.StatusOK: ok++ case http.StatusBadRequest: default: t.Errorf("unexpected status %d", c) } } if ok != 1 { t.Fatalf("%d sign-ups succeeded on one invite, want exactly 1 (codes %v)", ok, codes) } var made int if err := pool.QueryRow(context.Background(), `SELECT count(*) FROM users WHERE username LIKE 'inviterace%'`).Scan(&made); err != nil { t.Fatalf("count: %v", err) } if made != 1 { t.Fatalf("%d accounts exist after the race, want 1", made) } } // Once an account exists, an invite is the only way in: a sign-up without // one, or with a token that was never issued, is refused and creates no // account. A valid invite makes an ordinary (non-admin) account and is // marked redeemed. func TestRegister_AfterTheFirstAccountAnInviteIsTheOnlyWayIn(t *testing.T) { h, pool := testHandlers(t) resetInvites(t, h) admin := seedUser(t, pool, "admin1", "pw", true) const token = "test-invite-abc123" if _, err := pool.Exec(context.Background(), `INSERT INTO user_invites (token, invited_by, expires_at) VALUES ($1, $2, now() + interval '24 hours')`, token, admin.ID); err != nil { t.Fatalf("seed invite: %v", err) } for _, tc := range []struct { username, inviteToken string status int }{ {"noinvite", "", http.StatusBadRequest}, {"badinvite", "nonexistent-token", http.StatusBadRequest}, {"invitee", token, http.StatusOK}, } { body := `{"username":"` + tc.username + `","password":"abcd1234","invite_token":"` + tc.inviteToken + `"}` rec := httptest.NewRecorder() h.handleRegister(rec, httptest.NewRequest(http.MethodPost, "/api/auth/register", bytes.NewReader([]byte(body)))) if rec.Code != tc.status { t.Errorf("%s: status %d, want %d; body=%s", tc.username, rec.Code, tc.status, rec.Body.String()) } var accounts, admins int if err := pool.QueryRow(context.Background(), `SELECT count(*), count(*) FILTER (WHERE is_admin) FROM users WHERE username = $1`, tc.username).Scan(&accounts, &admins); err != nil { t.Fatalf("count accounts: %v", err) } wantAccounts := 0 if tc.status == http.StatusOK { wantAccounts = 1 } if accounts != wantAccounts || admins != 0 { t.Errorf("%s: %d accounts (%d admin), want %d (0 admin)", tc.username, accounts, admins, wantAccounts) } } var redeemed bool if err := pool.QueryRow(context.Background(), `SELECT redeemed_at IS NOT NULL FROM user_invites WHERE token = $1`, token).Scan(&redeemed); err != nil { t.Fatalf("read invite: %v", err) } if !redeemed { t.Errorf("the invite was not marked redeemed") } }