Files
minstrel/internal/auth/bootstrap.go
T
bvandeusen 4845628ae4 feat(db/m7-user-mgmt): migration 0022 + audit helper
Schema for user management U1: display_name on users; user_invites;
registration_settings singleton (default 'invite_only'); audit_log.
Plus the internal/audit package centralizing the action-name
vocabulary and JSON metadata marshaling so handlers don't repeat
boilerplate.

Race-safe first-admin uses a query-shape primitive
(CreateUserFirstAdminRace's WHERE NOT EXISTS subquery) rather than
a schema-level constraint. Concurrent empty-state registrations
both see 'no users yet' and both insert as admin — fine, having
two admins from the start is benign; what matters is at-least-one.
users.username uniqueness arbitrates if the two callers picked the
same username.

CreateUser signature gains display_name (nullable); existing
bootstrap call sites pass nil. The audit package declares the full
U1+U2+U3 action vocabulary upfront so subsequent slices are purely
additive on the caller side.

Tests cover audit Write with + without metadata and that every
declared action constant persists correctly.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-07 11:51:00 -04:00

101 lines
3.0 KiB
Go

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
}