Skip to content

fix(api): atomic first-superadmin election without demotion (replaces #2753) - #2772

Merged
simple-agent-manager[bot] merged 11 commits into
mainfrom
sam/fix-first-superadmin-election
Nov 16, 2026
Merged

simple-agent-manager[bot] merged 11 commits into
mainfrom
sam/fix-first-superadmin-election

Conversation

@simple-agent-manager

@simple-agent-manager simple-agent-manager Bot commented Nov 15, 2026 •

Copy link
Copy Markdown
Contributor

Summary

This replaces Codex Security draft PR #2753. The finding was confirmed real (low to medium) on 2026-11-15, but the patch had defects.

Vulnerability (confirmed): in apps/api/src/auth.ts, the user.create.before hook read "no real users" and returned role: 'superadmin'. The insert happens after the hook, so two first sign-ups racing on a fresh install both won. This applies only to installs without BOOTSTRAP_OWNER_EMAIL.

Kept from the scanner patch: the atomic election, which runs a guarded UPDATE plus a platform_settings marker insert in one D1 batch (apps/api/src/services/first-superadmin.ts). It runs in session.create.before.

Defects fixed:

  1. Two failing tests.

    • first-superadmin.test.ts builds its tables from the drizzle schema, so they include updated_at.
    • auth.test.ts now uses installSignupApprovalQuery() instead of the removed mock.
  2. The migration no longer demotes anyone. It only inserts the marker, and only when a non-system superadmin exists. It never touches user rows.

    • Instances that have more than one superadmin get a first-superadmin.multiple_superadmins warning on each sign-in. The count comes from the existing first read, so it adds no query.
    • The self-hosting guide has a query to review those accounts and a command to demote one.
  3. "Only real user" guard. The guarded UPDATE requires all of the following:

    • the target is not a system row;
    • the target is not suspended;
    • the target is not already superadmin;
    • no other real account exists, in any status;
    • the marker is absent.

    Real-SQL tests cover (a) a sole suspended user plus a new sign-up and (b) a sole non-admin user plus a new sign-up. Each is paired with an owner-path control. A stale-read test covers the guard inside the UPDATE.

  4. A D1 failure no longer blocks sign-in. On error, session.create.before logs auth.first_superadmin_election.failed and returns the session without promoting anyone. A workers test drives BetterAuth's real createSession against a failing D1, then shows the user is elected on the next sign-in once D1 recovers.

  5. Recovery documented in self-hosting.mdx ("Recovering when no account can administer the instance"), admin-settings.md, security.md and configuration.md. There are two paths:

    • set the BOOTSTRAP_OWNER_EMAIL Worker secret (not available on installer-bound instances whose owner is already established);
    • promote an account directly in D1.

Design decision (fail closed): if two sign-ups both create their account rows before either election runs, both lose. The install then has no superadmin until the documented recovery is used. Electing the oldest account instead would also promote someone on upgraded installs that have several users and no superadmin, so that option was rejected. This matches the project's "fail closed instead of insecure fallback" policy.

Migration number: 0246_first_superadmin_election.sql. It was renumbered from 0243 in 0cdc603 because main now has 0245_asks.sql and #2691 also uses 0243. The migration-ordering check only rejects duplicate prefixes. Tests locate the file by its name suffix.

Validation

  • Typecheck clean; ESLint clean on touched files; pnpm quality:migration-safety 0 violations; format:check ratchet passes
  • Targeted: first-superadmin.test.ts + auth.test.ts 45/45; superadmin-self-heal.test.ts (workers, real D1) 21/21
  • Full API unit suite: 15251 passed, 4 skipped, 1 failed. The failure was an unrelated timing flake (capacity-pool-edit-query-plan.test.ts, 5s timeout on a shared machine). It passes alone, and this branch doesn't touch that file.
  • Workers suite in 4 shards: 542 + 66 + 578 + 540 + 485 tests, all passed
  • CI

Discrimination checks (each guard deleted once):

Removed Tests that went red
"Only real user" guard (a) and (b) attack cases, the overlapping-race case, and the migration "promotes nobody" case (the controls stayed green)
Marker guard in the UPDATE stale-read test
Suspended guard suspended sole user test
System guard on the target system-user test
Duplicate warning reporting test
The scanner's demoting migration swapped back in duplicate-preservation, "promotes nobody", and reporting tests
try/catch in auth.ts workers D1-outage test
Owner-email skip workers owner-email skip test

Per-sign-in cost: once established, +1 D1 round trip per session creation (the marker and duplicate count in one SELECT). Before establishment: +2.

Staging Verification (REQUIRED for all code changes — merge-blocking)

Verified on staging2 (sammy2.party). The primary staging worker is blocked by the #2721 DO migration tag. Deploy run 43812594179 of head 0cdc603 passed: lease, validate, deploy (D1 migrations applied) and smoke tests.

  • Staging deployment green, with migration applied: 0246_first_superadmin_election.sql is recorded in d1_migrations
  • Live app verified via Playwright: the ordinary user signed in and loaded /dashboard, /projects and /settings (all 200, no error text)
  • Existing workflows confirmed working: two existing users signed in after the deploy
  • New feature/fix verified on staging: superadmin rows are identical before and after the migration, and the marker was written
  • Infrastructure verification completed: N/A, no infra changes
  • Mobile and desktop verification notes added for UI changes: N/A

Staging Verification Evidence

Check Before deploy (05:48Z) After migration and sign-ins (06:11Z)
users WHERE role='superadmin' staging2-agent-admin (active) staging2-agent-admin (active), unchanged
Ordinary user staging2-agent-user: role user role user (not promoted)
System sentinel system_anonymous_trials: role user, status system unchanged
Marker setup.firstSuperadminEstablished absent {"version":1,"ownerId":"staging2-agent-admin"}, written 05:56:30Z by the migration
Latest migration 0245_asks.sql 0246_first_superadmin_election.sql

Sign-ins after the deploy:

  • At 06:10:27Z the ordinary user signed in through workload identity and loaded the app. A new sessions row was created and their role stayed user.
  • At 06:10:28Z the admin signed in through token-login. GET /api/auth/me returned role: superadmin, and GET /api/admin/users listed exactly one superadmin.

Both logins completed, so the election hook ran without blocking sign-in. The only console errors were 404s for a placeholder /projects/none URL used by the check script.

UI Compliance Checklist (Required for UI changes)

N/A: no UI changes.

End-to-End Verification (Required for multi-component changes)

  • Data flow traced with code path citations
  • Capability test exercises the complete path: BetterAuth's real session hooks on real D1 (workers tests), plus the real migration SQL on SQLite
  • Assumptions verified against code: sentinel exclusion, bootstrapSessionAllowed independent of the marker, admin API cannot grant superadmin
  • Manual verification documented: see Staging Verification Evidence

Data Flow Trace

  1. On sign-up, BetterAuth's user.create.before (auth.ts) no longer promotes anyone; the account is created as an ordinary user.
  2. On the first session, session.create.before calls establishFirstSuperadmin(env.DATABASE, userId) when bootstrapOwnerEmail(env) is unset. That runs one SELECT (marker exists? superadmin count) and then, if the install is not yet established, a D1 batch: ELECT_SQL (the guarded UPDATE), then RECORD_SQL (insert the marker naming the oldest real superadmin).
  3. session.create.after self-heal (LOGIN_SELF_HEAL_SQL) applies the same sole-user conditions plus NOT EXISTS marker. It is a retry only when the election failed.
  4. Migration 0246_first_superadmin_election.sql backfills the marker on installs that already have a superadmin.
  5. Recovery: bootstrapSessionAllowed (services/bootstrap-owner.ts) promotes a verified BOOTSTRAP_OWNER_EMAIL while no superadmin exists and the owner is not yet established.

Untested Gaps

The concurrency test uses better-sqlite3, so it proves the guard predicates rather than true cross-isolate interleaving. Atomicity rests on D1's batch transaction and single-statement UPDATE semantics.

Post-Mortem (Required for bug fix PRs)

What broke

Two concurrent first sign-ups on a fresh install could both become superadmin.

Root cause

A "no other users" read in user.create.before decided the role before the insert, which is a check-then-act gap.

Class of bug

A privilege decided by a non-atomic count instead of in the final atomic write (rule 69: enforce at the final reservation).

Why it wasn't caught

The existing tests ran sign-ups sequentially.

Process fix included in this PR

The election is a single guarded write. Real-SQL attack and control tests cover it, plus BetterAuth-driven workers tests.

Post-mortem file

The task file tasks/active/2026-11-15-ship-codex-security-fixes-2753-2754-2755.md lives on the #2759 branch.

Specialist Review Evidence (Required for agent-authored PRs)

  • All local reviewers completed and findings addressed before merge
  • If any reviewer did NOT complete: needs-human-review label added and merge deferred to human: N/A
Reviewer Status Outcome
security-auditor PASS Adversarial review: the fix holds. I found no path to two superadmins and no path for a stranger to be promoted. 3 LOW items: the owner-email recovery doesn't apply on established installer-bound instances (now documented); an extra account blocks the election (by design, documented); the self-heal promotes without writing the marker (it is backfilled on the next sign-in).
cloudflare-specialist PASS MEDIUM items: the migration-number clash with #2721, handled at merge time as above; the permanent lockout when two accounts exist before the election (fail-closed, documented). The migration is safe and replay-safe, the batch is atomic, and the per-sign-in cost is +1 round trip.
task-completion-validator PASS All five code requirements are done. The discrimination evidence is recorded above.
doc-sync-validator ADDRESSED wrangler secret put now uses --name; the owner-email recovery is scoped; the warning-condition wording is fixed; admin-settings.md and .env.example were stale. All fixed in 75e3fa7.

CodeRabbit Review Evidence (Required for agent-authored PRs)

  • CodeRabbit requested after local review, staging if applicable, and CI gates passed
  • Waited about 15 minutes, or up to about 45 minutes in total while a review CodeRabbit had started was still in progress
  • Either CodeRabbit reviewed and no CodeRabbit feedback is unresolved, or it did not review and the observed outcome is recorded below

CodeRabbit Notes

  • 06:46:08Z: coderabbit-review label applied after CI run 43815768248 passed and staging2 verification completed. The bridge workflow run 43819045056 succeeded.
  • 07:02Z: CodeRabbit did not review. It answered "Review rate limited" ("You've used all free OSS reviews for now"). Per rule 25, a rate-limited CodeRabbit is recorded and does not block merge.

Exceptions (If any)

  • Scope: none
  • Rationale:
  • Expiration:

Agent Preflight (Required)

  • Preflight completed before code changes

Classification

  • external-api-change
  • cross-component-change
  • business-logic-change
  • public-surface-change
  • docs-sync-change
  • security-sensitive-change
  • ui-change
  • infra-change

External References

N/A: no external API changes. BetterAuth database-hook behaviour was verified through the existing workers harness, which drives the real internalAdapter.createSession.

Codebase Impact Analysis

  • apps/api/src/auth.ts: user.create.before no longer promotes anyone; session.create.before runs the election inside a try/catch; the self-heal gains a marker guard
  • apps/api/src/services/first-superadmin.ts (new)
  • apps/api/src/db/migrations/0246_first_superadmin_election.sql (new; inserts the marker only)
  • apps/api/src/routes/agent-sign-in.ts: comment only
  • Tests: tests/unit/services/first-superadmin.test.ts, tests/unit/auth.test.ts, tests/workers/superadmin-self-heal.test.ts

Documentation & Specs

  • apps/www/src/content/docs/docs/guides/self-hosting.mdx
  • apps/www/src/content/docs/docs/guides/admin-settings.md
  • apps/www/src/content/docs/docs/architecture/security.md
  • apps/www/src/content/docs/docs/reference/configuration.md
  • apps/api/.env.example
  • apps/api/.claude/rules/40-sentinel-rows-excluded-from-counts.md (a note on where the promotion lives)

Constitution & Risk Check

  • Principle XI: no new tunables.
  • Migration safety: append-only marker insert, no row changes (rule 31).
  • Fail closed: a D1 error never promotes anyone, and the race yields no superadmin rather than two.
  • Risk: in the rare double race, an operator has to use the documented recovery.

🤖 Generated with Claude Code

raphaeltm and others added 7 commits November 15, 2026 13:44
Corrects the bot election from #2753:

- Election (services/first-superadmin.ts): promote the signing-in user in one
  guarded UPDATE only while they are the ONLY real (status != 'system') account,
  are not suspended, and the election marker is absent; then record the oldest
  real superadmin as the marker in the same D1 batch. A later sign-up never wins
  against an existing account (suspended or non-admin), and two sign-ups whose
  rows both exist fail closed rather than electing by timing.
- Report installs with more than one superadmin via a structured
  first-superadmin.multiple_superadmins warning on sign-in, folded into the
  existing single read. No user row is changed.
- session.create.before: catch election failures, log
  auth.first_superadmin_election.failed and continue without promotion, so a
  D1 error never blocks login.
- Migration renumbered 0242 -> 0243 (open PR #2721 already uses 0242). It now
  only inserts the marker for installs that already have a non-system
  superadmin and never updates or deletes users; the oldest-superadmin
  demotion is removed.
- Tests: real-SQL election/migration tests on drizzle-built tables (attack
  cases paired with owner controls), the auth.test fixture regression, and
  workers tests that drive BetterAuth's createSession against real D1 (happy
  path, existing-account refusal, D1 outage, owner-email skip, and the
  BOOTSTRAP_OWNER_EMAIL recovery path).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…very

Describe the one-time ordinary election (only-real-account guard, durable
setup.firstSuperadminEstablished marker, login never blocked), how to review
and resolve more than one superadmin, and the recovery paths when no account
can administer the instance: the BOOTSTRAP_OWNER_EMAIL Worker secret
(bootstrapSessionAllowed) or a direct D1 update.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…name

Coordinator decision: main ends at 0241 and the builder branch also uses 0242;
whichever merges second renumbers, so do not renumber speculatively. Tests now
find the migration by its `_first_superadmin_election.sql` suffix, and the code
comments and docs name it without a number, so a renumber is a file rename only.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- wrangler secret put needs --name (no checked-in env sections)
- owner-email recovery does not apply to an installer-bound instance whose owner
  was already established; use the D1 update there
- the duplicate-superadmin warning is logged only without BOOTSTRAP_OWNER_EMAIL
- admin-settings and .env.example no longer claim nobody is ever promoted again
- rule 40 notes where the promotion lives now

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@coderabbitai

coderabbitai Bot commented Nov 15, 2026 •

Copy link
Copy Markdown

Warning

Review limit reached

You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository.

Next included review available in 19 minutes.

Check out review usage here.

View limit details

Limit details: You’ve used the included review currently available.

Learn how review limits work.

Review configuration:

Run configuration

Commits

Reviewing files that changed from the base of the PR and between b83d697 and 0cdc603.

Files selected for processing: 13

  • apps/api/.claude/rules/40-sentinel-rows-excluded-from-counts.md
  • apps/api/.env.example
  • apps/api/src/auth.ts
  • apps/api/src/db/migrations/0246_first_superadmin_election.sql
  • apps/api/src/routes/agent-sign-in.ts
  • apps/api/src/services/first-superadmin.ts
  • apps/api/tests/unit/auth.test.ts
  • apps/api/tests/unit/services/first-superadmin.test.ts
  • apps/api/tests/workers/superadmin-self-heal.test.ts
  • apps/www/src/content/docs/docs/architecture/security.md
  • apps/www/src/content/docs/docs/guides/admin-settings.md
  • apps/www/src/content/docs/docs/guides/self-hosting.mdx
  • apps/www/src/content/docs/docs/reference/configuration.md
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

raphaeltm and others added 2 commits November 15, 2026 23:25
…ases

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
0242 is taken by the Cloudflare build executor migration (PR #2721), which is
already applied on staging. Migration-ordering CI rejects duplicate prefixes;
the migration is replay-safe and tests locate it by name.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@simple-agent-manager

Copy link
Copy Markdown
Contributor Author

Migration numbering note from the coordinator: PR #2721 has 0242_cloudflare_build_executor.sql (already applied on primary staging, so it must keep that number) and is adding a new 0244. This PR and its peer (#2772 / #2691) both propose 0243. Whichever merges second must renumber to the next free prefix after main, and the duplicate-prefix CI check will enforce that. #2753 (0242) must renumber before it can merge.

@sonarqubecloud

Copy link
Copy Markdown

@simple-agent-manager
simple-agent-manager Bot marked this pull request as ready for review November 16, 2026 06:17
@github-actions
github-actions Bot requested a deployment to staging2 November 16, 2026 06:17 Abandoned
simple-agent-manager Bot pushed a commit that referenced this pull request Nov 16, 2026
0246 is taken by #2772 (already applied on staging2), 0247 by #2780 and 0248 by #2781.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@simple-agent-manager simple-agent-manager Bot added the coderabbit-review Trigger CodeRabbit review for opt-in PRs label Nov 16, 2026
@raphaeltm

Copy link
Copy Markdown
Owner

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Nov 16, 2026 •

Copy link
Copy Markdown
Action not completed

Review rate limited.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@simple-agent-manager
simple-agent-manager Bot merged commit b06a660 into main Nov 16, 2026
69 checks passed
simple-agent-manager Bot added a commit that referenced this pull request Nov 16, 2026
* feat(overview): aggregated project overview read (operation + REST route)

projectOverviewGet returns running chats and recent ideas/merged PRs for
the Inbox F1 Project Overview page; GET /api/projects/:projectId/overview.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* refactor(chat): share the new-chat composer and start path

Move composer state and the Instant/task start out of useProjectChatState
into useNewChatComposer, which returns what it started and never
navigates. The chat page keeps opening the new chat; the Project Overview
task box will reuse the same start without leaving the page.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat(web): Project Overview page with Running now, Budgets, Automations, Recently and a task box

New lazy-loaded page at /projects/:id/overview, first in the project nav
on desktop and phone. Running now and Recently come from the aggregated
overview read (refreshed by project socket events); Budgets reuses the
composer's usage model; Automations reuses the Automation page's model and
fix button through a new one-line AttentionLine. The task box is the real
new-chat composer and start path; sending stays on the page with a receipt
and an optimistic Running now row.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(overview): task box start without navigation, budgets wording, composer collapse

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* style: sort test imports

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(overview): Playwright visual audit; keep the idle phone task box to one row

The composer measured its height only when its text changed, so a box
first measured while its row was narrower kept a wrapped placeholder's
height. It now re-measures on width changes. While folded, attach waits
in the To row.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs: Project Overview guide and overview API reference

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* style: sort operations exports

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(overview): review findings — waiting-on-you ranked first, phone box refolds, accessible budgets

- Running now ranks chats waiting on the viewer first and reports
  waitingOnViewerTotal, so the cap never hides the page's one exception
  ('7 more running · 2 waiting on you').
- Composer folds on an outside tap or a completed send instead of on blur
  (iOS does not focus tapped buttons); the success receipt is transient;
  receipt live regions are persistent; the text box has a name.
- Budgets tiles speak the usage left; failing automations count in red with
  a secondary Resume; compact idea rows in Recently.
- Merged PR links must be https; global profile names only for the task
  creator's own profiles.
- Performance: index for newest merged PRs (migration 0246), a lighter
  recent-ideas read (11 measured round trips), no socket refetch on a
  hidden tab, ResizeObserver work deferred to the next frame.
- Tests: nav order on desktop and phone, round-trip budget, query plan,
  automation fix, Recently links, hidden-tab, fold-after-send.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* style: sort operations imports

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* task: archive inbox F1 project overview task

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test: sidebar scroll audit counts the Overview nav item

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* task: record F1 checklist and review outcomes

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* chore: renumber overview index migration to 0249

0246 is taken by #2772 (already applied on staging2), 0247 by #2780 and 0248 by #2781.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: give the GitHub sign-in prompt a painted background

The app-wide prompt in AuthProvider used bg-surface-elevated, a class no theme defines, so it
rendered transparent over whatever sat at the bottom of the page. Staging2 showed it over the
Overview task box. Use the Toast's glass-surface and shadow-dropdown. The Overview audit gains a
GitHub-reauth failed-start scene that asserts the prompt paints a background (red against the
old class).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Raphaël Titsworth-Morin <raphael@raphaeltm.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

This branch had an error being deployed

1 abandoned and 1 inactive deployments
staging2 — 0cdc6037 Deployed Nov 16, 2026 by github-actions[bot]
staging — 0cdc6037 Deployed Nov 16, 2026 by simple-agent-manager[bot] via lease #2909
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

coderabbit-review Trigger CodeRabbit review for opt-in PRs

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant