package auth import ( "context" "database/sql" "log/slog" ) // EnsureAdminFromEnv creates the first administrator on an empty database. // // This runs only when no users exist, so it is idempotent across restarts and // cannot reset a password or add an admin to an established install. If the // database is empty and no credentials are configured, it logs a warning // rather than inventing a default password — a known-weak default on a // LAN-reachable service is exactly how these servers get compromised. func EnsureAdminFromEnv(ctx context.Context, db *sql.DB, log *slog.Logger, username, password string) error { n, err := CountUsers(ctx, db) if err != nil { return err } if n > 0 { return nil } if username == "" || password == "" { log.Warn("no user accounts exist and VELLUM_ADMIN_USER / VELLUM_ADMIN_PASSWORD are unset; " + "the API is reachable but nobody can log in. Set both and restart to create the first admin.") return nil } if len(password) < 8 { log.Warn("VELLUM_ADMIN_PASSWORD is shorter than 8 characters; refusing to create the admin account") return nil } u, err := CreateUser(ctx, db, username, "Administrator", password, true) if err != nil { return err } log.Info("created first administrator", "username", u.Username) return nil }