refactor(server): remove bootstrap admin path

The bootstrap-admin-from-env-vars flow was a holdover from before
self-registration could create the first admin. Now that handleRegister
+ CreateUserFirstAdminRace promotes the first user to register on an
empty users table (verified shipped in v2026.05.08.2 / #376), the
bootstrap path is just a second source of truth that confuses operators
(and leaves an "admin" account in the DB that nobody asked for).

Removes:
- internal/auth/bootstrap.go + its test
- The auth.Bootstrap call from cmd/minstrel/main.go
- AuthConfig + AdminBootstrapConfig structs from config
- MINSTREL_AUTH_ADMIN_USERNAME / _PASSWORD env reads + their test
- The auth: block from config.example.yaml
- Bootstrap-related comments in docker-compose.yml + README.md

The README quickstart now points operators at /register on first start
instead of "watch the logs for a one-time password."

Existing instances keep their bootstrap-admin row in the DB; operators
who want it gone can register a new admin via /register, promote them
in /admin/users, then delete the old bootstrap user (last-admin guard
will require the new admin to be promoted first). No migration needed.

Recovery story for forgotten admin passwords now hinges on Fable #321
(admin password reset CLI) — currently the only path back in if no
other admin exists.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-05-08 22:14:33 -04:00
parent d5c8d316c5
commit c4cccea775
8 changed files with 1 additions and 303 deletions
-100
View File
@@ -1,100 +0,0 @@
package auth
import (
"context"
"crypto/rand"
"encoding/base64"
"fmt"
"log/slog"
"os"
"github.com/jackc/pgx/v5/pgxpool"
"golang.org/x/crypto/bcrypt"
"git.fabledsword.com/bvandeusen/minstrel/internal/config"
"git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq"
)
// Bootstrap creates the initial admin user when the users table is empty AND
// the config supplies a bootstrap username. A blank password means "generate a
// random one and print it once on stderr" — suitable for first-run setups
// where the operator is watching the logs.
func Bootstrap(ctx context.Context, pool *pgxpool.Pool, cfg config.AdminBootstrapConfig, logger *slog.Logger) error {
if cfg.Username == "" {
return nil
}
q := dbq.New(pool)
count, err := q.CountUsers(ctx)
if err != nil {
return fmt.Errorf("auth: count users: %w", err)
}
if count > 0 {
return nil
}
password := cfg.Password
passwordGenerated := false
if password == "" {
p, err := randomToken(18)
if err != nil {
return fmt.Errorf("auth: generate password: %w", err)
}
password = p
passwordGenerated = true
}
hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
if err != nil {
return fmt.Errorf("auth: hash password: %w", err)
}
apiToken, err := randomToken(32)
if err != nil {
return fmt.Errorf("auth: generate api token: %w", err)
}
user, err := q.CreateUser(ctx, dbq.CreateUserParams{
Username: cfg.Username,
PasswordHash: string(hash),
ApiToken: apiToken,
IsAdmin: true,
DisplayName: nil,
})
if err != nil {
return fmt.Errorf("auth: insert admin: %w", err)
}
// Mirror the bootstrap password into subsonic_password so Subsonic clients
// (Feishin, Symfonium, …) can authenticate via t+s without the operator
// having to run a separate SQL update after first boot. This is plaintext
// at rest — the cost of Subsonic's legacy auth — and matches what servers
// like Navidrome do. Operators who don't want a plaintext copy can clear
// it later with SetSubsonicPassword(nil).
subPass := password
if err := q.SetSubsonicPassword(ctx, dbq.SetSubsonicPasswordParams{
ID: user.ID,
SubsonicPassword: &subPass,
}); err != nil {
return fmt.Errorf("auth: set subsonic password: %w", err)
}
logger.Info("admin bootstrapped", "username", cfg.Username, "user_id", user.ID.String())
if passwordGenerated {
fmt.Fprintf(os.Stderr, "\n--- minstrel admin bootstrap (shown once) ---\nusername: %s\npassword: %s\napi_token: %s\n(password works for both the native UI and Subsonic clients)\n---\n\n",
cfg.Username, password, apiToken)
} else {
fmt.Fprintf(os.Stderr, "\n--- minstrel admin api token (shown once) ---\nusername: %s\napi_token: %s\n(your configured password now also works for Subsonic clients)\n---\n\n",
cfg.Username, apiToken)
}
return nil
}
// randomToken returns a URL-safe base64 string backed by n random bytes.
func randomToken(n int) (string, error) {
b := make([]byte, n)
if _, err := rand.Read(b); err != nil {
return "", err
}
return base64.RawURLEncoding.EncodeToString(b), nil
}
-143
View File
@@ -1,143 +0,0 @@
package auth
import (
"context"
"io"
"log/slog"
"os"
"testing"
"github.com/jackc/pgx/v5/pgxpool"
"golang.org/x/crypto/bcrypt"
"git.fabledsword.com/bvandeusen/minstrel/internal/config"
"git.fabledsword.com/bvandeusen/minstrel/internal/db"
"git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq"
)
// TestBootstrap_Integration exercises the admin-bootstrap flow against a real
// Postgres. Gated on MINSTREL_TEST_DATABASE_URL, skipped in -short mode.
func TestBootstrap_Integration(t *testing.T) {
if testing.Short() {
t.Skip("skipping bootstrap integration in -short mode")
}
dsn := os.Getenv("MINSTREL_TEST_DATABASE_URL")
if dsn == "" {
t.Skip("MINSTREL_TEST_DATABASE_URL not set; skipping")
}
ctx := context.Background()
logger := slog.New(slog.NewTextHandler(io.Discard, nil))
if err := db.Migrate(dsn, logger); err != nil {
t.Fatalf("Migrate: %v", err)
}
pool, err := pgxpool.New(ctx, dsn)
if err != nil {
t.Fatalf("pool: %v", err)
}
t.Cleanup(pool.Close)
// Bootstrap requires an empty users table to test the first-run path.
// When the test DB is shared with the operator's dev environment, the
// TRUNCATE wipes their real admin login. Save any non-test users now and
// reinsert them after the test finishes so the operator can log back in.
type savedUser struct {
username, passwordHash, apiToken string
isAdmin, listenbrainzEnabled bool
subsonicPassword, listenbrainzToken *string
}
var saved []savedUser
rows, err := pool.Query(ctx, `
SELECT username, password_hash, api_token, is_admin,
subsonic_password, listenbrainz_token, listenbrainz_enabled
FROM users
WHERE username NOT LIKE 'test-%'`)
if err != nil {
t.Fatalf("save users: %v", err)
}
for rows.Next() {
var s savedUser
if err := rows.Scan(&s.username, &s.passwordHash, &s.apiToken, &s.isAdmin,
&s.subsonicPassword, &s.listenbrainzToken, &s.listenbrainzEnabled); err != nil {
rows.Close()
t.Fatalf("scan: %v", err)
}
saved = append(saved, s)
}
rows.Close()
t.Cleanup(func() {
// Remove anything the test created, then restore non-test users.
if _, err := pool.Exec(context.Background(), "TRUNCATE users RESTART IDENTITY CASCADE"); err != nil {
t.Logf("cleanup truncate: %v", err)
return
}
for _, s := range saved {
if _, err := pool.Exec(context.Background(), `
INSERT INTO users (username, password_hash, api_token, is_admin,
subsonic_password, listenbrainz_token, listenbrainz_enabled)
VALUES ($1, $2, $3, $4, $5, $6, $7)`,
s.username, s.passwordHash, s.apiToken, s.isAdmin,
s.subsonicPassword, s.listenbrainzToken, s.listenbrainzEnabled); err != nil {
t.Logf("restore %q: %v", s.username, err)
}
}
})
if _, err := pool.Exec(ctx, "TRUNCATE users RESTART IDENTITY CASCADE"); err != nil {
t.Fatalf("truncate: %v", err)
}
const testAdmin = "test-admin"
cfg := config.AdminBootstrapConfig{Username: testAdmin, Password: "hunter2"}
if err := Bootstrap(ctx, pool, cfg, logger); err != nil {
t.Fatalf("Bootstrap: %v", err)
}
q := dbq.New(pool)
user, err := q.GetUserByUsername(ctx, testAdmin)
if err != nil {
t.Fatalf("GetUserByUsername: %v", err)
}
if !user.IsAdmin {
t.Error("bootstrapped user not marked admin")
}
if user.ApiToken == "" {
t.Error("api_token empty")
}
if err := bcrypt.CompareHashAndPassword([]byte(user.PasswordHash), []byte("hunter2")); err != nil {
t.Errorf("bcrypt compare: %v", err)
}
if user.SubsonicPassword == nil || *user.SubsonicPassword != "hunter2" {
t.Errorf("subsonic_password = %v, want \"hunter2\"", user.SubsonicPassword)
}
byToken, err := q.GetUserByAPIToken(ctx, user.ApiToken)
if err != nil {
t.Fatalf("GetUserByAPIToken: %v", err)
}
if byToken.Username != testAdmin {
t.Errorf("token lookup returned %q", byToken.Username)
}
// Second call must be a no-op because users table is non-empty.
if err := Bootstrap(ctx, pool, cfg, logger); err != nil {
t.Fatalf("Bootstrap (second call): %v", err)
}
count, err := q.CountUsers(ctx)
if err != nil {
t.Fatalf("CountUsers: %v", err)
}
if count != 1 {
t.Errorf("expected exactly 1 user after idempotent bootstrap, got %d", count)
}
}
// TestBootstrap_NoUsernameSkips verifies the no-config path without needing
// a database connection.
func TestBootstrap_NoUsernameSkips(t *testing.T) {
err := Bootstrap(context.Background(), nil, config.AdminBootstrapConfig{}, slog.New(slog.NewTextHandler(io.Discard, nil)))
if err != nil {
t.Errorf("empty config should return nil, got %v", err)
}
}