Files
coder/coderd/firstusersetup.go
T
Bobby Ho cf68914831 fix(coderd): let only one request create the first user (#32417)
Prevent multiple Owner accounts from being created during concurrent first-user setup requests.

Refs https://linear.app/codercom/issue/CORE-853

Use a transaction-scoped PostgreSQL advisory lock shared by password setup and GitHub/OIDC first sign-ins. Recheck the user count under the lock to ensure only one account receives the Owner role, while preserving existing responses for subsequent requests.

- Add a stable, backport-safe lock ID and shared first-user setup helper.
- Apply locking only when no users exist, leaving normal sign-ins unaffected.
- Use `READ COMMITTED` isolation to ensure accurate counts regardless of database defaults.
- Keep validation and trial licence requests outside the lock.
- Preserve existing API responses, status codes, and telemetry behavior.

**Testing**
- Add concurrent password, OAuth, and mixed-path tests verifying exactly one Owner.
- Cover lock contention, cancellation, isolation levels, telemetry, and lock bypass.
- Verify tests fail when locking is removed.
- Pass targeted race tests, 124 related tests, lint, and `intxcheck`.

**Known limitation:** A burst of concurrent OAuth sign-ins on an empty deployment could exhaust the database connection pool while waiting for the lock. This remains unverified and is outside the scope of this fix.

**Note:** Stacked on #32324; will be rebased onto `main` after it merges.
2026-11-20 09:12:05 -07:00

39 lines
1.4 KiB
Go

package coderd
import (
"context"
"database/sql"
"golang.org/x/xerrors"
"github.com/coder/coder/v2/coderd/database"
"github.com/coder/coder/v2/coderd/database/dbauthz"
)
var errFirstUserExists = xerrors.New("the initial user has already been created")
// firstUserSetupTxOptions names the isolation level that
// lockFirstUserSetup needs. At read committed the count sees a user
// that another request committed while this one waited for the lock.
// At a higher level the count comes from a snapshot taken before the
// wait, and a Postgres server can make a higher level its default.
// Built per call because InTx writes to the options it receives.
func firstUserSetupTxOptions() *database.TxOptions {
return &database.TxOptions{Isolation: sql.LevelReadCommitted}
}
// lockFirstUserSetup takes the first user setup lock and returns the
// user count while the lock is held. The lock is released when tx ends.
// tx must be started with firstUserSetupTxOptions.
func lockFirstUserSetup(ctx context.Context, tx database.Store) (int64, error) {
if err := tx.AcquireLock(ctx, database.LockIDFirstUserSetup); err != nil {
return 0, xerrors.Errorf("acquire first user setup lock: %w", err)
}
//nolint:gocritic // Getting user count is a system function.
userCount, err := tx.GetUserCount(dbauthz.AsSystemRestricted(ctx), false)
if err != nil {
return 0, xerrors.Errorf("get user count: %w", err)
}
return userCount, nil
}