fix(auth): an invite is the only way to an account

The README offered open registration, and the register handler still had
a branch for a registration_settings mode nothing could set. Now every
account after the first needs an invite; the first still needs the setup
token from the log. Migration 0110 drops registration_settings and its
queries, and backups no longer carry it (an older backup that holds it
restores without it). The web form asks for the invite token as required.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-26 08:59:25 -05:00
co-authored by Claude Opus 5.5
parent de335333da
commit dd27e014c0
10 changed files with 69 additions and 137 deletions
+31 -38
View File
@@ -40,29 +40,30 @@ type registerReq struct {
// handleRegister implements POST /api/auth/register.
//
// An invite from an admin is the only way to an account. The one exception is
// the first account on an empty server, which becomes the admin and needs the
// setup token from the server log instead.
//
// Flow:
// 1. Validate username/password format + minimum lengths.
// 2. Look up registration_settings.mode and current user count.
// 3. If users table is empty: insert via CreateUserFirstAdminRace
// (sets is_admin from a SELECT NOT EXISTS subquery). Skip invite
// check.
// 4. Else if mode == 'invite_only': atomically redeem invite via
// RedeemInvite (returns rows-affected; 0 means no usable
// invite — reject 400).
// 5. Else (mode == 'open'): proceed without invite check.
// 6. Hash password, mint session token, insert session row, set
// 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.
// 4. Hash password, mint session token, insert session row, set
// cookie, return user + token.
// 7. Audit ActionRegister and (if invite was used) ActionInviteRedeem.
// 5. Audit ActionRegister and ActionInviteRedeem.
//
// Errors:
// - 400 invalid_body / username_invalid / password_too_short
// - 400 invite_required (invite_only mode, no token supplied)
// - 400 invite_required (no token supplied)
// - 400 invite_invalid (token doesn't exist, expired, or already redeemed)
// - 409 username_taken (PG unique violation on users.username)
// - 500 server_error otherwise
func (h *handlers) handleRegister(w http.ResponseWriter, r *http.Request) {
// Every attempt counts, not only failures: a successful registration is
// the thing being sprayed when the mode is open.
// 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 {
writeRateLimited(w, wait)
@@ -107,38 +108,30 @@ func (h *handlers) handleRegister(w http.ResponseWriter, r *http.Request) {
return
}
// Validate invite (skipped on empty-users state; skipped in 'open' mode).
// Every account after the first needs an invite.
usedInviteToken := ""
if userCount > 0 {
mode, err := q.GetRegistrationMode(r.Context())
if err != nil {
h.logger.Error("register: get mode failed", "err", err)
writeErr(w, apierror.Internal(err))
if req.InviteToken == "" {
writeErr(w, apierror.BadRequest("invite_required", "an invite token is required to register"))
return
}
if mode == "invite_only" {
if req.InviteToken == "" {
writeErr(w, apierror.BadRequest("invite_required", "an invite token is required to register"))
// Pre-validate existence + non-redeemed + non-expired so we fail
// fast on bad tokens before creating the user.
invite, ierr := q.GetInviteByToken(r.Context(), req.InviteToken)
if ierr != nil {
if errors.Is(ierr, pgx.ErrNoRows) {
writeErr(w, apierror.BadRequest("invite_invalid", "invite token not found"))
return
}
// Pre-validate existence + non-redeemed + non-expired so we fail
// fast on bad tokens before creating the user.
invite, ierr := q.GetInviteByToken(r.Context(), req.InviteToken)
if ierr != nil {
if errors.Is(ierr, pgx.ErrNoRows) {
writeErr(w, apierror.BadRequest("invite_invalid", "invite token not found"))
return
}
h.logger.Error("register: get invite failed", "err", ierr)
writeErr(w, apierror.Internal(ierr))
return
}
if invite.RedeemedAt.Valid || invite.ExpiresAt.Time.Before(time.Now()) {
writeErr(w, apierror.BadRequest("invite_invalid", "invite token is expired or already redeemed"))
return
}
usedInviteToken = req.InviteToken
h.logger.Error("register: get invite failed", "err", ierr)
writeErr(w, apierror.Internal(ierr))
return
}
if invite.RedeemedAt.Valid || invite.ExpiresAt.Time.Before(time.Now()) {
writeErr(w, apierror.BadRequest("invite_invalid", "invite token is expired or already redeemed"))
return
}
usedInviteToken = req.InviteToken
}
// Hash password.
+14 -57
View File
@@ -76,7 +76,6 @@ func TestRegister_InviteOnlyMode_RequiresToken(t *testing.T) {
h, pool := testHandlers(t)
// Seed an admin user so we're past the empty-users state.
seedUser(t, pool, "existingadmin", "pw", true)
// Mode is default invite_only.
body := `{"username":"newuser","password":"abcd1234"}`
req := httptest.NewRequest(http.MethodPost, "/api/auth/register", bytes.NewReader([]byte(body)))
@@ -151,62 +150,28 @@ func TestRegister_InviteOnlyMode_InvalidTokenRejects(t *testing.T) {
}
}
func TestRegister_OpenMode_NoTokenNeeded(t *testing.T) {
if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" {
t.Skip("MINSTREL_TEST_DATABASE_URL not set")
}
h, pool := testHandlers(t)
seedUser(t, pool, "preexisting", "pw", true)
// Switch to open mode; restore invite_only afterwards so other tests are
// not affected (registration_settings is a singleton not truncated by
// ResetDB).
if _, err := pool.Exec(context.Background(),
"UPDATE registration_settings SET mode = 'open' WHERE id = true"); err != nil {
t.Fatalf("set mode: %v", err)
}
t.Cleanup(func() {
if _, err := pool.Exec(context.Background(),
"UPDATE registration_settings SET mode = 'invite_only' WHERE id = true"); err != nil {
t.Logf("cleanup: restore mode failed: %v", err)
}
})
body := `{"username":"openreg","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.Errorf("status = %d, want 200; body=%s", rec.Code, rec.Body.String())
}
}
func TestRegister_DuplicateUsername_409(t *testing.T) {
if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" {
t.Skip("MINSTREL_TEST_DATABASE_URL not set")
}
h, pool := testHandlers(t)
resetUsers(t, h)
// Switch to open mode so the second attempt is not rejected by invite
// check before it can reach the INSERT and hit the unique violation.
if _, err := pool.Exec(context.Background(),
"UPDATE registration_settings SET mode = 'open' WHERE id = true"); err != nil {
t.Fatalf("set mode: %v", err)
}
t.Cleanup(func() {
if _, err := pool.Exec(context.Background(),
"UPDATE registration_settings SET mode = 'invite_only' WHERE id = true"); err != nil {
t.Logf("cleanup: restore mode failed: %v", err)
}
})
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)
// Second register with same username in open mode → 409 (unique violation).
req2 := httptest.NewRequest(http.MethodPost, "/api/auth/register", bytes.NewReader([]byte(body)))
// 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)
@@ -315,18 +280,10 @@ func TestRegister_FirstUserNeedsSetupToken(t *testing.T) {
t.Fatalf("right token: status = %d, want 200", code)
}
// Once an account exists the token plays no part: the second user is
// governed by registration mode, not the setup token.
if _, err := h.pool.Exec(context.Background(),
`UPDATE registration_settings SET mode = 'open' WHERE id = true`); err != nil {
t.Fatalf("open mode: %v", err)
}
t.Cleanup(func() {
_, _ = h.pool.Exec(context.Background(),
`UPDATE registration_settings SET mode = 'invite_only' WHERE id = true`)
})
if code := register(`{"username":"second","password":"abcd1234"}`); code != http.StatusOK {
t.Errorf("second user without 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)
}
}
+1 -1
View File
@@ -39,12 +39,12 @@ var Tables = []Table{
// Settings.
{Name: "library_settings"},
{Name: "network_settings"},
{Name: "registration_settings"},
{Name: "smtp_config", Omit: []string{"password"}},
{Name: "notification_email_settings"},
{Name: "acoustid_settings", Omit: []string{"api_key"}},
{Name: "fingerprint_settings"},
{Name: "loudness_settings"},
{Name: "lookup_settings"},
{Name: "cover_art_provider_settings", Omit: []string{"api_key"}},
{Name: "cover_art_sources_meta"},
{Name: "tag_provider_settings", Omit: []string{"api_key"}},
@@ -1,30 +0,0 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.31.1
// source: registration_settings.sql
package dbq
import (
"context"
)
const getRegistrationMode = `-- name: GetRegistrationMode :one
SELECT mode FROM registration_settings WHERE id = true
`
func (q *Queries) GetRegistrationMode(ctx context.Context) (string, error) {
row := q.db.QueryRow(ctx, getRegistrationMode)
var mode string
err := row.Scan(&mode)
return mode, err
}
const setRegistrationMode = `-- name: SetRegistrationMode :exec
UPDATE registration_settings SET mode = $1 WHERE id = true
`
func (q *Queries) SetRegistrationMode(ctx context.Context, mode string) error {
_, err := q.db.Exec(ctx, setRegistrationMode, mode)
return err
}
@@ -0,0 +1,7 @@
CREATE TABLE registration_settings (
id boolean DEFAULT true NOT NULL PRIMARY KEY,
mode text DEFAULT 'invite_only'::text NOT NULL,
CONSTRAINT registration_settings_mode_check CHECK ((mode = ANY (ARRAY['invite_only'::text, 'open'::text]))),
CONSTRAINT registration_settings_singleton CHECK ((id = true))
);
INSERT INTO registration_settings (id, mode) VALUES (true, 'invite_only');
@@ -0,0 +1,4 @@
-- An account needs an invite from an admin; the first account needs the
-- setup token from the server log. There is no open registration, so the
-- setting that would have chosen between the two is gone.
DROP TABLE registration_settings;
@@ -1,5 +0,0 @@
-- name: GetRegistrationMode :one
SELECT mode FROM registration_settings WHERE id = true;
-- name: SetRegistrationMode :exec
UPDATE registration_settings SET mode = $1 WHERE id = true;