// SPDX-License-Identifier: GPL-2.0-or-later // Copyright (C) 2026 Bryan Joshua Pedini package main import ( "bufio" "context" "database/sql" "errors" "fmt" "io" "log/slog" "net" "net/http" "net/netip" "strconv" "strings" "text/tabwriter" "time" ) const usageText = `usage: coredns-web-ui start the HTTP server coredns-web-ui help print this usage text coredns-web-ui version print the version and commit coredns-web-ui healthcheck query the local /health endpoint coredns-web-ui user list [all] list the active users, or every user with all coredns-web-ui user add create a user with role admin or user, reading the password from stdin coredns-web-ui user passwd set the password of a user, reading it from stdin coredns-web-ui user role set the role of a user to admin or user coredns-web-ui user delete mark a user as deleted and end their sessions coredns-web-ui check [zone] report the rows the plugin cannot serve correctly coredns-web-ui audit [n] print the latest n audit rows (default 20) ` const ( healthcheckTimeout = 3 * time.Second defaultAuditRows = 20 maxPasswordLineBytes = 4096 cliTimeLayout = "2006-01-02T15:04:05Z" ) var ( errZoneHasNoRows = errors.New("the zone has no records") errNoActiveUser = errors.New("no active user has this username") errLastActiveAdmin = errors.New("the last active admin cannot be demoted or deleted") ) var userListHeader = []string{"USERNAME", "ROLE", "ZONES", "CREATED_AT", "LAST_LOGIN_AT", "DELETED_AT"} func usageError(msg string) error { return fmt.Errorf("%w: %s", errUsage, msg) } type cliCommand struct { name string prepare func() error run func(ctx context.Context, db *sql.DB, t tableNames, log *slog.Logger) error } func (a *app) execute(ctx context.Context, args []string) error { if len(args) == 0 { cfg, err := loadConfig(a.lookupEnv) if err != nil { return err } return a.runServer(ctx, cfg, newLogger(a.stderr, cfg.LogLevel)) } switch args[0] { case "help": if len(args) != 1 { return usageError("help takes no arguments") } return writeOutput(a.stdout, usageText) case "version": if len(args) != 1 { return usageError("version takes no arguments") } return writeOutput(a.stdout, versionLine()+"\n") case "healthcheck": if len(args) != 1 { return usageError("healthcheck takes no arguments") } cfg, err := loadHTTPConfig(a.lookupEnv) if err != nil { return err } return a.healthcheck(ctx, cfg) case "user", "check", "audit": return a.runDatabaseCommand(ctx, args) default: return usageError("unknown command") } } func writeOutput(w io.Writer, s string) error { if _, err := io.WriteString(w, s); err != nil { return fmt.Errorf("write output: %w", err) } return nil } func (a *app) runDatabaseCommand(ctx context.Context, args []string) (err error) { cfg, err := loadConfig(a.lookupEnv) if err != nil { return err } log := newLogger(a.stderr, cfg.LogLevel) ctx = withTraceLogger(ctx, log) defer traceFunc(ctx, log, "app.runDatabaseCommand")() var cmd cliCommand switch args[0] { case "user": cmd, err = a.parseUserCommand(args[1:]) case "check": cmd, err = a.parseCheckCommand(args[1:]) default: cmd, err = a.parseAuditCommand(args[1:]) } if err != nil { return err } log.DebugContext(ctx, "cli dispatch", "command", cmd.name) if cmd.prepare != nil { if err := cmd.prepare(); err != nil { return err } } db, t, err := a.prepareDB(ctx, cfg, log) if err != nil { return err } defer func() { if db == nil { return } if cerr := db.Close(); cerr != nil && err == nil { err = fmt.Errorf("close database: %w", cerr) } }() err = cmd.run(ctx, db, t, log) log.DebugContext(ctx, "cli command finished", "command", cmd.name, "ok", err == nil) return err } func (a *app) connectDatabase(ctx context.Context, cfg Config, log *slog.Logger) (*sql.DB, tableNames, error) { t, err := newTableNames(cfg.DBTablePrefix) if err != nil { return nil, tableNames{}, err } db, err := a.openDB(cfg, log) if err != nil { return nil, tableNames{}, err } if err := a.initDatabase(ctx, db, t, log); err != nil { _ = db.Close() return nil, tableNames{}, err } return db, t, nil } func (a *app) initDatabase(ctx context.Context, db *sql.DB, t tableNames, log *slog.Logger) error { if err := pingDatabase(ctx, db, a.pingBackoff, log); err != nil { return err } if err := verifyRecordsContract(ctx, db, t, log); err != nil { return err } return migrateDatabase(ctx, db, t, log) } func (a *app) parseUserCommand(args []string) (cliCommand, error) { if len(args) == 0 { return cliCommand{}, usageError("missing user subcommand") } switch args[0] { case "list": if len(args) > 2 { return cliCommand{}, usageError("user list takes at most one argument") } if len(args) == 2 && args[1] != "all" { return cliCommand{}, usageError("unknown user list argument") } all := len(args) == 2 return a.userCommand("user list", func(ctx context.Context, b cliUserBackend, log *slog.Logger) error { return a.userList(ctx, b, all) }), nil case "add": if len(args) != 3 { return cliCommand{}, usageError("user add requires a username and a role") } username, role := args[1], args[2] if err := checkUsernameArg(username); err != nil { return cliCommand{}, err } if username == reservedUsername { return cliCommand{}, usageError("reserved username") } if err := checkRoleArg(role); err != nil { return cliCommand{}, err } return a.passwordCommand("user add", func(ctx context.Context, b cliUserBackend, log *slog.Logger, hash string) error { return a.userAdd(ctx, b, log, username, role, hash) }), nil case "passwd": if len(args) != 2 { return cliCommand{}, usageError("user passwd requires a username") } username := args[1] if err := checkUsernameArg(username); err != nil { return cliCommand{}, err } return a.passwordCommand("user passwd", func(ctx context.Context, b cliUserBackend, log *slog.Logger, hash string) error { return a.userPasswd(ctx, b, log, username, hash) }), nil case "role": if len(args) != 3 { return cliCommand{}, usageError("user role requires a username and a role") } username, role := args[1], args[2] if err := checkUsernameArg(username); err != nil { return cliCommand{}, err } if err := checkRoleArg(role); err != nil { return cliCommand{}, err } return a.userCommand("user role", func(ctx context.Context, b cliUserBackend, log *slog.Logger) error { return a.userRole(ctx, b, log, username, role) }), nil case "delete": if len(args) != 2 { return cliCommand{}, usageError("user delete requires a username") } username := args[1] if err := checkUsernameArg(username); err != nil { return cliCommand{}, err } return a.userCommand("user delete", func(ctx context.Context, b cliUserBackend, log *slog.Logger) error { return a.userDelete(ctx, b, log, username) }), nil default: return cliCommand{}, usageError("unknown user subcommand") } } func (a *app) userCommand(name string, fn func(ctx context.Context, b cliUserBackend, log *slog.Logger) error) cliCommand { return cliCommand{name: name, run: func(ctx context.Context, db *sql.DB, t tableNames, log *slog.Logger) error { return fn(ctx, a.newUserBackend(db, t), log) }} } func (a *app) passwordCommand(name string, fn func(ctx context.Context, b cliUserBackend, log *slog.Logger, hash string) error) cliCommand { var hash string return cliCommand{ name: name, prepare: func() error { password, err := a.readPassword() if err != nil { return err } if err := checkPasswordRules(password); err != nil { return err } h, err := a.hashPassword(password) if err != nil { return fmt.Errorf("hash password: %w", err) } hash = h return nil }, run: func(ctx context.Context, db *sql.DB, t tableNames, log *slog.Logger) error { return fn(ctx, a.newUserBackend(db, t), log, hash) }, } } func checkUsernameArg(username string) error { if !validUsernameSyntax(username) { return usageError("invalid username") } return nil } func checkRoleArg(role string) error { if !validRole(role) { return usageError("invalid role") } return nil } func (a *app) readPassword() (string, error) { if a.stdinIsTerminal() { first, err := a.promptPassword("Password: ") if err != nil { return "", err } second, err := a.promptPassword("Repeat password: ") if err != nil { return "", err } if first != second { return "", errors.New("passwords do not match") } return first, nil } r := bufio.NewReader(io.LimitReader(a.stdin, maxPasswordLineBytes+1)) line, err := r.ReadString('\n') if err != nil && !errors.Is(err, io.EOF) { return "", fmt.Errorf("read password: %w", err) } if errors.Is(err, io.EOF) && line == "" { return "", errors.New("no password on stdin") } line = strings.TrimSuffix(line, "\n") line = strings.TrimSuffix(line, "\r") return line, nil } func (a *app) promptPassword(prompt string) (string, error) { if _, err := io.WriteString(a.stderr, prompt); err != nil { return "", fmt.Errorf("write prompt: %w", err) } b, err := a.readTerminalPassword() _, _ = io.WriteString(a.stderr, "\n") if err != nil { return "", fmt.Errorf("read password: %w", err) } return string(b), nil } func (a *app) parseCheckCommand(args []string) (cliCommand, error) { if len(args) > 1 { return cliCommand{}, usageError("check takes at most one zone") } zone := "" if len(args) == 1 { z, err := a.normalizeZone(args[0]) if err != nil { return cliCommand{}, usageError("invalid zone") } zone = z } return cliCommand{name: "check", run: func(ctx context.Context, db *sql.DB, t tableNames, log *slog.Logger) error { return a.runCheck(ctx, db, t, log, zone) }}, nil } func (a *app) parseAuditCommand(args []string) (cliCommand, error) { if len(args) > 1 { return cliCommand{}, usageError("audit takes at most one count") } n := int64(defaultAuditRows) if len(args) == 1 { v, err := parseAuditCount(args[0]) if err != nil { return cliCommand{}, usageError("invalid audit count") } n = v } return cliCommand{name: "audit", run: func(ctx context.Context, db *sql.DB, t tableNames, log *slog.Logger) error { return a.runAudit(ctx, db, t, log, n) }}, nil } func parseAuditCount(s string) (int64, error) { if s == "" || strings.Trim(s, "0123456789") != "" { return 0, errors.New("invalid count") } n, err := strconv.ParseInt(s, 10, 64) if err != nil || n < 1 { return 0, errors.New("invalid count") } return n, nil } type cliReadBackend interface { ListZones(ctx context.Context) ([]zoneSummary, error) ZoneRows(ctx context.Context, zone string) ([]recordRow, error) LatestAudit(ctx context.Context, n int64) ([]auditRow, error) } type sqlReadBackend struct { recordStore auditStore } func newSQLReadBackend(db *sql.DB, t tableNames) cliReadBackend { return sqlReadBackend{recordStore: newRecordStore(db, t), auditStore: newAuditStore(db, t)} } var checkHeader = []string{"ZONE", "NAME", "TYPE", "ID", "SEVERITY", "PROBLEM"} var auditHeader = []string{"TIME", "ACTOR", "ORIGIN", "OPERATION", "STATUS", "ZONE", "RECORD", "TARGET_USER"} func cliText(s string) string { s = strings.TrimSpace(printableText(s, -1)) if s == "" { return "-" } return s } func checkRows(zone string, problems []zoneProblem) [][]string { rows := make([][]string, 0, len(problems)) for _, p := range problems { name, recordType, id := "-", "-", "-" if p.RecordID != 0 { name, recordType, id = p.Name, cliText(p.Type), strconv.FormatInt(p.RecordID, 10) if name == "" { name = "@" } name = cliText(name) } rows = append(rows, []string{cliText(zone), name, recordType, id, p.Severity, cliText(p.Code + ": " + p.Message)}) } return rows } func (a *app) runCheck(ctx context.Context, db *sql.DB, t tableNames, log *slog.Logger, zone string) error { return a.checkZones(ctx, a.newReadBackend(db, t), zone) } func (a *app) checkZones(ctx context.Context, b cliReadBackend, zone string) error { zones := []string{zone} if zone == "" { summaries, err := b.ListZones(ctx) if err != nil { return err } zones = zones[:0] for _, z := range summaries { zones = append(zones, z.Zone) } } now := a.now() var table [][]string for _, z := range zones { rows, err := b.ZoneRows(ctx, z) if err != nil { return err } if len(rows) == 0 { return errZoneHasNoRows } table = append(table, checkRows(z, checkZone(z, rows, now))...) } if err := writeTable(a.stdout, checkHeader, table); err != nil { return err } if len(table) > 0 { return errCheckProblems } return nil } func (a *app) runAudit(ctx context.Context, db *sql.DB, t tableNames, log *slog.Logger, n int64) error { return a.printAudit(ctx, a.newReadBackend(db, t), n) } func cliNullInt(v sql.NullInt64) string { if !v.Valid { return "-" } return strconv.FormatInt(v.Int64, 10) } func cliNullText(v sql.NullString) string { if !v.Valid { return "-" } return cliText(v.String) } func auditRows(entries []auditRow) [][]string { rows := make([][]string, 0, len(entries)) for _, e := range entries { rows = append(rows, []string{ formatCLITime(e.Time), cliText(e.Actor), cliText(e.Origin), cliText(e.Operation), cliNullInt(e.Status), cliNullText(e.Zone), cliNullInt(e.RecordID), cliNullText(e.TargetUsername), }) } return rows } func (a *app) printAudit(ctx context.Context, b cliReadBackend, n int64) error { entries, err := b.LatestAudit(ctx, n) if err != nil { return err } return writeTable(a.stdout, auditHeader, auditRows(entries)) } func newHealthClient() *http.Client { return &http.Client{ Timeout: healthcheckTimeout, Transport: &http.Transport{Proxy: nil, DisableKeepAlives: true}, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }, } } func healthcheckURL(cfg Config) string { host := cfg.HTTPAddr if addr, err := netip.ParseAddr(host); err != nil || addr.IsUnspecified() { host = "127.0.0.1" } return "http://" + net.JoinHostPort(host, strconv.Itoa(cfg.HTTPPort)) + "/health" } func (a *app) healthcheck(ctx context.Context, cfg Config) error { ctx, cancel := context.WithTimeout(ctx, healthcheckTimeout) defer cancel() req, err := http.NewRequestWithContext(ctx, http.MethodGet, healthcheckURL(cfg), nil) if err != nil { return fmt.Errorf("health check failed: %w", err) } resp, err := a.healthClient.Do(req) if err != nil { return fmt.Errorf("health check failed: %w", err) } defer resp.Body.Close() _, _ = io.Copy(io.Discard, io.LimitReader(resp.Body, 4096)) if resp.StatusCode != http.StatusOK { return fmt.Errorf("health check failed: status %d", resp.StatusCode) } return nil } func writeTable(out io.Writer, header []string, rows [][]string) error { w := bufio.NewWriter(out) tw := tabwriter.NewWriter(w, 0, 0, 2, ' ', 0) fmt.Fprintln(tw, strings.Join(header, "\t")) for _, row := range rows { fmt.Fprintln(tw, strings.Join(row, "\t")) } err := tw.Flush() if ferr := w.Flush(); err == nil { err = ferr } if err != nil { return fmt.Errorf("write output: %w", err) } return nil } func formatCLITime(t time.Time) string { return t.UTC().Format(cliTimeLayout) } func formatCLINullTime(t sql.NullTime) string { if !t.Valid { return "-" } return formatCLITime(t.Time) } func userListRows(users []userSummary) [][]string { rows := make([][]string, 0, len(users)) for _, u := range users { rows = append(rows, []string{ u.Username, u.Role, strconv.FormatInt(u.Zones, 10), formatCLITime(u.CreatedAt), formatCLINullTime(u.LastLoginAt), formatCLINullTime(u.DeletedAt), }) } return rows } type cliUserBackend interface { ListUsers(ctx context.Context, includeDeleted bool) ([]userSummary, error) InTx(ctx context.Context, fn func(tx cliUserTx) error) error } type cliUserTx interface { CreateUser(ctx context.Context, username, role, passwordHash string, now time.Time) (userRow, error) UserByUsernameForUpdate(ctx context.Context, username string) (userRow, error) LockActiveAdmins(ctx context.Context) ([]userRow, error) SetPassword(ctx context.Context, id int64, passwordHash string, now time.Time) error SetRole(ctx context.Context, id int64, role string, now time.Time) error MarkDeleted(ctx context.Context, id int64, now time.Time) error DeleteUserSessions(ctx context.Context, userID int64) (int64, error) InsertAudit(ctx context.Context, e auditEntry) (int64, error) } type sqlUserBackend struct { db *sql.DB t tableNames } type sqlUserTx struct { userStore sessionStore auditStore } func newSQLUserBackend(db *sql.DB, t tableNames) cliUserBackend { return sqlUserBackend{db: db, t: t} } func (b sqlUserBackend) ListUsers(ctx context.Context, includeDeleted bool) ([]userSummary, error) { return newUserStore(b.db, b.t).ListUsers(ctx, includeDeleted) } func (b sqlUserBackend) InTx(ctx context.Context, fn func(tx cliUserTx) error) error { return runInTx(ctx, b.db, func(tx *sql.Tx) error { return fn(sqlUserTx{ userStore: newUserStore(tx, b.t), sessionStore: newSessionStore(tx, b.t), auditStore: newAuditStore(tx, b.t), }) }) } func (a *app) userList(ctx context.Context, b cliUserBackend, all bool) error { users, err := b.ListUsers(ctx, all) if err != nil { return err } return writeTable(a.stdout, userListHeader, userListRows(users)) } func insertCLIAudit(ctx context.Context, tx cliUserTx, now time.Time, operation string, target userRow, before, after *userRow) error { _, err := tx.InsertAudit(ctx, cliAuditEntry(now, operation, target, before, after)) return err } func activeUserForUpdate(ctx context.Context, tx cliUserTx, username string) (userRow, error) { u, err := tx.UserByUsernameForUpdate(ctx, username) if errors.Is(err, errRowNotFound) || (err == nil && u.DeletedAt.Valid) { return userRow{}, errNoActiveUser } return u, err } func logCLIChange(ctx context.Context, log *slog.Logger, operation, username string) { log.InfoContext(ctx, "change committed", "operation", operation, "target_user", username, "actor", cliActor) } func (a *app) userAdd(ctx context.Context, b cliUserBackend, log *slog.Logger, username, role, hash string) error { now := dbTime(a.now()) err := b.InTx(ctx, func(tx cliUserTx) error { u, err := tx.CreateUser(ctx, username, role, hash, now) if err != nil { return err } return insertCLIAudit(ctx, tx, now, opUserCreate, u, nil, &u) }) if err != nil { return err } logCLIChange(ctx, log, opUserCreate, username) return nil } func (a *app) userPasswd(ctx context.Context, b cliUserBackend, log *slog.Logger, username, hash string) error { now := dbTime(a.now()) err := b.InTx(ctx, func(tx cliUserTx) error { u, err := activeUserForUpdate(ctx, tx, username) if err != nil { return err } if err := tx.SetPassword(ctx, u.ID, hash, now); err != nil { return err } if _, err := tx.DeleteUserSessions(ctx, u.ID); err != nil { return err } return insertCLIAudit(ctx, tx, now, opUserPassword, u, &u, &u) }) if err != nil { return err } logCLIChange(ctx, log, opUserPassword, username) return nil } func (a *app) userRole(ctx context.Context, b cliUserBackend, log *slog.Logger, username, role string) error { now := dbTime(a.now()) changed := false err := b.InTx(ctx, func(tx cliUserTx) error { admins, err := tx.LockActiveAdmins(ctx) if err != nil { return err } u, err := activeUserForUpdate(ctx, tx, username) if err != nil { return err } if u.Role == role { return nil } if leavesNoActiveAdmin(u, admins) { return errLastActiveAdmin } if err := tx.SetRole(ctx, u.ID, role, now); err != nil { return err } after := u after.Role = role after.UpdatedAt = now changed = true return insertCLIAudit(ctx, tx, now, opUserRole, u, &u, &after) }) if err != nil { return err } if changed { logCLIChange(ctx, log, opUserRole, username) } return nil } func (a *app) userDelete(ctx context.Context, b cliUserBackend, log *slog.Logger, username string) error { now := dbTime(a.now()) err := b.InTx(ctx, func(tx cliUserTx) error { admins, err := tx.LockActiveAdmins(ctx) if err != nil { return err } u, err := activeUserForUpdate(ctx, tx, username) if err != nil { return err } if leavesNoActiveAdmin(u, admins) { return errLastActiveAdmin } if err := tx.MarkDeleted(ctx, u.ID, now); err != nil { return err } if _, err := tx.DeleteUserSessions(ctx, u.ID); err != nil { return err } after := u after.DeletedAt = sql.NullTime{Time: now, Valid: true} after.UpdatedAt = now return insertCLIAudit(ctx, tx, now, opUserDelete, u, &u, &after) }) if err != nil { return err } logCLIChange(ctx, log, opUserDelete, username) return nil }