Skip to content

fix(coderd): let only one request create the first user - #32417

Merged
BobbyHo merged 26 commits into
mainfrom
bobby/core-853-securityhigh-prevent-concurrent-first-user
Nov 20, 2026
Merged

BobbyHo merged 26 commits into
mainfrom
bobby/core-853-securityhigh-prevent-concurrent-first-user

Conversation

@BobbyHo

@BobbyHo BobbyHo commented Nov 19, 2026 •

Copy link
Copy Markdown
Collaborator

TL;DR

The first account on a new deployment gets the Owner role. If two requests to create that account arrive at the same moment, both can see that no user exists yet, and both become Owners. This PR makes the two ways of creating the first account, the setup form and a first GitHub or OIDC sign-in, take turns. Only one request creates the Owner. Any other request that arrived at the same time gets the answer it would get today after setup is finished.

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

Note

This PR is stacked on #32324 and targets that branch, so the diff shows only this change. It will be rebased onto main after #32324 merges.

How to navigate this PR
  • About 60 lines of production code in four files, and about 400 lines of tests in one new file. No migration, no new query and no generated files.
  • Read these closely, in this order:
    1. coderd/database/lock.go: the new lock ID. Check that it is declared outside the numbered list.
    2. coderd/firstusersetup.go (new): lockFirstUserSetup takes the lock and returns the user count while the lock is held. This is the most important function. Both paths call it.
    3. coderd/users.go: postFirstUser. The call to CreateUser moves into a transaction that calls the helper first. Most of the diff here is indentation. Check that the checks above it, and the trial request, stay outside the transaction.
    4. coderd/userauth.go: oauthLogin. One inserted block. Check its condition: the lock is taken only when the first count is zero and the person has no account.
    5. coderd/firstusersetup_test.go (new): the tests.
  • The only change that affects code outside first-user setup is the block in oauthLogin, which every GitHub and OIDC sign-in passes. It does nothing when a user already exists.
Implementation
  • coderd/database/lock.go: adds LockIDFirstUserSetup, derived from a string with GenLockID.
  • coderd/firstusersetup.go: adds lockFirstUserSetup, which takes a Postgres advisory lock for the length of the transaction and then counts the users, and errFirstUserExists.
  • coderd/users.go: postFirstUser creates the user in a transaction. It takes the lock, counts again, and returns the existing 409 when the count is no longer zero.
  • coderd/userauth.go: oauthLogin takes the lock when the first count is zero and the person is new, and replaces its user count with the count taken under the lock. The lines below it that decide whether a sign-up is allowed and whether to give the Owner role already read that variable.
  • Both paths write one warning line, with the remote address, when a request waited for the lock and then found a user.

Choices a reviewer might question

  • The lock ID is not added to the numbered list. That list has a different length on each release branch, so a new entry would get a different number on each one, and this fix is meant to be backported.
  • The user count is read twice. The first read, without the lock, stays so that a request after setup is answered without touching the lock, and so that ordinary sign-ins never wait on it.
  • The count under the lock is correct only at read committed. Both transactions ask for it with firstUserSetupTxOptions(), so that a Postgres server whose default is repeatable read or serializable gets the same result.
  • The lock blocks. A request that could not get the lock at once would not know yet whether the request holding it will succeed, so it could not answer truthfully.
  • The password is hashed while the lock is held, because CreateUser hashes inside its transaction. Moving it would change a function that other callers use.
  • The trial licence request is an outbound call, so it stays before the lock.
  • On the OAuth path a request that waited gets no new error. It continues as an ordinary sign-up.

Known limit

  • A request that waits for the lock holds one database connection. On a deployment with no users and OAuth sign-ups enabled, a burst of first sign-ins as large as the connection pool (10 by default) can use every connection. The sign-in that holds the lock then needs one more connection to notify the Owner about the new user, and can wait until other requests time out.
  • This needs that exact burst on an empty deployment. The password path and deployments with sign-ups disabled are not affected. It has not been reproduced, and the tests cannot show it because they use a notifier with no database.
  • A fix would change CreateUser, so it is left out of this PR.
Expected Output
  • Ten first-user requests sent at the same time, with different emails, create one user with the Owner role. One request gets 201. Nine get 409 with "The initial user has already been created."
  • Ten GitHub or OIDC first sign-ins at the same time, with sign-ups disabled, create one user with the Owner role. The other nine get the existing "Signups are disabled" page.
  • The same with sign-ups enabled creates ten users, and exactly one has the Owner role.
  • A first-user request and an OAuth first sign-in at the same time create exactly one Owner.
  • A single request with nothing else happening behaves as before on both paths.
  • A first-user request after setup still gets 409 at once and does not wait.
  • A sign-in or sign-up on a deployment that has users does not take the lock.
  • A request refused for a missing setup token, or for a weak password, is refused before the lock and does not wait.
  • If the request holding the lock fails, nothing is saved and the next request can create the first user.
  • A client that disconnects while waiting stops waiting, and no user is created for it.
  • Only the request that created the user sends first-user telemetry.
  • No request field, response field, status code or message changes.
Testing

All in coderd/firstusersetup_test.go:

  • TestFirstUserSetup_ConcurrentPassword: ten first-user requests at once. Checks one 201, nine 409s, one user, one Owner and one telemetry report.
  • TestFirstUserSetup_ConcurrentOAuth: ten GitHub sign-ins by different users at once, with sign-ups disabled and enabled. Checks the statuses, the user count and that there is one Owner.
  • TestFirstUserSetup_PasswordAndOAuth: five first-user requests and five GitHub sign-ins at once. Checks that there is one Owner.
  • TestFirstUserSetup_Lock: the test holds the lock itself.
    • RequestWaitsForLock: a first-user request waits, and returns 201 after the lock is released. The test reads pg_locks to see the request waiting, so it does not depend on timing.
    • ClientGivesUp: the client cancels while waiting. The server stops waiting and no user is created.
    • TrialRequestedBeforeLock: the trial generator is called while the lock is still held by the test.
    • ServerDefaultRepeatableRead: the test database defaults to repeatable read. A user is committed while a request waits for the lock. The request is refused, on the password path and on the GitHub path.
    • NotTakenWhenUsersExist: with a user present, a first-user request and a GitHub sign-up both complete while the test holds the lock.
  • The concurrent OAuth tests use the GitHub callback, not OIDC. Both end in oauthLogin. The fake OIDC provider in coderd/coderdtest/oidctest/idp.go writes its shared OAuth2 config on every login, which the race detector reports when two logins run at once.
  • Checked that the tests catch the bug: with the changes to coderd/users.go and coderd/userauth.go removed, the three concurrent tests fail, and ten requests create ten Owners. With the trial request moved inside the lock, or the lock taken on every sign-up, the matching sub-test fails. With the transactions left at the server default, ServerDefaultRepeatableRead fails.
  • Not covered by an automated test: a failure of the request that holds the lock, two replicas on one database, and the warning line. The setup token order is covered by the existing tests from feat: require a setup token to create the first user on a tunnel #32324, which still pass.
  • Ran and passed:
    • go test ./coderd/ -run 'TestFirstUserSetup' -count=3 -race -parallel=4
    • go test ./coderd/ -parallel=3 for TestFirstUser, TestFirstUser_OnboardingTelemetry, TestUserOIDC, TestUserOAuth2Github, TestUserLogin, TestPostLogin, TestPostUsers and the other OIDC tests: 124 passed.
    • golangci-lint run ./coderd/ ./coderd/database/ and go run ./scripts/intxcheck ./coderd/.
  • Not run locally: make pre-commit, make gen and the full test suite.

develop.sh, the compose dev environment and the deploy-ephemeral skill
created every admin and member user with the same public password.
Each now generates a random password per user on first use, stores it
in a file only the owner can read, prints it, and reuses it on later
runs. The old default is refused as an override.

A user that already exists keeps its password. develop.sh warns when
it did not set that password, and stops with advice when it has no
way to sign in.
A compose environment created before passwords were generated has the
member user but no member password file. setup-users exited 1 there, and
the site service never started because it waits for setup-users. It now
warns that it did not set the member's password and exits 0. It still
fails when the member has to be created and no password is available.
…vironment

setup-users warned when the member existed without a password file.
setup-init only said the admin password was not set by the
environment. The admin is the Owner, so it now gets the same warning.
Both scripts call one function in password.sh.
An instance created before passwords were generated kept the old public
default for [email protected] and [email protected]. develop.sh and the
compose setup now give such a user a generated password. The old default
is sent as the current password, so the server keeps a password that was
changed by hand.

Changing the admin password revokes its tokens, so develop.sh signs in
again and the compose setup recreates the bootstrap token.
…that keep the database

When --password signed in and no admin password was stored, develop.sh
forgot it, so the next run without the flag stopped once the saved
session expired. It is now saved to the admin password file, which is
never replaced when it already exists.

The unknown-password error now lists the two ways out that keep the
database before --db-reset.
A server published through a try.coder.app tunnel let the first
visitor become Owner. The server now prints a setup token at startup
when it opened a tunnel and no user exists. The first-user endpoint
refuses a request without it, and an OAuth sign-in cannot create the
first user until setup is complete.
The slim binary must not import coderd/rbac, and the setup token code
reaches it through dbauthz. It is only used by the server command,
which is already left out of slim builds.

Also write the nolint directive without a leading space.
A short --setup-token stopped the server even when an access URL was
set and the token was ignored. The warning for an ignored token now
names coder server create-admin-user.
The setup page hint and the install page said a matching email is
enough to sign in with GitHub later. The account must also be switched
under Account > Security. The quickstart and the GCP guide now say
where to find the setup token.
A stored password did not show that the server still accepted it.
develop and compose now replace the old default whether or not a
password file exists, and store an override that signs in when the
stored password differs. develop signs in as the admin with the old
default instead of using the saved session, which can belong to
another user. A refused stored password has its own error in develop,
and the compose error names the source, the HTTP status and the
recovery.
…expired

The bootstrap token expires after the default token lifetime of 7 days.
An environment created before passwords were generated then kept the old
default password, because setup-init had no way to sign in. It now signs
in with the old default to replace it.

An accepted CODER_DEV_ADMIN_PASSWORD is also stored on the first run, so
a later start without the variable can still create a new token.
Concurrent requests during first-user setup could each read a user
count of zero and each create a user with the owner role. Both the
password path and the OAuth path now take an advisory lock, count the
users again while holding it, and create the user in the same
transaction. A request that waited gets the existing 409, or
continues as an ordinary sign-up on the OAuth path.

The lock ID is derived from a string so that it has the same value on
every release branch.
@linear-code

linear-code Bot commented Nov 19, 2026

Copy link
Copy Markdown

CORE-853

@BobbyHo

BobbyHo commented Nov 19, 2026

Copy link
Copy Markdown
Collaborator Author

/coder-agents-review Please limit the review to P0, P1, and P2 issues only.

@coder-agents-review

coder-agents-review Bot commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

Chat: Review in progress (10/10 reviewers complete) | View chat
Requested: 2026-11-19 01:42 UTC by @BobbyHo
Spend: $16.85 / $100.00

Review history
  • R1 (2026-11-19): 13 reviewers, 1 P2, COMMENT. Review

deep-review v0.13.0 | Round 2 | c6cd321..5116516

Last posted: Round 2, 1 findings (1 P2), APPROVE. Review

Finding inventory

Findings

# Sev Status Location Summary Round Reviewer Posted
CRF-1 P4 Dropped by orchestrator (author asked for P0 to P2 only) firstusersetup_test.go:152 requireLockWaiters counts every ungranted advisory lock, not only the setup lock R1 Netero No
CRF-2 P4 Dropped by orchestrator (author asked for P0 to P2 only) users.go:289 409 message text duplicated in two responses and errFirstUserExists R1 Netero No
CRF-3 P4 Dropped by orchestrator (author asked for P0 to P2 only) userauth.go:1793 OAuth lock error return (client cancel while waiting) has no coverage R1 Netero No
CRF-4 Note Dropped by orchestrator (author asked for P0 to P2 only) firstusersetup_test.go:161 ConcurrentPassword is probabilistic and can pass without the fix R1 Netero No
CRF-5 P2 Author fixed (5116516) firstusersetup.go:17 Lock transactions inherit server default isolation; at repeatable read a second Owner is created R1 Razor P3, Pariston P3, Gon P3, Leorio P3 Yes
CRF-6 OOS Out of scope (body) users.go:2199 CreateUser enqueues notification on a second pool connection inside the caller's tx; pool-size OAuth sign-up bursts hang R1 Kurapika P2, Killua P2, Hisoka P2, Knuckle P3, Ryosuke P3, Takumi Note, Pariston Note, Mafuuu OOS No
CRF-7 P4 Dropped by orchestrator (author asked for P0 to P2 only) users.go:224 Losing first-user request with trial still inserts a trial license R1 Hisoka P4, Mafuuu Note, Takumi OOS No
CRF-8 P4 Dropped by orchestrator (author asked for P0 to P2 only) firstusersetup_test.go:284 PasswordAndOAuth discards HTTP statuses R1 Bisky No
CRF-9 P4 Dropped by orchestrator (downgraded from Gon P2; author asked for P0 to P2 only) users.go:180 postFirstUser comment names "oidc" instead of oauthLogin (GitHub and OIDC) R1 Gon No
CRF-10 Nit Dropped by orchestrator (downgraded from Gon P2; author asked for P0 to P2 only) users.go:257 Comment above lockFirstUserSetup call longer than its reason R1 Gon No
CRF-11 Nit Dropped by orchestrator (downgraded from Gon P2; author asked for P0 to P2 only) userauth.go:1788 Comment clause repeats the if condition R1 Gon No
CRF-12 Nit Dropped by orchestrator (downgraded from Gon P2; author asked for P0 to P2 only) firstusersetup_test.go:211 wantUsers field comment restates the name R1 Gon No
CRF-13 Nit Dropped by orchestrator (downgraded from Gon P2; author asked for P0 to P2 only) firstusersetup_test.go:267 "Half of the requests use each path" restates the branch R1 Gon No
CRF-14 Nit Dropped by orchestrator (author asked for P0 to P2 only) firstusersetup_test.go:213 wantOther name and "the first" wording R1 Gon No
CRF-15 Nit Dropped by orchestrator (author asked for P0 to P2 only) firstusersetup_test.go:27 concurrentFirstUserRequests has no comment and covers OAuth too R1 Gon No
CRF-16 OOS Out of scope (body) users.go:2187 CreateUser notifies admins before the caller's tx commits; rolled-back oauthLogin notifies about a nonexistent account R1 Pariston No
CRF-17 OOS Out of scope (body) userauth.go:1878 oauthLogin reports first-user telemetry inside the tx before org/group/role sync R1 Ryosuke No
CRF-18 OOS Dropped by orchestrator (author asked for P0 to P2 only; comment wording in unchanged lines) users.go:274 Re-indented "dormant" comment wording R1 Gon No
CRF-19 OOS Dropped by orchestrator (author asked for P0 to P2 only; comment wording in unchanged lines) userauth.go:1802 "sign up with OIDC" comment also covers GitHub R1 Gon No
CRF-20 Nit Dropped by orchestrator (downgraded from Gon P2; author asked for P0 to P2 only) firstusersetup.go:15 firstUserSetupTxOptions doc restates the body R2 Gon No
CRF-21 Nit Dropped by orchestrator (downgraded from Gon P2; author asked for P0 to P2 only) firstusersetup_test.go:148 setDefaultRepeatableRead doc restates name and SQL R2 Gon No
CRF-22 Nit Dropped by orchestrator (downgraded from Gon P2; author asked for P0 to P2 only) firstusersetup_test.go:334 ServerDefaultRepeatableRead comment second sentence restates body R2 Gon No
CRF-23 Nit Dropped by orchestrator (downgraded from Gon P2; author asked for P0 to P2 only) firstusersetup_test.go:341 request field comment restates name and signature R2 Gon No
CRF-24 P4 Dropped by orchestrator (author asked for P0 to P2 only) firstusersetup_test.go:137 sync.Once plus wrapper can be sync.OnceFunc R2 Ging-Go No
CRF-25 OOS Dropped by orchestrator (no consequence: needs direct DB access, so the operator already has full control; author asked for P0 to P2 only) cli/server_createadminuser.go:1 create-admin-user inserts an Owner without the setup lock R2 Kite No

Contested and acknowledged

Round log

Round 1

Netero first pass: 3 P4, 1 Note. No P0, panel proceeds. Author comment requests P0 to P2 findings only.

Full panel (round 1). Multi-domain, security-sensitive (first Owner creation, unauthenticated endpoint, Postgres locking). Specialists: ging-go, kurapika, knuckle, takumi, ryosuke, killua. Core: pariston, mafuuu. Pool: bisky (tests), hisoka, gon, leorio (once-per-PR floor). Wildcard: razor (shuf from distilled set). 13 reviewers; target 9 to 12 exceeded by one because Gon and Leorio were placed in round 1 per the floor.

Cross-check:

  • CRF-5 raised from P3 to P2. Four reviewers converge; Razor and Pariston reproduced it, and Razor's run created a second Owner at repeatable read. The consequence is the bug the PR fixes, so "wrong but survivable" (P2) fits better than "rough edge". Precedent for pinning read committed: coderd/oauth2provider/tokens.go:538, coderd/experiments/write.go:114.
  • CRF-6 classified out of scope. Keep-argument: the lock adds an unbounded blocking wait inside a transaction, so waiters hold connections while they queue. Drop reason: Takumi's runs with the real StoreEnqueuer showed identical outcomes with and without the PR (pool 10 with 10 callbacks passed in both, pool 10 with 20 callbacks hung in both); Mafuuu reproduced the hang at base with an existing Owner (pool 4, 4 sign-ups, 3 of 3 runs) and a retry-without-lock variant still hung. Empirical results override Hisoka's "cannot happen at base" (Hisoka's setup held the lock from a separate pool, which has no base equivalent). Root cause is CreateUser's enqueue on api.Database during an open transaction, which the PR does not change.
  • Gon's comment findings downgraded from P2. Keep-argument for CRF-9: a reader following "oidc" could miss the GitHub path. Downgrade reason: the sentence the PR appends names lockFirstUserSetup, whose two callers are found by one search; the "oidc" wording predates the PR. The rest restate adjacent code, which is Nit.
  • Reviewed against c6cd321..a1e358a.

Round 2

Churn guard PROCEED: CRF-5 addressed in 5116516. Netero (advisory): no findings, CRF-5 fix verified by breaking it on purpose.

Fix round (not a restructure: no files added, renamed, or moved; no exported signature change; effective additions grew by 88). Panel: razor, pariston, gon, leorio (raised CRF-5, code touched), ging-go, bisky, knuckle (changed Go, test, isolation), wildcard kite (shuf from distilled set). Gon and Leorio also required because comments changed.

Cross-check: CRF-5 verified fixed by Razor, Pariston, Gon, Leorio, Bisky, Knuckle, Kite. Each reverted a call site and saw ServerDefaultRepeatableRead fail. Gon's four comment findings downgraded from P2 to Nit. Keep-argument: comment length is a pattern across the PR. Downgrade reason: the comments are accurate and the code works, which is the Nit definition. Kite's side-effect note (every OAuth login transaction now runs at read committed) has no consequence; the rest of that transaction makes only database calls. No P0 to P2 findings open. Reviewed against c6cd321..5116516.

About deep-review

CRF = Coder Review Finding (P0-P4, Nit, Note)

Reviewer Focus
Bisky tests
Chopper ops/errors
Churn-guard change verification
Ging language modernization
Gon naming
Hisoka edge cases
Killua perf
Kite change integrity
Knov contracts
Knuckle SQL
Komugi flake/determinism
Kurapika security
Law decomposition
Leorio docs
Luffy product
Mafu-san process
Mafuuu contracts
Melody dispatch/pairing
Meruem structural
Nami frontend
Netero mechanical checks
Pariston premise testing
Pen-botter product gaps
Razor verification
Robin duplication
Ryosuke Go arch
Takumi concurrency
Zoro shape

🤖 Managed by Coder Agents.

@coder-agents-review coder-agents-review Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This PR makes postFirstUser and oauthLogin take a transaction-scoped advisory lock and count the users again before creating the first user. One P2 finding. As you asked, findings below P2 are not posted.

Out of scope (needs a ticket or explicit acceptance by a human):

  • coderd/users.go:2199: CreateUser enqueues the account-created notification through api.NotificationsEnqueuer, which needs a second pool connection while the caller's transaction is still open. With OAuth sign-ups enabled, a number of concurrent sign-ups equal to the pool size leaves every request holding one connection and waiting for another, so they all hang until clients disconnect. This also happens at the base commit, and on deployments that already have an Owner. Making lock waiters roll back and retry did not remove it. The PR description's "Known limit" says only the new lock on an empty deployment causes it.
  • coderd/users.go:2187: the same notifications are sent before the caller's transaction commits, so an oauthLogin that later rolls back (for example, when org or group sync fails) tells admins about an account that does not exist.
  • coderd/userauth.go:1878: oauthLogin reports first-user telemetry inside the transaction, before org, group, and role sync. If one of those fails, telemetry has reported a first user that does not exist.

🤖 This review was automatically generated with Coder Agents.

Comment thread coderd/firstusersetup.go Resolved
The count taken under the first-user setup lock must see a user that
another request committed during the wait. That holds at read
committed. Both transactions passed no options, so they ran at the
Postgres server's default level. Where an operator has set
default_transaction_isolation to repeatable read, the count came from
a snapshot taken before the wait and a second owner was created.

Both transactions now ask for read committed.
@BobbyHo

BobbyHo commented Nov 19, 2026

Copy link
Copy Markdown
Collaborator Author

/coder-agents-review Please limit the review to P0, P1, and P2 issues only.

@coder-agents-review coder-agents-review Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Round 2 reviewed the read committed fix in 511651665d. The unpinned isolation level is fixed: both lock transactions now use firstUserSetupTxOptions(), and TestFirstUserSetup_Lock/ServerDefaultRepeatableRead fails on each path when that path's options are reverted. No new P0 to P2 findings. The out-of-scope items from round 1 are unchanged and still need a ticket or explicit acceptance by a human.

🤖 This review was automatically generated with Coder Agents.

@BobbyHo
BobbyHo marked this pull request as ready for review November 19, 2026 01:55
@BobbyHo
BobbyHo requested review from a team and geokat November 19, 2026 01:55
Base automatically changed from bobby/core-784-setup-token to main November 20, 2026 03:22
…tyhigh-prevent-concurrent-first-user

# Conflicts:
#	.agents/skills/deploy-ephemeral/SKILL.md
#	coderd/userauth.go
#	scripts/develop/main.go
#	scripts/develop/password.go
#	scripts/develop/password_test.go
@BobbyHo
BobbyHo merged commit cf68914 into main Nov 20, 2026
29 checks passed
@BobbyHo
BobbyHo deleted the bobby/core-853-securityhigh-prevent-concurrent-first-user branch November 20, 2026 16:12
@github-actions github-actions Bot locked and limited conversation to collaborators Nov 20, 2026

This branch had an error being deployed

1 failed and 1 inactive deployments
main — 148f5eac Deployed Nov 20, 2026 by BobbyHo via Backport to release/2.34 #7235
docs-preview — 148f5eac Deployed Nov 20, 2026 by BobbyHo via cleanup #286
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants