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:
@@ -57,7 +57,7 @@ Open `http://<host>:4533/register` and create the first account with that setup
|
||||
2. **Install the Android app.** In **Settings** (`/settings`), the *Install the Android app* card downloads the app this server ships. It updates itself from your server after that.
|
||||
|
||||
**On an iPhone** there is no Minstrel app; use a Subsonic app such as play:Sub or Amperfy. Make a password for it in **Settings › Connections › Subsonic apps**, and give the app your server's address, your username and that password. Subsonic apps can browse, search, play, like and scrobble. Minstrel's daily mixes appear in them as playlists, and when an app asks the server for random songs or an instant mix it gets Minstrel's smart shuffle and radio. An app that shuffles on the phone instead shuffles at random.
|
||||
3. **Invite the household.** In **Admin › Users** (`/admin/users`), make an invite token or turn on open registration. Each person gets their own likes, history and recommendations.
|
||||
3. **Invite the household.** In **Admin › Users** (`/admin/users`), make an invite token for each person; an invite is the only way to an account. Each person gets their own likes, history and recommendations.
|
||||
4. **Optional: connect ListenBrainz.** Each person adds their own ListenBrainz token in **Settings › Connections**.
|
||||
|
||||
## Configuration
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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;
|
||||
@@ -37,7 +37,7 @@
|
||||
case 'password_too_short':
|
||||
return 'Password must be at least 8 characters.';
|
||||
case 'invite_required':
|
||||
return 'This server requires an invite token to register. Ask an admin for one.';
|
||||
return 'An invite token is needed to register. Ask an admin of this server for one.';
|
||||
case 'invite_invalid':
|
||||
return 'That invite token is invalid, expired, or already used.';
|
||||
case 'username_taken':
|
||||
@@ -162,15 +162,16 @@
|
||||
</label>
|
||||
{:else}
|
||||
<label class="block">
|
||||
<span class="mb-1 block text-sm text-text-secondary">
|
||||
Invite token <span class="text-text-secondary opacity-60">(if required by your server)</span>
|
||||
</span>
|
||||
<span class="mb-1 block text-sm text-text-secondary">Invite token</span>
|
||||
<input
|
||||
type="text"
|
||||
autocomplete="off"
|
||||
class="w-full rounded border border-border bg-background px-3 py-2 outline-hidden focus:border-accent"
|
||||
spellcheck="false"
|
||||
required
|
||||
class="w-full rounded border border-border bg-background px-3 py-2 font-mono outline-hidden focus:border-accent"
|
||||
bind:value={inviteToken}
|
||||
/>
|
||||
<span class="mt-1 block text-xs text-text-secondary">Ask an admin of this server for one.</span>
|
||||
</label>
|
||||
{/if}
|
||||
|
||||
|
||||
@@ -40,6 +40,7 @@ describe('/register page', () => {
|
||||
await fireEvent.input(screen.getByLabelText(/username/i), { target: { value: 'newuser' } });
|
||||
await fireEvent.input(screen.getByLabelText(/^password$/i), { target: { value: 'abcd1234' } });
|
||||
await fireEvent.input(screen.getByLabelText(/confirm password/i), { target: { value: 'differentpw' } });
|
||||
await fireEvent.input(screen.getByLabelText(/invite token/i), { target: { value: 'abc123' } });
|
||||
await fireEvent.click(screen.getByRole('button', { name: /create account/i }));
|
||||
expect(register).not.toHaveBeenCalled();
|
||||
expect(screen.getByRole('alert').textContent).toMatch(/do not match/i);
|
||||
@@ -71,6 +72,7 @@ describe('/register page', () => {
|
||||
await fireEvent.input(screen.getByLabelText(/username/i), { target: { value: 'newuser' } });
|
||||
await fireEvent.input(screen.getByLabelText(/^password$/i), { target: { value: 'abcd1234' } });
|
||||
await fireEvent.input(screen.getByLabelText(/confirm password/i), { target: { value: 'abcd1234' } });
|
||||
await fireEvent.input(screen.getByLabelText(/invite token/i), { target: { value: 'abc123' } });
|
||||
await fireEvent.click(screen.getByRole('button', { name: /create account/i }));
|
||||
await waitFor(() => {
|
||||
expect(screen.getByRole('alert').textContent).toMatch(/invite token is invalid/i);
|
||||
@@ -83,6 +85,7 @@ describe('/register page', () => {
|
||||
await fireEvent.input(screen.getByLabelText(/username/i), { target: { value: 'existinguser' } });
|
||||
await fireEvent.input(screen.getByLabelText(/^password$/i), { target: { value: 'abcd1234' } });
|
||||
await fireEvent.input(screen.getByLabelText(/confirm password/i), { target: { value: 'abcd1234' } });
|
||||
await fireEvent.input(screen.getByLabelText(/invite token/i), { target: { value: 'abc123' } });
|
||||
await fireEvent.click(screen.getByRole('button', { name: /create account/i }));
|
||||
await waitFor(() => {
|
||||
expect(screen.getByRole('alert').textContent).toMatch(/username is already taken/i);
|
||||
@@ -95,6 +98,7 @@ describe('/register page', () => {
|
||||
await fireEvent.input(screen.getByLabelText(/username/i), { target: { value: 'newuser' } });
|
||||
await fireEvent.input(screen.getByLabelText(/^password$/i), { target: { value: 'abcd1234' } });
|
||||
await fireEvent.input(screen.getByLabelText(/confirm password/i), { target: { value: 'abcd1234' } });
|
||||
await fireEvent.input(screen.getByLabelText(/invite token/i), { target: { value: 'abc123' } });
|
||||
await fireEvent.click(screen.getByRole('button', { name: /create account/i }));
|
||||
await waitFor(() => {
|
||||
expect(screen.getByRole('alert').textContent).toMatch(/invite token/i);
|
||||
@@ -110,6 +114,7 @@ describe('/register page', () => {
|
||||
await fireEvent.input(screen.getByLabelText(/username/i), { target: { value: 'newuser' } });
|
||||
await fireEvent.input(screen.getByLabelText(/^password$/i), { target: { value: 'abcd1234' } });
|
||||
await fireEvent.input(screen.getByLabelText(/confirm password/i), { target: { value: 'abcd1234' } });
|
||||
await fireEvent.input(screen.getByLabelText(/invite token/i), { target: { value: 'abc123' } });
|
||||
await fireEvent.click(screen.getByRole('button', { name: /create account/i }));
|
||||
const btn = screen.getByRole('button', { name: /creating account/i });
|
||||
expect(btn).toBeDisabled();
|
||||
|
||||
Reference in New Issue
Block a user