Make the admin a member with a flag, and drop the second listener

The admin was a set of env credentials on its own loopback listener. That
bought network isolation, and charged a second port to tunnel and proxy and
a second credential in the password manager. It also sat outside the
SameSite protection the member cookie already had, and left every ban and
password reset with no actor to log.

is_admin on users reuses what was already there: the session, the login
rate limiter, ban-drops-sessions, CSRF. /admin is now a route on the member
mux. A member without the flag gets 404 rather than 403 — the pages are
none of their business, and "forbidden" confirms there is something to be
forbidden from.

Registration needs an invite and invites come from /admin, so an empty
database cannot grow its first user. seedAdmin breaks that circle exactly
once, from ADMIN_EMAIL and ADMIN_PASSWORD, and does nothing against a
database that already has users.

An admin cannot ban themselves: banning drops the target's sessions, and
nothing would be left that could undo it.

This reverses decision 8, which is rewritten rather than deleted, along
with the admin entry in the CONTEXT.md vocabulary.
This commit is contained in:
Esa Kataja
2026-09-05 13:40:26 +03:00
parent 00ea7624ca
commit 2af29fe999
16 changed files with 321 additions and 186 deletions
+72 -50
View File
@@ -2,7 +2,6 @@ package main
import (
"context"
"crypto/subtle"
"database/sql"
"fmt"
"log/slog"
@@ -11,6 +10,7 @@ import (
"path/filepath"
"strings"
"golang.org/x/crypto/bcrypt"
_ "modernc.org/sqlite"
)
@@ -18,34 +18,31 @@ import (
var version = "dev"
type config struct {
dbPath string
adminUser string
dbPath string
// Only read when the database has no users at all: seedAdmin turns these into account number
// one. Once that account exists they are dead weight and can leave the environment.
adminEmail string
adminName string
adminPass string
addr string
adminAddr string
storageDir string
secureCookies bool
// Public address of the member site, so admin-side invite links are pasteable. The admin
// listener's own Host is a tunnel, not the site, so it cannot be derived.
// Public address of the site, so invite links are pasteable out of the admin page.
publicURL string
}
func loadConfig() config {
c := config{
adminUser: env("ADMIN_USER", "admin"),
adminEmail: os.Getenv("ADMIN_EMAIL"),
adminName: env("ADMIN_NAME", "Ylläpito"),
adminPass: os.Getenv("ADMIN_PASSWORD"),
addr: env("ADDR", ":8080"),
adminAddr: env("ADMIN_ADDR", "127.0.0.1:8081"),
storageDir: env("STORAGE_DIR", "./storage"),
secureCookies: env("SECURE_COOKIES", "true") != "false",
publicURL: strings.TrimRight(os.Getenv("PUBLIC_URL"), "/"),
}
// The database lives beside the audio, so one volume is the whole backup.
c.dbPath = env("DB_PATH", filepath.Join(c.storageDir, "levyraati.db"))
// An admin panel that silently opens is worse than one that won't boot.
if c.adminPass == "" {
fatal("ADMIN_PASSWORD is not set")
}
return c
}
@@ -122,22 +119,48 @@ func main() {
if err := sweep(ctx, db); err != nil {
fatal("startup sweep", "error", err)
}
if err := seedAdmin(ctx, db, cfg); err != nil {
fatal("seed admin", "error", err)
}
a := &app{cfg: cfg, db: db}
// ponytail: two listeners, one process. Admin is loopback-only — reach it over an SSH tunnel
// or the reverse proxy. A separate binary would need its own deploy and would race the
// startup migrations; it buys nothing else.
go func() {
slog.Info("admin listening", "ctx", "startup", "addr", cfg.adminAddr)
err := http.ListenAndServe(cfg.adminAddr, a.requireAdmin(a.adminMux()))
fatal("admin listener", "error", err)
}()
slog.Info("listening", "ctx", "startup", "addr", cfg.addr)
fatal("listener", "error", http.ListenAndServe(cfg.addr, a.withMember(a.memberMux())))
}
// Registration needs an invite and invites are minted from the admin page, so a database with no
// users has no way to grow one. seedAdmin breaks that circle exactly once: on an empty users table
// it creates account number one from the environment and marks it admin. Every account after it
// arrives through an invite like anyone else.
//
// ponytail: no promote-existing-user path and no password reset here. Re-running against a
// populated database does nothing, which is what makes it safe to leave in the boot sequence.
func seedAdmin(ctx context.Context, db *sql.DB, cfg config) error {
var users int
if err := db.QueryRowContext(ctx, `select count(*) from users`).Scan(&users); err != nil {
return err
}
if users > 0 {
return nil
}
if cfg.adminEmail == "" || cfg.adminPass == "" {
// A site nobody can log into is worse than one that won't boot.
fatal("empty database: set ADMIN_EMAIL and ADMIN_PASSWORD to create the first account")
}
hash, err := bcrypt.GenerateFromPassword([]byte(cfg.adminPass), bcrypt.DefaultCost)
if err != nil {
return err
}
if _, err := db.ExecContext(ctx,
`insert into users (name, email, password_hash, is_admin) values ($1, $2, $3, 1)`,
cfg.adminName, strings.ToLower(cfg.adminEmail), string(hash)); err != nil {
return err
}
slog.Info("first admin created", "ctx", "startup", "email", cfg.adminEmail)
return nil
}
func (a *app) memberMux() *http.ServeMux {
mux := http.NewServeMux()
mux.Handle("GET /static/", http.FileServerFS(assetFS))
@@ -187,41 +210,40 @@ func (a *app) memberMux() *http.ServeMux {
mux.HandleFunc("POST /submit/{id}/lyrics", a.requireMember(a.suggestLyrics))
mux.HandleFunc("POST /submit/{id}/retry", a.requireMember(a.retry))
mux.HandleFunc("POST /submit/{id}/discard", a.requireMember(a.discard))
a.adminRoutes(mux)
return mux
}
func (a *app) adminMux() *http.ServeMux {
mux := http.NewServeMux()
mux.Handle("GET /static/", http.FileServerFS(assetFS))
mux.HandleFunc("GET /admin", a.adminDashboard)
mux.HandleFunc("POST /admin/invites", a.createInvite)
mux.HandleFunc("POST /admin/users/{id}/ban", a.toggleBan)
mux.HandleFunc("POST /admin/users/{id}/password", a.resetPassword)
mux.HandleFunc("POST /admin/songs/{id}/delete", a.adminDeleteSong)
mux.HandleFunc("GET /admin/reports", a.adminReports)
mux.HandleFunc("POST /admin/reports/{id}/resolve", a.resolveReport)
mux.HandleFunc("GET /admin/audio/{id}", a.adminAudio)
mux.HandleFunc("GET /{$}", func(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, "/admin", http.StatusSeeOther)
})
return mux
// The admin pages sit on the same mux and the same session as everything else; only the guard
// differs. There is no /admin/audio: requireAdmin members can reach GET /audio/{id} like anyone.
func (a *app) adminRoutes(mux *http.ServeMux) {
mux.HandleFunc("GET /admin", a.requireAdmin(a.adminDashboard))
mux.HandleFunc("POST /admin/invites", a.requireAdmin(a.createInvite))
mux.HandleFunc("POST /admin/users/{id}/ban", a.requireAdmin(a.toggleBan))
mux.HandleFunc("POST /admin/users/{id}/password", a.requireAdmin(a.resetPassword))
mux.HandleFunc("POST /admin/songs/{id}/delete", a.requireAdmin(a.adminDeleteSong))
mux.HandleFunc("GET /admin/reports", a.requireAdmin(a.adminReports))
mux.HandleFunc("POST /admin/reports/{id}/resolve", a.requireAdmin(a.resolveReport))
}
// ponytail: Basic Auth, no admin session, no admin row. Ceiling: one admin, no logout
// (close the browser). Add a cookie session if a second admin ever needs one.
// ponytail: one flag, no roles. A moderator tier is a second column on the day someone needs to
// resolve reports without also being able to reset passwords.
//
// No bcrypt: hashing protects stored passwords against a database leak, and this one lives in the
// env file already. The constant-time compare is the part that matters.
func (a *app) requireAdmin(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
u, p, ok := r.BasicAuth()
userOK := subtle.ConstantTimeCompare([]byte(u), []byte(a.cfg.adminUser)) == 1
passOK := subtle.ConstantTimeCompare([]byte(p), []byte(a.cfg.adminPass)) == 1
if !ok || !userOK || !passOK {
w.Header().Set("WWW-Authenticate", `Basic realm="levyraati admin"`)
http.Error(w, "unauthorized", http.StatusUnauthorized)
// A signed-out visitor is sent to log in, the same as any member page. A signed-in member who is
// not an admin gets 404 rather than 403: the admin pages are none of their business, and saying
// "forbidden" confirms there is something there to be forbidden from.
func (a *app) requireAdmin(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
m := memberFrom(r.Context())
if m == nil {
http.Redirect(w, r, "/login", http.StatusSeeOther)
return
}
next.ServeHTTP(w, r)
})
if !m.IsAdmin {
http.NotFound(w, r)
return
}
next(w, r)
}
}