- 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
834 lines
30 KiB
Go
834 lines
30 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: stubNormalizeZone,
|
|
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", "10000000"}, "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)
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestCheckAndAuditCommands(t *testing.T) {
|
|
var zone string
|
|
h := newCLIHarness(t, "")
|
|
h.a.normalizeZone = func(z string) (string, error) { zone = z; return "example.org.", nil }
|
|
if code := h.run("check", "Example.Org"); code != 1 || h.stderr.String() != "coredns-web-ui: check: not implemented\n" || h.prepared != 1 || zone != "Example.Org" {
|
|
t.Fatalf("%d %q", code, h.stderr.String())
|
|
}
|
|
h = newCLIHarness(t, "")
|
|
if code := h.run("check"); code != 1 || h.prepared != 1 {
|
|
t.Fatal(code)
|
|
}
|
|
for _, args := range [][]string{{"audit"}, {"audit", "5"}, {"audit", "0001"}, {"audit", "1000000"}} {
|
|
h = newCLIHarness(t, "")
|
|
if code := h.run(args...); code != 1 || h.stderr.String() != "coredns-web-ui: audit: not implemented\n" || h.prepared != 1 {
|
|
t.Fatalf("%v: %d %q", args, code, h.stderr.String())
|
|
}
|
|
}
|
|
if n, err := parseAuditCount("20"); n != 20 || err != nil {
|
|
t.Fatal(n, err)
|
|
}
|
|
}
|
|
|
|
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)
|
|
}
|
|
}
|