build: add makefile, dockerfile, ci and development stack

- build: add makefile, dockerfile, ci and development stack
- feat(config): add environment configuration and logger
- feat(server): add server lifecycle with health and version routes
- feat(db): add connection, contract check, migrations and stores
- feat(cli): add command dispatch and user management
- test(db): add integration tests against mysql
This commit is contained in:
bryanpedini committed 2026-11-19 15:46:12 +01:00
1 parent 45d1e307c6
commit 7089a6f408
46 files changed
+8456

No files matched your search

+693
View File
@@ -0,0 +1,693 @@
// 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"
"regexp"
"strconv"
"strings"
"text/tabwriter"
"time"
"unicode"
"unicode/utf8"
)
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 <username> <role> create a user with role admin or user, reading the password from stdin
coredns-web-ui user passwd <username> set the password of a user, reading it from stdin
coredns-web-ui user role <username> <role> set the role of a user to admin or user
coredns-web-ui user delete <username> 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
cliActor = "cli"
cliOrigin = "local"
defaultAuditRows = 20
maxAuditRows = 1000000
minPasswordBytes = 12
maxPasswordBytes = 256
maxPasswordLineBytes = 4096
cliTimeLayout = "2006-01-02T15:04:05Z"
)
var usernamePattern = regexp.MustCompile(`^[a-z0-9][a-z0-9._-]{0,63}$`)
var (
errNotImplemented = errors.New("not implemented")
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)
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 == cliActor {
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 role != "admin" && role != "user" {
return usageError("invalid role")
}
return nil
}
func validUsernameSyntax(username string) bool {
return usernamePattern.MatchString(username)
}
func checkPasswordRules(password string) error {
if len(password) < minPasswordBytes || len(password) > maxPasswordBytes {
return fmt.Errorf("password must be %d to %d bytes", minPasswordBytes, maxPasswordBytes)
}
if !utf8.ValidString(password) {
return errors.New("password must be valid UTF-8")
}
for _, r := range password {
if unicode.IsControl(r) {
return errors.New("password must not contain control characters")
}
}
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 := 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) (int, error) {
if s == "" || len(s) > 7 || strings.Trim(s, "0123456789") != "" {
return 0, errors.New("invalid count")
}
n, err := strconv.Atoi(s)
if err != nil || n < 1 || n > maxAuditRows {
return 0, errors.New("invalid count")
}
return n, nil
}
func (a *app) runCheck(ctx context.Context, db *sql.DB, t tableNames, log *slog.Logger, zone string) error {
return fmt.Errorf("check: %w", errNotImplemented)
}
func (a *app) runAudit(ctx context.Context, db *sql.DB, t tableNames, log *slog.Logger, n int) error {
return fmt.Errorf("audit: %w", errNotImplemented)
}
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 cliAuditEntry(now time.Time, operation string, target userRow, before, after *userRow) (auditEntry, error) {
e := auditEntry{
Time: now,
Actor: cliActor,
Origin: cliOrigin,
Operation: operation,
TargetUserID: sql.NullInt64{Int64: target.ID, Valid: true},
}
var err error
if before != nil {
if e.Before, err = auditUserJSON(*before); err != nil {
return auditEntry{}, err
}
}
if after != nil {
if e.After, err = auditUserJSON(*after); err != nil {
return auditEntry{}, err
}
}
return e, nil
}
func insertCLIAudit(ctx context.Context, tx cliUserTx, now time.Time, operation string, target userRow, before, after *userRow) error {
e, err := cliAuditEntry(now, operation, target, before, after)
if err != nil {
return fmt.Errorf("audit value: %w", err)
}
_, err = tx.InsertAudit(ctx, e)
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, "user_create", u, nil, &u)
})
if err != nil {
return err
}
logCLIChange(ctx, log, "user_create", 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, "user_password", u, &u, &u)
})
if err != nil {
return err
}
logCLIChange(ctx, log, "user_password", 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 u.Role == "admin" && len(admins) <= 1 {
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, "user_role", u, &u, &after)
})
if err != nil {
return err
}
if changed {
logCLIChange(ctx, log, "user_role", 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 u.Role == "admin" && len(admins) <= 1 {
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, "user_delete", u, &u, &after)
})
if err != nil {
return err
}
logCLIChange(ctx, log, "user_delete", username)
return nil
}