Files
coredns-web-ui/cli_test.go
T
bryanpedini a7ba01fc77 refactor(api): use audit operation constants and the shared zone not found error in zone handlers
- refactor(api): use audit operation constants and the shared zone not found error in zone handlers
- fix(api): return the stored content of rows with check errors
- fix(api): return warnings from record deletes, zone creation and import apply
- fix(api): allow repairing rows stored with a non canonical zone and invalid SOA sets
- fix(check): accept JSON column formatting and an absent SOA serial as canonical content
- fix(ui): match audit diff items by identity instead of array index
- fix(ui): count the SOA change once, report import warnings and check the request size
- fix(ui): edit the selected SOA row, keep the server order, show error rows raw and report write warnings
- test(check): cover triggering and clean pairs with exact codes and record ids
- test(records): cover SRV port, SOA timer and CAA value boundaries
- test(cli): check the exact check output and the exit code of warning-only zones
- refactor(import): order current rows with cmp.Compare
- test(check): cover malformed stored content and a mailbox stored as an address
- test(api): cover zone write failure paths, ambiguous SOA updates and unchanged record detection
2026-11-19 15:46:12 +01:00

1043 lines
38 KiB
Go

// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright (C) 2026 Bryan Joshua Pedini
package main
import (
"bytes"
"context"
"database/sql"
"database/sql/driver"
"encoding/json"
"errors"
"log/slog"
"net"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"testing"
"time"
)
const specUsageText = "usage:\n" +
" coredns-web-ui start the HTTP server\n" +
" coredns-web-ui help print this usage text\n" +
" coredns-web-ui version print the version and commit\n" +
" coredns-web-ui healthcheck query the local /health endpoint\n" +
" coredns-web-ui user list [all] list the active users, or every user with all\n" +
" coredns-web-ui user add <username> <role> create a user with role admin or user, reading the password from stdin\n" +
" coredns-web-ui user passwd <username> set the password of a user, reading it from stdin\n" +
" coredns-web-ui user role <username> <role> set the role of a user to admin or user\n" +
" coredns-web-ui user delete <username> mark a user as deleted and end their sessions\n" +
" coredns-web-ui check [zone] report the rows the plugin cannot serve correctly\n" +
" coredns-web-ui audit [n] print the latest n audit rows (default 20)\n"
var cliNow = time.Date(2026, 11, 18, 12, 0, 0, 0, time.UTC)
type fakeUsers struct {
users []userRow
zones map[int64]int64
sessions map[int64]int64
audit []auditEntry
nextID int64
failOn string
listCalls int
}
func (f *fakeUsers) clone() *fakeUsers {
c := *f
c.users = append([]userRow(nil), f.users...)
c.audit = append([]auditEntry(nil), f.audit...)
c.sessions = map[int64]int64{}
for k, v := range f.sessions {
c.sessions[k] = v
}
return &c
}
func (f *fakeUsers) fail(op string) error {
if f.failOn == op {
return errors.New(op + " failed")
}
return nil
}
func (f *fakeUsers) ListUsers(ctx context.Context, all bool) ([]userSummary, error) {
f.listCalls++
if err := f.fail("ListUsers"); err != nil {
return nil, err
}
var out []userSummary
for _, u := range f.users {
if all || !u.DeletedAt.Valid {
out = append(out, userSummary{userRow: u, Zones: f.zones[u.ID]})
}
}
return out, nil
}
func (f *fakeUsers) InTx(ctx context.Context, fn func(tx cliUserTx) error) error {
work := f.clone()
if err := fn(work); err != nil {
return err
}
if err := f.fail("Commit"); err != nil {
return err
}
*f = *work
return nil
}
func (f *fakeUsers) CreateUser(ctx context.Context, username, role, hash string, now time.Time) (userRow, error) {
if err := f.fail("CreateUser"); err != nil {
return userRow{}, err
}
for _, u := range f.users {
if u.Username == username {
return userRow{}, errUsernameTaken
}
}
f.nextID++
u := userRow{ID: f.nextID, Username: username, Role: role, PasswordHash: hash, CreatedAt: now, UpdatedAt: now}
f.users = append(f.users, u)
return u, nil
}
func (f *fakeUsers) find(id int64) *userRow {
for i := range f.users {
if f.users[i].ID == id {
return &f.users[i]
}
}
return nil
}
func (f *fakeUsers) UserByUsernameForUpdate(ctx context.Context, username string) (userRow, error) {
if err := f.fail("UserByUsernameForUpdate"); err != nil {
return userRow{}, err
}
for _, u := range f.users {
if u.Username == username {
return u, nil
}
}
return userRow{}, errRowNotFound
}
func (f *fakeUsers) LockActiveAdmins(ctx context.Context) ([]userRow, error) {
if err := f.fail("LockActiveAdmins"); err != nil {
return nil, err
}
var out []userRow
for _, u := range f.users {
if u.Role == "admin" && !u.DeletedAt.Valid {
out = append(out, u)
}
}
return out, nil
}
func (f *fakeUsers) SetPassword(ctx context.Context, id int64, hash string, now time.Time) error {
if err := f.fail("SetPassword"); err != nil {
return err
}
u := f.find(id)
u.PasswordHash, u.UpdatedAt = hash, now
return nil
}
func (f *fakeUsers) SetRole(ctx context.Context, id int64, role string, now time.Time) error {
if err := f.fail("SetRole"); err != nil {
return err
}
u := f.find(id)
u.Role, u.UpdatedAt = role, now
return nil
}
func (f *fakeUsers) MarkDeleted(ctx context.Context, id int64, now time.Time) error {
if err := f.fail("MarkDeleted"); err != nil {
return err
}
u := f.find(id)
u.DeletedAt, u.UpdatedAt = sql.NullTime{Time: now, Valid: true}, now
return nil
}
func (f *fakeUsers) DeleteUserSessions(ctx context.Context, userID int64) (int64, error) {
if err := f.fail("DeleteUserSessions"); err != nil {
return 0, err
}
n := f.sessions[userID]
delete(f.sessions, userID)
return n, nil
}
func (f *fakeUsers) InsertAudit(ctx context.Context, e auditEntry) (int64, error) {
if err := f.fail("InsertAudit"); err != nil {
return 0, err
}
e.ID = int64(len(f.audit) + 1)
f.audit = append(f.audit, e)
return e.ID, nil
}
type cliHarness struct {
a *app
stdout bytes.Buffer
stderr bytes.Buffer
env map[string]string
users *fakeUsers
prepared int
hashed []string
prepErr error
}
func newCLIHarness(t *testing.T, stdin string) *cliHarness {
h := &cliHarness{
env: map[string]string{
"DB_HOST": "db", "DB_USER": "u", "DB_PASSWORD": "dbpass-secret", "DB_NAME": "coredns", "LOG_LEVEL": "error",
},
users: &fakeUsers{zones: map[int64]int64{}, sessions: map[int64]int64{}},
}
h.a = &app{
lookupEnv: func(k string) (string, bool) { v, ok := h.env[k]; return v, ok },
stdin: strings.NewReader(stdin),
stdout: &h.stdout,
stderr: &h.stderr,
stdinIsTerminal: func() bool { return false },
readTerminalPassword: func() ([]byte, error) { t.Fatal("terminal read"); return nil, nil },
now: func() time.Time { return cliNow },
hashPassword: func(p string) (string, error) {
h.hashed = append(h.hashed, p)
return "$hash$" + p, nil
},
normalizeZone: normalizeZone,
prepareDB: func(ctx context.Context, cfg Config, log *slog.Logger) (*sql.DB, tableNames, error) {
h.prepared++
return nil, tableNames{}, h.prepErr
},
newUserBackend: func(*sql.DB, tableNames) cliUserBackend { return h.users },
healthClient: newHealthClient(),
}
return h
}
func (h *cliHarness) run(args ...string) int {
return run(args, h.a)
}
func (h *cliHarness) addUser(username, role string, deleted bool) userRow {
h.users.nextID++
u := userRow{ID: h.users.nextID, Username: username, Role: role, PasswordHash: "$old", CreatedAt: cliNow.Add(-time.Hour), UpdatedAt: cliNow.Add(-time.Hour)}
if deleted {
u.DeletedAt = sql.NullTime{Time: cliNow.Add(-time.Minute), Valid: true}
}
h.users.users = append(h.users.users, u)
return u
}
func TestUsageTextMatchesSpec(t *testing.T) {
if usageText != specUsageText {
t.Fatalf("usage text differs:\n%s", usageText)
}
}
func TestHelpAndVersion(t *testing.T) {
h := newCLIHarness(t, "")
h.env = map[string]string{}
if code := h.run("help"); code != 0 || h.stdout.String() != specUsageText || h.stderr.Len() != 0 {
t.Fatalf("help: %d %q %q", code, h.stdout.String(), h.stderr.String())
}
h = newCLIHarness(t, "")
h.env = map[string]string{}
if code := h.run("version"); code != 0 || h.stdout.String() != "coredns-web-ui latest undefined\n" || h.stderr.Len() != 0 {
t.Fatalf("version: %d %q %q", code, h.stdout.String(), h.stderr.String())
}
old, oldCommit := APP_VERSION, COMMIT_ID
APP_VERSION, COMMIT_ID = "1.2.3", "abcdef123456"
defer func() { APP_VERSION, COMMIT_ID = old, oldCommit }()
h = newCLIHarness(t, "")
if code := h.run("version"); code != 0 || h.stdout.String() != "coredns-web-ui 1.2.3 abcdef123456\n" {
t.Fatalf("version: %d %q", code, h.stdout.String())
}
}
func TestUsageErrors(t *testing.T) {
cases := []struct {
args []string
msg string
}{
{[]string{"secretarg"}, "unknown command"},
{[]string{"help", "secretarg"}, "help takes no arguments"},
{[]string{"version", "secretarg"}, "version takes no arguments"},
{[]string{"healthcheck", "secretarg"}, "healthcheck takes no arguments"},
{[]string{"user"}, "missing user subcommand"},
{[]string{"user", "secretarg"}, "unknown user subcommand"},
{[]string{"user", "list", "secretarg"}, "unknown user list argument"},
{[]string{"user", "list", "ALL"}, "unknown user list argument"},
{[]string{"user", "list", "all", "secretarg"}, "user list takes at most one argument"},
{[]string{"user", "add"}, "user add requires a username and a role"},
{[]string{"user", "add", "alice"}, "user add requires a username and a role"},
{[]string{"user", "add", "alice", "admin", "secretarg"}, "user add requires a username and a role"},
{[]string{"user", "add", "Secretarg", "admin"}, "invalid username"},
{[]string{"user", "add", ".secretarg", "admin"}, "invalid username"},
{[]string{"user", "add", strings.Repeat("s", 65), "admin"}, "invalid username"},
{[]string{"user", "add", "cli", "admin"}, "reserved username"},
{[]string{"user", "add", "alice", "Admin"}, "invalid role"},
{[]string{"user", "add", "alice", "secretarg"}, "invalid role"},
{[]string{"user", "passwd"}, "user passwd requires a username"},
{[]string{"user", "passwd", "a", "secretarg"}, "user passwd requires a username"},
{[]string{"user", "passwd", "secret arg"}, "invalid username"},
{[]string{"user", "role", "alice"}, "user role requires a username and a role"},
{[]string{"user", "role", "secret/arg", "user"}, "invalid username"},
{[]string{"user", "role", "alice", "root"}, "invalid role"},
{[]string{"user", "delete"}, "user delete requires a username"},
{[]string{"user", "delete", "secret$arg"}, "invalid username"},
{[]string{"check", "a.org.", "secretarg"}, "check takes at most one zone"},
{[]string{"check", ""}, "invalid zone"},
{[]string{"audit", "1", "secretarg"}, "audit takes at most one count"},
{[]string{"audit", "0"}, "invalid audit count"},
{[]string{"audit", "-1"}, "invalid audit count"},
{[]string{"audit", "+5"}, "invalid audit count"},
{[]string{"audit", "5x"}, "invalid audit count"},
{[]string{"audit", "secretarg"}, "invalid audit count"},
{[]string{"audit", "9223372036854775808"}, "invalid audit count"},
}
for _, c := range cases {
h := newCLIHarness(t, "password-on-stdin\n")
code := h.run(c.args...)
want := "coredns-web-ui: usage error: " + c.msg + "\n" + specUsageText
if code != 2 || h.stderr.String() != want || h.stdout.Len() != 0 {
t.Errorf("%v: code %d stderr %q", c.args, code, h.stderr.String())
}
if strings.Contains(h.stderr.String(), "ecretarg") || strings.Contains(h.stderr.String(), "ecret arg") {
t.Errorf("%v: argument echoed", c.args)
}
if h.prepared != 0 || len(h.hashed) != 0 {
t.Errorf("%v: database or password touched", c.args)
}
}
}
func TestDatabaseCommandsNeedConfig(t *testing.T) {
for _, args := range [][]string{{"user", "list"}, {"check"}, {"audit"}, {"user", "bogus"}} {
h := newCLIHarness(t, "")
delete(h.env, "DB_PASSWORD")
code := h.run(args...)
if code != 2 || h.stderr.String() != "coredns-web-ui: configuration error: DB_PASSWORD is required\n" || h.prepared != 0 {
t.Errorf("%v: %d %q", args, code, h.stderr.String())
}
}
h := newCLIHarness(t, "")
delete(h.env, "DB_HOST")
if code := h.run(); code != 2 || !strings.Contains(h.stderr.String(), "DB_HOST is required") {
t.Fatalf("server: %d %q", code, h.stderr.String())
}
}
func TestPrepareFailure(t *testing.T) {
h := newCLIHarness(t, "")
h.prepErr = errors.New("database unavailable: ping failed")
if code := h.run("user", "list"); code != 1 || h.stderr.String() != "coredns-web-ui: database unavailable: ping failed\n" {
t.Fatalf("%d %q", code, h.stderr.String())
}
if h.users.listCalls != 0 {
t.Fatal("command ran without database")
}
}
func TestUserList(t *testing.T) {
h := newCLIHarness(t, "")
a := h.addUser("alice", "admin", false)
h.users.users[0].LastLoginAt = sql.NullTime{Time: time.Date(2026, 11, 18, 11, 30, 15, 999, time.UTC), Valid: true}
b := h.addUser("bob-the-builder", "user", false)
h.addUser("carl", "user", true)
h.users.zones[b.ID] = 12
_ = a
if code := h.run("user", "list"); code != 0 || h.stderr.Len() != 0 {
t.Fatalf("%d %q", code, h.stderr.String())
}
want := "" +
"USERNAME ROLE ZONES CREATED_AT LAST_LOGIN_AT DELETED_AT\n" +
"alice admin 0 2026-11-18T11:00:00Z 2026-11-18T11:30:15Z -\n" +
"bob-the-builder user 12 2026-11-18T11:00:00Z - -\n"
if h.stdout.String() != want {
t.Fatalf("got\n%s", h.stdout.String())
}
h.stdout.Reset()
if code := h.run("user", "list", "all"); code != 0 {
t.Fatal(code)
}
if !strings.HasSuffix(h.stdout.String(), "carl user 0 2026-11-18T11:00:00Z - 2026-11-18T11:59:00Z\n") {
t.Fatalf("got\n%s", h.stdout.String())
}
if len(h.users.audit) != 0 {
t.Fatal("list wrote audit rows")
}
h = newCLIHarness(t, "")
if code := h.run("user", "list"); code != 0 || h.stdout.String() != "USERNAME ROLE ZONES CREATED_AT LAST_LOGIN_AT DELETED_AT\n" {
t.Fatalf("%d %q", code, h.stdout.String())
}
h = newCLIHarness(t, "")
h.users.failOn = "ListUsers"
if code := h.run("user", "list"); code != 1 || h.stdout.Len() != 0 {
t.Fatal(code)
}
}
func decodeAuditUser(t *testing.T, b []byte) map[string]any {
t.Helper()
var m map[string]any
if err := json.Unmarshal(b, &m); err != nil {
t.Fatalf("%s: %v", b, err)
}
return m
}
func TestUserAdd(t *testing.T) {
h := newCLIHarness(t, "correct horse battery\n")
if code := h.run("user", "add", "alice", "admin"); code != 0 || h.stdout.Len() != 0 || h.stderr.Len() != 0 {
t.Fatalf("%d %q %q", code, h.stdout.String(), h.stderr.String())
}
if len(h.users.users) != 1 {
t.Fatal(h.users.users)
}
u := h.users.users[0]
if u.Username != "alice" || u.Role != "admin" || u.PasswordHash != "$hash$correct horse battery" || !u.CreatedAt.Equal(cliNow) {
t.Fatalf("%+v", u)
}
if len(h.users.audit) != 1 {
t.Fatal(h.users.audit)
}
e := h.users.audit[0]
if e.Actor != "cli" || e.Origin != "local" || e.Operation != "user_create" || e.UserID.Valid || e.Status.Valid || e.Error.Valid ||
e.Zone.Valid || e.RecordID.Valid || e.TargetUserID.Int64 != u.ID || e.Before != nil || !e.Time.Equal(cliNow) {
t.Fatalf("%+v", e)
}
after := decodeAuditUser(t, e.After)
if after["username"] != "alice" || after["role"] != "admin" || after["deleted_at"] != nil || after["created_at"] != "2026-11-18T12:00:00.000000Z" || len(after) != 5 {
t.Fatalf("%v", after)
}
if strings.Contains(string(e.After), "hash") {
t.Fatal("hash in audit")
}
h2 := newCLIHarness(t, "another password\n")
h2.addUser("alice", "user", true)
if code := h2.run("user", "add", "alice", "user"); code != 1 || h2.stderr.String() != "coredns-web-ui: username already used\n" || len(h2.users.audit) != 0 {
t.Fatalf("%d %q", code, h2.stderr.String())
}
h3 := newCLIHarness(t, "another password\n")
h3.users.failOn = "InsertAudit"
if code := h3.run("user", "add", "bob", "user"); code != 1 || len(h3.users.users) != 0 {
t.Fatalf("audit failure did not roll back: %d %v", code, h3.users.users)
}
}
func TestPasswordInput(t *testing.T) {
cases := []struct {
stdin string
ok bool
want string
msg string
}{
{"twelve-bytes", true, "twelve-bytes", ""},
{"twelve-bytes\r\n", true, "twelve-bytes", ""},
{"twelve-bytes\nsecond line\n", true, "twelve-bytes", ""},
{" spaces ok \n", true, " spaces ok ", ""},
{"ünïcödé-pässwörd\n", true, "ünïcödé-pässwörd", ""},
{strings.Repeat("p", 256) + "\n", true, strings.Repeat("p", 256), ""},
{"", false, "", "no password on stdin"},
{"\n", false, "", "password must be 12 to 256 bytes"},
{"eleven-byte\n", false, "", "password must be 12 to 256 bytes"},
{strings.Repeat("p", 257) + "\n", false, "", "password must be 12 to 256 bytes"},
{strings.Repeat("p", 10000), false, "", "password must be 12 to 256 bytes"},
{"tab\tinside-password\n", false, "", "password must not contain control characters"},
{"nul\x00inside-password\n", false, "", "password must not contain control characters"},
{"c1\u0085inside-password\n", false, "", "password must not contain control characters"},
{"bad\xffutf8-password\n", false, "", "password must be valid UTF-8"},
}
for _, c := range cases {
h := newCLIHarness(t, c.stdin)
h.addUser("alice", "admin", false)
code := h.run("user", "passwd", "alice")
if c.ok {
if code != 0 || len(h.hashed) != 1 || h.hashed[0] != c.want {
t.Errorf("%q: %d %q %q", c.stdin, code, h.hashed, h.stderr.String())
}
continue
}
if code != 1 || h.stderr.String() != "coredns-web-ui: "+c.msg+"\n" || h.prepared != 0 || len(h.hashed) != 0 {
t.Errorf("%q: %d %q prepared %d", c.stdin, code, h.stderr.String(), h.prepared)
}
if p := strings.TrimSpace(c.stdin); p != "" && strings.Contains(h.stderr.String(), p) {
t.Errorf("password echoed")
}
}
}
type failingReader struct{}
func (failingReader) Read([]byte) (int, error) { return 0, errors.New("broken stdin") }
func TestPasswordInputErrors(t *testing.T) {
h := newCLIHarness(t, "")
h.a.stdin = failingReader{}
if code := h.run("user", "add", "alice", "admin"); code != 1 || !strings.Contains(h.stderr.String(), "read password: broken stdin") {
t.Fatalf("%d %q", code, h.stderr.String())
}
h = newCLIHarness(t, "long enough password\n")
h.a.hashPassword = func(string) (string, error) { return "", errors.New("argon2 failure") }
if code := h.run("user", "add", "alice", "admin"); code != 1 || h.stderr.String() != "coredns-web-ui: hash password: argon2 failure\n" || h.prepared != 0 {
t.Fatalf("%d %q", code, h.stderr.String())
}
}
func TestPasswordTerminal(t *testing.T) {
answers := [][]byte{[]byte("terminal-password"), []byte("terminal-password")}
h := newCLIHarness(t, "")
h.a.stdinIsTerminal = func() bool { return true }
h.a.readTerminalPassword = func() ([]byte, error) {
a := answers[0]
answers = answers[1:]
return a, nil
}
if code := h.run("user", "add", "alice", "user"); code != 0 {
t.Fatalf("%d %q", code, h.stderr.String())
}
if h.stderr.String() != "Password: \nRepeat password: \n" || h.stdout.Len() != 0 || h.hashed[0] != "terminal-password" {
t.Fatalf("%q %q", h.stderr.String(), h.hashed)
}
answers = [][]byte{[]byte("terminal-password"), []byte("different-password")}
h = newCLIHarness(t, "")
h.a.stdinIsTerminal = func() bool { return true }
h.a.readTerminalPassword = func() ([]byte, error) {
a := answers[0]
answers = answers[1:]
return a, nil
}
if code := h.run("user", "add", "alice", "user"); code != 1 || !strings.HasSuffix(h.stderr.String(), "coredns-web-ui: passwords do not match\n") || h.prepared != 0 {
t.Fatalf("%d %q", code, h.stderr.String())
}
for _, failAt := range []int{1, 2} {
calls := 0
h = newCLIHarness(t, "")
h.a.stdinIsTerminal = func() bool { return true }
h.a.readTerminalPassword = func() ([]byte, error) {
calls++
if calls == failAt {
return nil, errors.New("tty gone")
}
return []byte("terminal-password"), nil
}
if code := h.run("user", "passwd", "alice"); code != 1 || !strings.Contains(h.stderr.String(), "read password: tty gone") {
t.Fatalf("%d %q", code, h.stderr.String())
}
}
h = newCLIHarness(t, "")
h.a.stdinIsTerminal = func() bool { return true }
h.a.stderr = failingWriter{}
if _, err := h.a.readPassword(); err == nil || !strings.Contains(err.Error(), "write prompt") {
t.Fatal(err)
}
}
type failingWriter struct{}
func (failingWriter) Write([]byte) (int, error) { return 0, errors.New("closed") }
func TestUserPasswd(t *testing.T) {
h := newCLIHarness(t, "brand new password\n")
alice := h.addUser("alice", "admin", false)
h.users.sessions[alice.ID] = 3
if code := h.run("user", "passwd", "alice"); code != 0 || h.stdout.Len() != 0 {
t.Fatalf("%d %q", code, h.stderr.String())
}
u := h.users.users[0]
if u.PasswordHash != "$hash$brand new password" || !u.UpdatedAt.Equal(cliNow) || h.users.sessions[alice.ID] != 0 {
t.Fatalf("%+v %v", u, h.users.sessions)
}
e := h.users.audit[0]
if len(h.users.audit) != 1 || e.Operation != "user_password" || e.TargetUserID.Int64 != alice.ID || string(e.Before) != string(e.After) || e.Before == nil {
t.Fatalf("%+v", e)
}
for _, name := range []string{"nobody", "gone"} {
h = newCLIHarness(t, "brand new password\n")
h.addUser("gone", "user", true)
if code := h.run("user", "passwd", name); code != 1 || h.stderr.String() != "coredns-web-ui: no active user has this username\n" || len(h.users.audit) != 0 {
t.Fatalf("%s: %d %q", name, code, h.stderr.String())
}
}
for _, op := range []string{"UserByUsernameForUpdate", "SetPassword", "DeleteUserSessions", "InsertAudit", "Commit"} {
h = newCLIHarness(t, "brand new password\n")
h.addUser("alice", "admin", false)
h.users.failOn = op
if code := h.run("user", "passwd", "alice"); code != 1 || h.users.users[0].PasswordHash != "$old" || len(h.users.audit) != 0 {
t.Fatalf("%s: %d", op, code)
}
}
}
func TestUserRole(t *testing.T) {
h := newCLIHarness(t, "")
alice := h.addUser("alice", "admin", false)
bob := h.addUser("bob", "user", false)
if code := h.run("user", "role", "alice", "user"); code != 1 || h.stderr.String() != "coredns-web-ui: the last active admin cannot be demoted or deleted\n" {
t.Fatalf("%d %q", code, h.stderr.String())
}
h.stderr.Reset()
if code := h.run("user", "role", "bob", "admin"); code != 0 || h.stderr.Len() != 0 {
t.Fatalf("%d %q", code, h.stderr.String())
}
e := h.users.audit[0]
if e.Operation != "user_role" || e.TargetUserID.Int64 != bob.ID || decodeAuditUser(t, e.Before)["role"] != "user" || decodeAuditUser(t, e.After)["role"] != "admin" {
t.Fatalf("%+v", e)
}
if code := h.run("user", "role", "alice", "user"); code != 0 || h.users.users[0].Role != "user" || len(h.users.audit) != 2 {
t.Fatalf("%d %+v", code, h.users.users)
}
if code := h.run("user", "role", "alice", "user"); code != 0 || len(h.users.audit) != 2 {
t.Fatalf("unchanged role wrote audit: %d", len(h.users.audit))
}
_ = alice
h = newCLIHarness(t, "")
h.addUser("gone", "admin", true)
h.addUser("root", "admin", false)
if code := h.run("user", "role", "gone", "user"); code != 1 || !strings.Contains(h.stderr.String(), "no active user") {
t.Fatalf("%d %q", code, h.stderr.String())
}
h = newCLIHarness(t, "")
h.addUser("bob", "user", false)
if code := h.run("user", "role", "bob", "user"); code != 0 || len(h.users.audit) != 0 {
t.Fatal(code)
}
for _, op := range []string{"LockActiveAdmins", "UserByUsernameForUpdate", "SetRole", "InsertAudit"} {
h = newCLIHarness(t, "")
h.addUser("a1", "admin", false)
h.addUser("a2", "admin", false)
h.users.failOn = op
if code := h.run("user", "role", "a1", "user"); code != 1 || h.users.users[0].Role != "admin" {
t.Fatalf("%s: %d", op, code)
}
}
}
func TestUserDelete(t *testing.T) {
h := newCLIHarness(t, "")
alice := h.addUser("alice", "admin", false)
bob := h.addUser("bob", "user", false)
h.users.sessions[bob.ID] = 2
if code := h.run("user", "delete", "alice"); code != 1 || !strings.Contains(h.stderr.String(), "last active admin") {
t.Fatalf("%d %q", code, h.stderr.String())
}
if code := h.run("user", "delete", "bob"); code != 0 {
t.Fatalf("%d %q", code, h.stderr.String())
}
u := h.users.users[1]
if !u.DeletedAt.Valid || !u.DeletedAt.Time.Equal(cliNow) || h.users.sessions[bob.ID] != 0 {
t.Fatalf("%+v", u)
}
e := h.users.audit[0]
if e.Operation != "user_delete" || decodeAuditUser(t, e.Before)["deleted_at"] != nil || decodeAuditUser(t, e.After)["deleted_at"] != "2026-11-18T12:00:00.000000Z" {
t.Fatalf("%+v", e)
}
if code := h.run("user", "delete", "bob"); code != 1 || len(h.users.audit) != 1 {
t.Fatal("deleted twice")
}
h.addUser("carol", "admin", false)
if code := h.run("user", "delete", "alice"); code != 0 {
t.Fatalf("second admin present: %d", code)
}
_ = alice
for _, op := range []string{"LockActiveAdmins", "MarkDeleted", "DeleteUserSessions", "InsertAudit"} {
h = newCLIHarness(t, "")
h.addUser("bob", "user", false)
h.users.failOn = op
if code := h.run("user", "delete", "bob"); code != 1 || h.users.users[0].DeletedAt.Valid {
t.Fatalf("%s: %d", op, code)
}
}
}
type fakeReadBackend struct {
zones []zoneSummary
rows map[string][]recordRow
audit []auditRow
failOn string
auditN int64
rowCalls []string
}
func (f *fakeReadBackend) ListZones(ctx context.Context) ([]zoneSummary, error) {
if f.failOn == "ListZones" {
return nil, errFakeStore
}
return f.zones, nil
}
func (f *fakeReadBackend) ZoneRows(ctx context.Context, zone string) ([]recordRow, error) {
f.rowCalls = append(f.rowCalls, zone)
if f.failOn == "ZoneRows" {
return nil, errFakeStore
}
return f.rows[zone], nil
}
func (f *fakeReadBackend) LatestAudit(ctx context.Context, n int64) ([]auditRow, error) {
f.auditN = n
if f.failOn == "LatestAudit" {
return nil, errFakeStore
}
return f.audit, nil
}
func cliRecord(id int64, zone, name, recordType string, ttl any, content any) recordRow {
r := recordRow{ID: id, Zone: zone, Name: name, RecordType: recordType}
if v, ok := ttl.(int); ok {
r.TTL = sql.NullInt64{Int64: int64(v), Valid: true}
}
if v, ok := content.(string); ok {
r.Content = sql.NullString{String: v, Valid: true}
}
return r
}
func cleanZoneRows(zone string) []recordRow {
return []recordRow{
cliRecord(1, zone, "", "SOA", 3600, `{"ns":"ns1.`+zone+`","MBox":"hostmaster.`+zone+`","refresh":3600,"retry":600,"expire":604800,"minttl":300,"serial":2026111800}`),
cliRecord(2, zone, "", "NS", 3600, `{"host":"ns1.`+zone+`"}`),
cliRecord(3, zone, "ns1", "A", 3600, `{"ip":"192.0.2.1"}`),
}
}
func (h *cliHarness) withReadBackend(b *fakeReadBackend) {
h.a.newReadBackend = func(*sql.DB, tableNames) cliReadBackend { return b }
}
func TestCheckCommand(t *testing.T) {
var zone string
b := &fakeReadBackend{rows: map[string][]recordRow{"example.org.": cleanZoneRows("example.org.")}}
h := newCLIHarness(t, "")
h.withReadBackend(b)
h.a.normalizeZone = func(z string) (string, error) { zone = z; return normalizeZone(z) }
if code := h.run("check", "Example.Org"); code != 0 || h.stderr.Len() != 0 || h.prepared != 1 || zone != "Example.Org" {
t.Fatalf("%d %q", code, h.stderr.String())
}
if h.stdout.String() != "ZONE NAME TYPE ID SEVERITY PROBLEM\n" || len(b.rowCalls) != 1 || b.rowCalls[0] != "example.org." {
t.Fatalf("%q %v", h.stdout.String(), b.rowCalls)
}
broken := []recordRow{
cliRecord(7, "broken.test.", "www", "A", nil, `{"ip":"192.0.2.7"}`),
cliRecord(8, "broken.test.", "", "TXT", 300, "x\ty"),
}
b = &fakeReadBackend{
zones: []zoneSummary{{Zone: "broken.test."}, {Zone: "example.org."}},
rows: map[string][]recordRow{"example.org.": cleanZoneRows("example.org."), "broken.test.": broken},
}
h = newCLIHarness(t, "")
h.withReadBackend(b)
if code := h.run("check"); code != 3 || h.stderr.Len() != 0 {
t.Fatalf("%d %q", code, h.stderr.String())
}
lines := strings.Split(strings.TrimSuffix(h.stdout.String(), "\n"), "\n")
if !strings.HasPrefix(lines[0], "ZONE ") || !strings.Contains(lines[0], "PROBLEM") {
t.Fatal(lines[0])
}
out := h.stdout.String()
for _, want := range []string{"ttl_null: stored TTL is NULL", "soa_missing", "content_json", " www ", " @ ", " 7 ", " 8 ", "error"} {
if !strings.Contains(out, want) {
t.Errorf("missing %q in\n%s", want, out)
}
}
if strings.Contains(out, "example.org.") || strings.Contains(out, "\t") {
t.Fatalf("unexpected output\n%s", out)
}
for _, line := range lines[1:] {
if !strings.HasPrefix(line, "broken.test.") {
t.Fatalf("line %q", line)
}
}
if !strings.Contains(out, "broken.test. - - - error") {
t.Fatalf("zone level problem row missing\n%s", out)
}
h = newCLIHarness(t, "")
h.withReadBackend(&fakeReadBackend{rows: map[string][]recordRow{}})
if code := h.run("check", "missing.test"); code != 1 || h.stderr.String() != "coredns-web-ui: the zone has no records\n" || h.stdout.Len() != 0 {
t.Fatalf("%d %q", code, h.stderr.String())
}
for _, op := range []string{"ListZones", "ZoneRows"} {
h = newCLIHarness(t, "")
h.withReadBackend(&fakeReadBackend{zones: []zoneSummary{{Zone: "a.test."}}, failOn: op})
if code := h.run("check"); code != 1 || h.stdout.Len() != 0 {
t.Fatalf("%s: %d", op, code)
}
}
h = newCLIHarness(t, "")
h.withReadBackend(&fakeReadBackend{})
if code := h.run("check"); code != 0 || h.stdout.String() != "ZONE NAME TYPE ID SEVERITY PROBLEM\n" {
t.Fatalf("no zones: %d %q", code, h.stdout.String())
}
h = newCLIHarness(t, "")
if code := h.run("check", "a", "b"); code != 2 || h.prepared != 0 {
t.Fatal(code)
}
h = newCLIHarness(t, "")
if code := h.run("check", "bad zone"); code != 2 || h.prepared != 0 || strings.Contains(h.stderr.String(), "bad zone") {
t.Fatal(code, h.stderr.String())
}
}
func TestAuditCommand(t *testing.T) {
at := time.Date(2026, 11, 18, 10, 11, 12, 345678000, time.UTC)
b := &fakeReadBackend{audit: []auditRow{
{auditEntry: auditEntry{ID: 1, Time: at, Actor: "cli", Origin: "local", Operation: "user_create", TargetUserID: sql.NullInt64{Int64: 3, Valid: true}}, TargetUsername: sql.NullString{String: "bob", Valid: true}},
{auditEntry: auditEntry{ID: 2, Time: at.Add(time.Second), UserID: sql.NullInt64{Int64: 3, Valid: true}, Actor: "bad\tactor\n", Origin: "192.0.2.1", Operation: "record_update",
Status: sql.NullInt64{Int64: 200, Valid: true}, Zone: sql.NullString{String: "example.org.", Valid: true}, RecordID: sql.NullInt64{Int64: 42, Valid: true}}},
{auditEntry: auditEntry{ID: 3, Time: at.Add(2 * time.Second), Actor: "", Origin: "2001:db8::1", Operation: "login", Status: sql.NullInt64{Int64: 401, Valid: true}}},
}}
h := newCLIHarness(t, "")
h.withReadBackend(b)
if code := h.run("audit"); code != 0 || h.stderr.Len() != 0 || b.auditN != 20 || h.prepared != 1 {
t.Fatalf("%d %q %d", code, h.stderr.String(), b.auditN)
}
want := "TIME ACTOR ORIGIN OPERATION STATUS ZONE RECORD TARGET_USER\n" +
"2026-11-18T10:11:12Z cli local user_create - - - bob\n" +
"2026-11-18T10:11:13Z bad actor 192.0.2.1 record_update 200 example.org. 42 -\n" +
"2026-11-18T10:11:14Z - 2001:db8::1 login 401 - - -\n"
if h.stdout.String() != want {
t.Fatalf("got\n%s\nwant\n%s", h.stdout.String(), want)
}
for args, n := range map[string]int64{"5": 5, "0001": 1, "1000000": 1000000, "1000001": 1000001, "9223372036854775807": 9223372036854775807} {
b = &fakeReadBackend{}
h = newCLIHarness(t, "")
h.withReadBackend(b)
if code := h.run("audit", args); code != 0 || b.auditN != n || h.stdout.String() != "TIME ACTOR ORIGIN OPERATION STATUS ZONE RECORD TARGET_USER\n" {
t.Fatalf("%s: %d %d %q", args, code, b.auditN, h.stdout.String())
}
}
h = newCLIHarness(t, "")
h.withReadBackend(&fakeReadBackend{failOn: "LatestAudit"})
if code := h.run("audit"); code != 1 || h.stdout.Len() != 0 {
t.Fatal(code)
}
for _, args := range [][]string{{"audit", "0"}, {"audit", "-1"}, {"audit", "x"}, {"audit", "9223372036854775808"}, {"audit", "99999999999999999999"}, {"audit", "1", "2"}, {"audit", "+5"}, {"audit", "1e3"}, {"audit", " 5"}} {
h = newCLIHarness(t, "")
if code := h.run(args...); code != 2 || h.prepared != 0 {
t.Fatalf("%v: %d", args, code)
}
}
if n, err := parseAuditCount("20"); n != 20 || err != nil {
t.Fatal(n, err)
}
}
func TestSQLReadBackend(t *testing.T) {
db, state := newFakeDB(t, fdbRules())
b := newSQLReadBackend(db, fdbTables(t))
if _, err := b.ListZones(context.Background()); err != nil {
t.Fatal(err)
}
if _, err := b.ZoneRows(context.Background(), "example.org."); err != nil {
t.Fatal(err)
}
if _, err := b.LatestAudit(context.Background(), 3); err != nil {
t.Fatal(err)
}
q := state.Queries()
if len(q) != 3 || !strings.Contains(q[0], "GROUP BY") || !strings.Contains(q[1], "`coredns_records`") || !strings.Contains(q[2], "`coredns_webui_audit`") {
t.Fatal(q)
}
}
func TestExitCodes(t *testing.T) {
h := newCLIHarness(t, "")
if h.a.exitCode(nil) != 0 {
t.Fatal("nil")
}
if h.a.exitCode(errCheckProblems) != 3 || h.stderr.Len() != 0 {
t.Fatal("problems")
}
if h.a.exitCode(errors.New("line1\nline2\rline3")) != 1 || h.stderr.String() != "coredns-web-ui: line1 line2 line3\n" {
t.Fatalf("%q", h.stderr.String())
}
}
func TestValidUsernameSyntax(t *testing.T) {
for _, u := range []string{"a", "0", "alice", "a.b-c_d", "cli", strings.Repeat("a", 64)} {
if !validUsernameSyntax(u) {
t.Errorf("%q refused", u)
}
}
for _, u := range []string{"", "Alice", "_a", "-a", ".a", "a b", "a@b", strings.Repeat("a", 65), "ä"} {
if validUsernameSyntax(u) {
t.Errorf("%q accepted", u)
}
}
}
func TestHealthcheckURL(t *testing.T) {
cases := map[string]string{
"0.0.0.0": "http://127.0.0.1:8080/health",
"::": "http://127.0.0.1:8080/health",
"192.0.2.5": "http://192.0.2.5:8080/health",
"::1": "http://[::1]:8080/health",
}
for addr, want := range cases {
if got := healthcheckURL(Config{HTTPAddr: addr, HTTPPort: 8080}); got != want {
t.Errorf("%s: %s", addr, got)
}
}
}
func TestHealthcheckCommand(t *testing.T) {
status := http.StatusOK
var path string
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
path = r.URL.Path
w.WriteHeader(status)
}))
defer srv.Close()
u, _ := url.Parse(srv.URL)
host, port, _ := net.SplitHostPort(u.Host)
for _, tc := range []struct {
status int
code int
stderr string
}{
{http.StatusOK, 0, ""},
{http.StatusServiceUnavailable, 1, "coredns-web-ui: health check failed: status 503\n"},
{http.StatusFound, 1, "coredns-web-ui: health check failed: status 302\n"},
} {
status = tc.status
h := newCLIHarness(t, "")
h.env = map[string]string{"HTTP_ADDR": host, "HTTP_PORT": port, "DB_PORT": "invalid"}
if code := h.run("healthcheck"); code != tc.code || h.stderr.String() != tc.stderr || h.stdout.Len() != 0 || path != "/health" {
t.Fatalf("%d: %d %q", tc.status, code, h.stderr.String())
}
}
srv.Close()
h := newCLIHarness(t, "")
h.env = map[string]string{"HTTP_ADDR": host, "HTTP_PORT": port}
if code := h.run("healthcheck"); code != 1 || !strings.HasPrefix(h.stderr.String(), "coredns-web-ui: health check failed: ") {
t.Fatalf("%d %q", code, h.stderr.String())
}
h = newCLIHarness(t, "")
h.env = map[string]string{"HTTP_PORT": "99999"}
if code := h.run("healthcheck"); code != 2 || h.stderr.String() != "coredns-web-ui: configuration error: invalid HTTP_PORT: must be an integer between 1 and 65535\n" {
t.Fatalf("%d %q", code, h.stderr.String())
}
if c := newHealthClient(); c.Timeout != 3*time.Second || c.CheckRedirect(nil, nil) != http.ErrUseLastResponse {
t.Fatal("health client")
}
}
func TestWriteOutputErrors(t *testing.T) {
h := newCLIHarness(t, "")
h.a.stdout = failingWriter{}
if code := h.run("help"); code != 1 || !strings.Contains(h.stderr.String(), "write output") {
t.Fatalf("%d %q", code, h.stderr.String())
}
if err := writeTable(failingWriter{}, []string{"A"}, nil); err == nil {
t.Fatal("table write error ignored")
}
}
func TestFormatCLITime(t *testing.T) {
if formatCLITime(time.Date(2026, 1, 2, 3, 4, 5, 999999999, time.FixedZone("x", 3600))) != "2026-01-02T02:04:05Z" {
t.Fatal("format")
}
if formatCLINullTime(sql.NullTime{}) != "-" {
t.Fatal("null")
}
}
func cliSQLHandler() fdbHandler {
return func(q string, args []any) fdbResponse {
switch {
case strings.HasPrefix(q, "INSERT INTO `coredns_webui_users`"):
return fdbResponse{lastInsertID: 7}
case strings.HasPrefix(q, "INSERT INTO `coredns_webui_audit`"):
return fdbResponse{lastInsertID: 1}
case strings.Contains(q, "COUNT(*)"):
return fdbResponse{rows: [][]driver.Value{append(userValues(7, "alice", "admin", false), int64(0))}}
}
return fdbResponse{}
}
}
func TestSQLUserBackend(t *testing.T) {
ctx := context.Background()
db, state := newFakeDB(t, cliSQLHandler())
b := newSQLUserBackend(db, fdbTables(t))
users, err := b.ListUsers(ctx, false)
if err != nil || len(users) != 1 || users[0].Username != "alice" {
t.Fatal(users, err)
}
h := newCLIHarness(t, "")
h.a.newUserBackend = newSQLUserBackend
if err := h.a.userAdd(ctx, b, discardLogger(), "alice", "admin", "$hash"); err != nil {
t.Fatal(err)
}
if state.commits != 1 {
t.Fatalf("commits %d", state.commits)
}
q := state.Queries()
if len(q) != 3 || !strings.HasPrefix(q[1], "INSERT INTO `coredns_webui_users`") || !strings.HasPrefix(q[2], "INSERT INTO `coredns_webui_audit`") {
t.Fatalf("queries %v", q)
}
audit := state.Calls()[2].args
if audit[1] != nil || audit[2] != "cli" || audit[3] != "local" || audit[4] != "user_create" || audit[5] != nil || audit[9] != int64(7) || audit[10] != nil {
t.Fatalf("audit args %#v", audit)
}
if err := h.a.userDelete(ctx, b, discardLogger(), "alice"); !errors.Is(err, errNoActiveUser) || state.rollbacks != 1 {
t.Fatalf("%v rollbacks %d", err, state.rollbacks)
}
}
func TestCheckCommandGolden(t *testing.T) {
broken := append(cleanZoneRows("broken.test."),
cliRecord(4, "broken.test.", "www", "A", nil, `{"ip":"192.0.2.7"}`),
cliRecord(5, "broken.test.", "", "MX", 3600, `{"host":"ns1.broken.test.","priority":10}`),
cliRecord(6, "broken.test.", "Mail", "A", 0, `{"ip":"192.0.2.8"}`),
)
warned := append(cleanZoneRows("warn.test."), cliRecord(9, "warn.test.", "text", "TXT", 3600, `{"text":"`+strings.Repeat("x", 256)+`"}`))
b := &fakeReadBackend{
zones: []zoneSummary{{Zone: "broken.test."}, {Zone: "warn.test."}},
rows: map[string][]recordRow{"broken.test.": broken, "warn.test.": warned},
}
h := newCLIHarness(t, "")
h.withReadBackend(b)
if code := h.run("check"); code != 3 || h.stderr.Len() != 0 {
t.Fatalf("exit %d, stderr %q", code, h.stderr.String())
}
want := "ZONE NAME TYPE ID SEVERITY PROBLEM\n" +
"broken.test. www A 4 error ttl_null: stored TTL is NULL\n" +
"broken.test. @ MX 5 error mx_priority_key: MX uses the preference key\n" +
"broken.test. @ MX 5 error field_invalid: preference: is required\n" +
"broken.test. Mail A 6 warning name_case: stored owner name contains uppercase letters\n" +
"broken.test. Mail A 6 warning ttl_zero: TTL zero is served as 360 seconds\n" +
"warn.test. text TXT 9 warning txt_split: TXT is served in strings of at most 255 bytes\n"
if h.stdout.String() != want {
t.Fatalf("output:\n%s\nwant:\n%s", h.stdout.String(), want)
}
h = newCLIHarness(t, "")
h.withReadBackend(b)
if code := h.run("check", "warn.test"); code != 3 || h.stderr.Len() != 0 {
t.Fatalf("warning-only zone: exit %d, stderr %q", code, h.stderr.String())
}
want = "ZONE NAME TYPE ID SEVERITY PROBLEM\n" +
"warn.test. text TXT 9 warning txt_split: TXT is served in strings of at most 255 bytes\n"
if h.stdout.String() != want {
t.Fatalf("warning-only output:\n%s\nwant:\n%s", h.stdout.String(), want)
}
}