From 1c28e17dfcc56734f0b51b3d8e2a9b13ed4d38d6 Mon Sep 17 00:00:00 2001 From: Bryan Van Deusen Date: Thu, 26 Nov 2026 23:45:07 -0500 Subject: [PATCH] fix(auth): one invite makes one account, and a burst of sign-ups can't outrun the limit (#8106) Registration inserted the user and only then claimed the invite. When the claim lost a race it kept the account anyway, so parallel sign-ups on one invite link each made an account. The insert and the claim now run in one transaction: RedeemInvite's row lock makes the second sign-up wait for the first, find the invite used, and roll its account back with invite_invalid. The register and forgot-password limits checked and counted in two steps, so a parallel burst all read the count before any attempt was added. They now call AttemptLimiter.Allow, which does both under the lock. Co-Authored-By: Claude Opus 5.5 --- internal/api/auth_forgot.go | 12 ++--- internal/api/auth_register.go | 76 ++++++++++++++++++------------ internal/api/auth_register_test.go | 57 ++++++++++++++++++++++ internal/auth/ratelimit.go | 29 +++++++++++- internal/auth/ratelimit_test.go | 33 +++++++++++++ 5 files changed, 170 insertions(+), 37 deletions(-) diff --git a/internal/api/auth_forgot.go b/internal/api/auth_forgot.go index 57baf6b7..1fdcfa10 100644 --- a/internal/api/auth_forgot.go +++ b/internal/api/auth_forgot.go @@ -52,14 +52,14 @@ func (h *handlers) handleForgotPassword(w http.ResponseWriter, r *http.Request) // inbox). Applied whether or not the email matches, so a 429 says // nothing about which addresses are registered. addr := auth.ClientIP(r, h.netSettings.Hops()) - blockedAddr, waitAddr := h.forgotAddressLimit.Blocked(addr) - blockedEmail, waitEmail := h.forgotEmailLimit.Blocked(email) - if blockedAddr || blockedEmail { - writeRateLimited(w, max(waitAddr, waitEmail)) + if ok, wait := h.forgotAddressLimit.Allow(addr); !ok { + writeRateLimited(w, wait) + return + } + if ok, wait := h.forgotEmailLimit.Allow(email); !ok { + writeRateLimited(w, wait) return } - h.forgotAddressLimit.Record(addr) - h.forgotEmailLimit.Record(email) q := dbq.New(h.pool) var matched bool diff --git a/internal/api/auth_register.go b/internal/api/auth_register.go index 4c1e437d..5ea069bb 100644 --- a/internal/api/auth_register.go +++ b/internal/api/auth_register.go @@ -45,8 +45,9 @@ type registerReq struct { // 2. If users table is empty: check the setup token, then insert via // CreateUserFirstAdminRace (sets is_admin from a SELECT NOT EXISTS // subquery). -// 3. Otherwise check the invite, then redeem it atomically via -// RedeemInvite once the user exists. +// 3. Otherwise check the invite. The user insert and the invite claim +// (RedeemInvite) then run in one transaction, so of several sign-ups +// racing on one invite exactly one makes an account. // 4. Hash password, mint session token, insert session row, set // cookie, return user + token. // 5. Audit ActionRegister and ActionInviteRedeem. @@ -61,11 +62,10 @@ func (h *handlers) handleRegister(w http.ResponseWriter, r *http.Request) { // Every attempt counts, not only failures, so invite tokens can't be // guessed at speed. addr := auth.ClientIP(r, h.netSettings.Hops()) - if blocked, wait := h.registerLimit.Blocked(addr); blocked { + if ok, wait := h.registerLimit.Allow(addr); !ok { writeRateLimited(w, wait) return } - h.registerLimit.Record(addr) var req registerReq if err := json.NewDecoder(r.Body).Decode(&req); err != nil { @@ -145,41 +145,25 @@ func (h *handlers) handleRegister(w http.ResponseWriter, r *http.Request) { return } - // Insert user (race-safe-first-admin variant). - user, err := q.CreateUserFirstAdminRace(r.Context(), dbq.CreateUserFirstAdminRaceParams{ + user, err := h.createRegisteredUser(r.Context(), dbq.CreateUserFirstAdminRaceParams{ Username: req.Username, PasswordHash: string(hash), ApiTokenHash: auth.HashAPIToken(apiToken), DisplayName: req.DisplayName, - }) - if err != nil { - if db.IsUniqueViolation(err) { - writeErr(w, apierror.Conflict("username_taken", "username is already taken")) - return - } + }, usedInviteToken) + switch { + case errors.Is(err, errInviteTaken): + writeErr(w, apierror.BadRequest("invite_invalid", "invite token is expired or already redeemed")) + return + case db.IsUniqueViolation(err): + writeErr(w, apierror.Conflict("username_taken", "username is already taken")) + return + case err != nil: h.logger.Error("register: create user failed", "err", err) writeErr(w, apierror.Internal(err)) return } - // Atomic invite redeem (if applicable). Now we have user.ID for - // redeemed_by. - if usedInviteToken != "" { - rows, rerr := q.RedeemInvite(r.Context(), dbq.RedeemInviteParams{ - Token: usedInviteToken, - RedeemedBy: user.ID, - }) - if rerr != nil || rows != 1 { - // Race: another caller redeemed between our pre-check and now. - // User was already inserted — the redeem failed but the user - // row exists. Best to leave the user in place (operator can - // promote them manually) but surface a clear log entry. - h.logger.Error("register: invite redeem failed; user inserted but invite not consumed", - "user_id", uuidToString(user.ID), "rows", rows, "err", rerr) - // Don't fail the response — the user IS registered. - } - } - // Mint session token + cookie (same shape as handleLogin). sessionToken, err := auth.MintSessionToken() if err != nil { @@ -240,6 +224,38 @@ func (h *handlers) handleRegister(w http.ResponseWriter, r *http.Request) { }) } +// errInviteTaken means the invite was redeemed or expired between the +// handler's check and its claim: another sign-up on the same invite won. +var errInviteTaken = errors.New("api: invite already redeemed or expired") + +// createRegisteredUser inserts the user and, when inviteToken is set, claims +// the invite for them, in one transaction. RedeemInvite's UPDATE locks the +// invite row, so a second sign-up on the same invite waits for the first to +// commit, then finds it redeemed and rolls its own account back. An invite +// therefore makes one account however many requests carry it. +func (h *handlers) createRegisteredUser(ctx context.Context, params dbq.CreateUserFirstAdminRaceParams, inviteToken string) (dbq.User, error) { + tx, err := h.pool.Begin(ctx) + if err != nil { + return dbq.User{}, err + } + defer func() { _ = tx.Rollback(ctx) }() + tq := dbq.New(tx) + user, err := tq.CreateUserFirstAdminRace(ctx, params) + if err != nil { + return dbq.User{}, err + } + if inviteToken != "" { + rows, err := tq.RedeemInvite(ctx, dbq.RedeemInviteParams{Token: inviteToken, RedeemedBy: user.ID}) + if err != nil { + return dbq.User{}, err + } + if rows != 1 { + return dbq.User{}, errInviteTaken + } + } + return user, tx.Commit(ctx) +} + // handleSetupStatus implements GET /api/auth/setup-status. It tells the // register screen whether to ask for the setup token, i.e. whether no // account exists yet. Public, since it is needed before anyone can sign in; diff --git a/internal/api/auth_register_test.go b/internal/api/auth_register_test.go index 608a7b5c..c6aeb80f 100644 --- a/internal/api/auth_register_test.go +++ b/internal/api/auth_register_test.go @@ -303,3 +303,60 @@ func TestSetupToken_MatchesOnlyItself(t *testing.T) { 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) { + if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" { + t.Skip("MINSTREL_TEST_DATABASE_URL not set") + } + 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) + } +} diff --git a/internal/auth/ratelimit.go b/internal/auth/ratelimit.go index 849aad73..523a807f 100644 --- a/internal/auth/ratelimit.go +++ b/internal/auth/ratelimit.go @@ -50,7 +50,9 @@ func NewAttemptLimiter(max int, window time.Duration) *AttemptLimiter { // Blocked reports whether key has used its attempts for the current window, // and if so how long until the window resets. It records nothing, so a check -// can run before the expensive work and the outcome be recorded after. +// can run before the expensive work and a failure be recorded after, which is +// the shape for a limit that counts only failures. Where every attempt +// counts, Allow checks and counts in one step. func (l *AttemptLimiter) Blocked(key string) (bool, time.Duration) { if l == nil || key == "" { return false, 0 @@ -72,6 +74,31 @@ func (l *AttemptLimiter) Blocked(key string) (bool, time.Duration) { return true, b.start.Add(l.window).Sub(now) } +// Allow counts one attempt against key and reports whether it was within the +// limit, and if not how long until the window resets. The check and the count +// happen together under the lock, so a burst of parallel requests cannot all +// read the count before any of them adds to it. A refused attempt is not +// counted. +func (l *AttemptLimiter) Allow(key string) (bool, time.Duration) { + if l == nil || key == "" { + return true, 0 + } + l.mu.Lock() + defer l.mu.Unlock() + now := l.now() + b, ok := l.buckets[key] + if !ok || now.Sub(b.start) >= l.window { + l.buckets[key] = &attemptBucket{count: 1, start: now} + l.maybeSweep(now) + return true, 0 + } + if b.count >= l.max { + return false, b.start.Add(l.window).Sub(now) + } + b.count++ + return true, 0 +} + // Record counts one attempt against key. func (l *AttemptLimiter) Record(key string) { if l == nil || key == "" { diff --git a/internal/auth/ratelimit_test.go b/internal/auth/ratelimit_test.go index 6560fb74..6428c35b 100644 --- a/internal/auth/ratelimit_test.go +++ b/internal/auth/ratelimit_test.go @@ -1,6 +1,8 @@ package auth import ( + "sync" + "sync/atomic" "testing" "time" ) @@ -112,3 +114,34 @@ func TestLoginGuard_AddressLimitSpansAccounts(t *testing.T) { t.Fatal("a success must not clear the address count") } } + +// A parallel burst on one key gets exactly max attempts through: the check +// and the count are one step, so no request reads the count before another +// has added to it. +func TestAttemptLimiter_AllowAdmitsExactlyMaxFromAParallelBurst(t *testing.T) { + l, c := newTestLimiter(10, time.Hour) + var allowed atomic.Int32 + var wg sync.WaitGroup + for i := 0; i < 100; i++ { + wg.Add(1) + go func() { + defer wg.Done() + if ok, _ := l.Allow("k"); ok { + allowed.Add(1) + } + }() + } + wg.Wait() + if n := allowed.Load(); n != 10 { + t.Fatalf("allowed %d of a 100-request burst, want exactly 10", n) + } + c.t = c.t.Add(20 * time.Minute) + ok, wait := l.Allow("k") + if ok || wait != 40*time.Minute { + t.Fatalf("Allow past the limit = %v, wait %v; want refused with the 40m left", ok, wait) + } + c.t = c.t.Add(40 * time.Minute) + if ok, _ := l.Allow("k"); !ok { + t.Fatal("refused once the window had passed") + } +}