Files
coredns-web-ui/handlers_zone_api_test.go
T

418 lines
20 KiB
Go

// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright (C) 2026 Bryan Joshua Pedini
package main
import (
"database/sql"
"errors"
"slices"
"strconv"
"strings"
"testing"
)
func zoneAPITestFailOn(failure error, parts ...string) func(string) error {
return func(query string) error {
for _, part := range parts {
if strings.HasPrefix(part, "!") {
if strings.Contains(query, part[1:]) {
return nil
}
} else if !strings.Contains(query, part) {
return nil
}
}
return failure
}
}
func TestZoneAPIFailurePaths(t *testing.T) {
failure := errors.New("database failed")
rows := zoneAPITestRows(t)
rowsWithStale := func(f *zoneAPITestDB, _ *apiContext) { f.rows, f.stale = nil, true }
asUser := func(f *zoneAPITestDB, c *apiContext) {
f.actor.Role, c.Principal.User.Role = "user", "user"
}
zoneRead := []string{zoneRowsWhere, "!FOR UPDATE"}
for _, tc := range []struct {
name string
operation string
id string
etag string
body string
setup func(*zoneAPITestDB, *apiContext)
failOn []string
status int
field string
ran string
}{
{name: "actor lookup", operation: "record_create", body: zoneAPITestRecord, failOn: []string{"SELECT u."}},
{name: "delegation lookup", operation: "record_create", body: zoneAPITestRecord, setup: asUser, failOn: []string{"zone_delegations", "LOCK IN SHARE MODE"}},
{name: "zone rows lookup", operation: "record_create", body: zoneAPITestRecord, failOn: []string{zoneRowsWhere, "FOR UPDATE"}},
{name: "create malformed body", operation: "zone_create", body: "{", status: 400},
{name: "create stale grant lookup", operation: "zone_create", body: zoneAPITestCreate, setup: rowsWithStale, failOn: []string{"ORDER BY username FOR UPDATE"}},
{name: "create after removing stale grants", operation: "zone_create", body: zoneAPITestCreate, setup: rowsWithStale,
failOn: []string{"INSERT INTO `coredns`.`coredns_records`"}, ran: "DELETE FROM `webui`.`coredns_webui_zone_delegations`"},
{name: "create written rows", operation: "zone_create", body: zoneAPITestCreate, setup: rowsWithStale, failOn: zoneRead, ran: "INSERT INTO `coredns`.`coredns_records`"},
{name: "delete malformed body", operation: "zone_delete", body: `{"confirm":`, status: 400},
{name: "delete grants", operation: "zone_delete", body: `{"confirm":"example.org"}`, setup: func(f *zoneAPITestDB, _ *apiContext) { f.stale = true },
failOn: []string{"DELETE FROM `webui`.`coredns_webui_zone_delegations`"}},
{name: "delete after removing grants", operation: "zone_delete", body: `{"confirm":"example.org"}`, setup: func(f *zoneAPITestDB, _ *apiContext) { f.stale = true },
failOn: []string{"DELETE FROM `coredns`.`coredns_records`"}, ran: "DELETE FROM `webui`.`coredns_webui_zone_delegations`"},
{name: "record lookup outside the zone", operation: "record_update", id: "99", etag: `"x"`, body: zoneAPITestRecord, failOn: []string{"WHERE `id` = ?", "SELECT"}},
{name: "update malformed replacement", operation: "record_update", id: "3", etag: recordETag(rows[2]), body: `{"name":`, status: 400},
{name: "update unknown field", operation: "record_update", id: "3", etag: recordETag(rows[2]), body: `{"name":"first","bogus":1}`, status: 400},
{name: "update rule rejection", operation: "record_update", id: "3", etag: recordETag(rows[2]),
body: `{"name":"second","type":"CNAME","ttl":60,"data":{"host":"target.example.net"}}`, status: 422, field: "name"},
{name: "update into a second SOA", operation: "record_update", id: "3", etag: recordETag(rows[2]), body: zoneAPITestSOARecord("@"), status: 422, field: "type"},
{name: "update content not an object", operation: "record_update", id: "3", etag: recordETag(rows[2]),
body: `{"name":"first","type":"A","ttl":60,"data":"192.0.2.1"}`, status: 422, field: "data"},
{name: "update write", operation: "record_update", id: "3", etag: recordETag(rows[2]), body: zoneAPITestRecord, failOn: []string{"UPDATE `coredns`.`coredns_records`", "!`id` = 1"}},
{name: "update written rows", operation: "record_update", id: "3", etag: recordETag(rows[2]), body: zoneAPITestRecord, failOn: zoneRead},
{name: "delete invalid id", operation: "record_delete", id: "x", etag: recordETag(rows[2]), status: 400},
{name: "delete write", operation: "record_delete", id: "3", etag: recordETag(rows[2]), failOn: []string{"DELETE FROM `coredns`.`coredns_records`"}},
{name: "bulk malformed body", operation: "record_bulk_delete", body: `{"records":[`, status: 400},
{name: "bulk SOA in the batch", operation: "record_bulk_delete",
body: `{"records":[{"id":3,"etag":` + zoneAPITestJSON(t, recordETag(rows[2])) + `},{"id":1,"etag":` + zoneAPITestJSON(t, recordETag(rows[0])) + `}]}`,
status: 422, field: "records"},
{name: "bulk last apex NS in the batch", operation: "record_bulk_delete",
body: `{"records":[{"id":2,"etag":` + zoneAPITestJSON(t, recordETag(rows[1])) + `},{"id":4,"etag":` + zoneAPITestJSON(t, recordETag(rows[3])) + `}]}`,
status: 422, field: "records"},
{name: "bulk duplicate id", operation: "record_bulk_delete",
body: `{"records":[{"id":3,"etag":` + zoneAPITestJSON(t, recordETag(rows[2])) + `},{"id":3,"etag":` + zoneAPITestJSON(t, recordETag(rows[2])) + `}]}`,
status: 422, field: "records"},
{name: "bulk write", operation: "record_bulk_delete",
body: `{"records":[{"id":3,"etag":` + zoneAPITestJSON(t, recordETag(rows[2])) + `},{"id":4,"etag":` + zoneAPITestJSON(t, recordETag(rows[3])) + `}]}`,
failOn: []string{"DELETE FROM `coredns`.`coredns_records`"}},
{name: "SOA malformed body", operation: "soa_update", etag: recordETag(rows[0]), body: "[", status: 400},
{name: "SOA write", operation: "soa_update", etag: recordETag(rows[0]), body: strings.Replace(zoneAPITestSOA, `"retry":600`, `"retry":700`, 1),
failOn: []string{"UPDATE `coredns`.`coredns_records`"}},
{name: "SOA relative primary name server", operation: "soa_update", etag: recordETag(rows[0]),
body: strings.Replace(zoneAPITestSOA, "ns.example.net", "ns..example.net", 1), status: 422, field: "ns"},
{name: "import malformed body", operation: "zone_import", body: `{"mode":"merge",`, status: 400},
{name: "import missing content", operation: "zone_import", body: `{"mode":"merge","fingerprint":"` + zoneFingerprint(rows) + `"}`, status: 422, field: "content"},
{name: "import missing content preview", operation: "zone_import_preview", body: `{"mode":"replace"}`, status: 422, field: "content"},
{name: "import write", operation: "zone_import",
body: `{"mode":"merge","content":"new 60 A 192.0.2.9\n","fingerprint":"` + zoneFingerprint(rows) + `"}`,
failOn: []string{"INSERT INTO `coredns`.`coredns_records`"}},
} {
t.Run(tc.name, func(t *testing.T) {
f := zoneAPITestDBFor(t, rows)
f.foreign = recordRow{ID: 90, Zone: "private.example.", RecordType: "TXT"}
if len(tc.failOn) != 0 {
f.fail = zoneAPITestFailOn(failure, tc.failOn...)
}
server, state := f.server()
zone := zoneAPITestName
if tc.operation == "zone_create" {
zone = ""
}
c := zoneAPITestRequest(server, f.actor, tc.operation, zone, tc.id, tc.etag, tc.body)
if tc.setup != nil {
tc.setup(f, c)
}
resp, err := zoneAPITestCall(t.Context(), c)
if tc.status == 0 {
if !errors.Is(err, failure) {
t.Fatalf("response %+v, error %v, want the database failure", resp, err)
}
} else {
var apiErr *apiError
if !errors.As(err, &apiErr) || apiErr.Status != tc.status || tc.field != "" && apiErr.Fields[tc.field] == "" {
t.Fatalf("error %#v, want status %d with field %q", err, tc.status, tc.field)
}
}
if state.commits != 0 || c.auditDone || c.Entry.Before != nil || c.Entry.After != nil {
t.Fatalf("failure committed: commits %d, audit %+v", state.commits, c.Entry)
}
if tc.ran != "" && len(zoneAPITestingSQL(state, tc.ran)) == 0 {
t.Fatalf("%q did not run before the failure: %v", tc.ran, state.Queries())
}
if tc.status == 0 && len(zoneAPITestingSQL(state, "webui_locks")) != 0 && state.rollbacks != 1 {
t.Fatalf("rollbacks = %d, SQL %v", state.rollbacks, state.Queries())
}
})
}
}
func TestZoneAPIWrittenRowMissing(t *testing.T) {
f := zoneAPITestDBFor(t, zoneAPITestRows(t))
f.hideInsert = true
server, state := f.server()
c := zoneAPITestRequest(server, f.actor, "record_create", zoneAPITestName, "", "", zoneAPITestRecord)
_, err := zoneAPITestCall(t.Context(), c)
if err == nil || err.Error() != "written record not found in zone" || state.commits != 0 || c.auditDone {
t.Fatalf("error %v, commits %d", err, state.commits)
}
w := zoneAPIWrite{}
if written, err := w.writtenRows(nil); written != nil || err != nil {
t.Fatalf("empty written rows = %v, %v", written, err)
}
}
func TestZoneAPICheckAllFailure(t *testing.T) {
failure := errors.New("database failed")
f := zoneAPITestDBFor(t, zoneAPITestRows(t))
f.fail = zoneAPITestFailOn(failure, zoneRowsWhere)
server, _ := f.server()
c := zoneAPITestRequest(server, f.actor, "check_all", "", "", "", "")
if _, err := zoneAPITestCall(t.Context(), c); !errors.Is(err, failure) {
t.Fatalf("check_all error = %v", err)
}
}
func TestZoneAPIUpdateSOAThroughRecordRoute(t *testing.T) {
rows := zoneAPITestRows(t)
f := zoneAPITestDBFor(t, rows)
server, _ := f.server()
body := strings.NewReplacer(`"refresh":3600`, `"refresh":1800`, `"minttl":300}`, `"minttl":300,"serial":7}`).Replace(zoneAPITestSOARecord("@"))
c := zoneAPITestRequest(server, f.actor, "record_update", zoneAPITestName, "1", recordETag(rows[0]), body)
resp := zoneAPITestStatus(t, t.Context(), c, 200)
zoneAPITestSerialOf(t, f.rows[0], newSOASerial(modelNow)+1)
if !strings.Contains(f.rows[0].Content.String, `"refresh":1800`) || resp.Header.Get("ETag") != recordETag(f.rows[0]) {
t.Fatalf("SOA row = %+v, response %+v", f.rows[0], resp)
}
zoneAPITestAuditIDs(t, c.Entry.Before, []int64{1})
zoneAPITestAuditIDs(t, c.Entry.After, []int64{1})
zoneAPITestPreserved(t, f, rows, 2, 3, 4)
c = zoneAPITestRequest(server, f.actor, "record_update", zoneAPITestName, "1", recordETag(f.rows[0]), body)
resp = zoneAPITestStatus(t, t.Context(), c, 200)
if c.Entry.Before != nil || c.Entry.After != nil || resp.Header.Get("ETag") != recordETag(f.rows[0]) {
t.Fatalf("unchanged SOA was written: %+v", c.Entry)
}
zoneAPITestSerialOf(t, f.rows[0], newSOASerial(modelNow)+1)
}
func TestZoneAPIUpdateRecordWithNullContent(t *testing.T) {
rows := zoneAPITestRows(t)
rows[2].Content = sql.NullString{}
f := zoneAPITestDBFor(t, rows)
server, _ := f.server()
body := `{"name":"first","type":"A","ttl":60,"data":{"ip":"192.0.2.1"}}`
c := zoneAPITestRequest(server, f.actor, "record_update", zoneAPITestName, "3", recordETag(rows[2]), body)
zoneAPITestStatus(t, t.Context(), c, 200)
if f.rows[2].Content.String != `{"ip":"192.0.2.1"}` || c.Entry.Before == nil || !strings.Contains(string(c.Entry.Before), `"content":null`) {
t.Fatalf("NULL content not replaced: %+v, %s", f.rows[2], c.Entry.Before)
}
}
func TestZoneAPIUpdateSOAAmbiguous(t *testing.T) {
rows := zoneAPITestRows(t)
extra := rows[0]
extra.ID = 5
extra.Content.String = strings.Replace(extra.Content.String, "ns.example.net.", "other.example.net.", 1)
rows = append(rows, extra)
for _, tc := range []struct {
name string
etag string
status int
}{
{"no ETag", "", 428},
{"ETag of no SOA", recordETag(rows[2]), 412},
{"ETag of the first SOA", recordETag(rows[0]), 422},
{"ETag of the second SOA", recordETag(extra), 422},
} {
t.Run(tc.name, func(t *testing.T) {
f := zoneAPITestDBFor(t, rows)
server, state := f.server()
c := zoneAPITestRequest(server, f.actor, "soa_update", zoneAPITestName, "", tc.etag, strings.Replace(zoneAPITestSOA, `"retry":600`, `"retry":700`, 1))
zoneAPITestStatus(t, t.Context(), c, tc.status)
if zoneAPIHasDataWrites(state) || !slices.Equal(f.rows, rows) {
t.Fatalf("ambiguous SOA update wrote data: %v", state.Queries())
}
if tc.status == 422 {
want := int64(1)
if tc.etag == recordETag(extra) {
want = 5
}
if c.Entry.RecordID.Int64 != want {
t.Fatalf("record id = %d, want %d", c.Entry.RecordID.Int64, want)
}
}
})
}
}
func TestZoneAPIFindSOA(t *testing.T) {
soa := func(id int64, name string) recordRow {
return recordRow{ID: id, Name: name, RecordType: "SOA"}
}
other := recordRow{ID: 9, RecordType: "NS"}
for _, tc := range []struct {
name string
rows []recordRow
want int64
}{
{"none", []recordRow{other}, 0},
{"apex", []recordRow{other, soa(3, "")}, 3},
{"non-apex only", []recordRow{other, soa(4, "below"), soa(5, "deeper")}, 4},
{"apex after non-apex", []recordRow{soa(4, "below"), soa(6, "")}, 6},
} {
if got := zoneAPIFindSOA(tc.rows); got.ID != tc.want {
t.Errorf("%s: SOA %d, want %d", tc.name, got.ID, tc.want)
}
if got := zoneAPISelectSOA(tc.rows, `"none"`); got.ID != tc.want {
t.Errorf("%s: selected SOA %d without a matching ETag, want %d", tc.name, got.ID, tc.want)
}
}
rows := []recordRow{soa(4, "below"), soa(6, "")}
if got := zoneAPISelectSOA(rows, recordETag(rows[0])); got.ID != 4 {
t.Fatalf("selected SOA %d, want 4", got.ID)
}
if view := zoneAPISOA(soa(4, "below"), modelNow); view != nil {
t.Fatalf("non-apex SOA summary = %+v", view)
}
}
func TestZoneAPIRecordUnchanged(t *testing.T) {
base := modelRawRow(3, "www", "A", 60, `{"ip":"192.0.2.1"}`)
with := func(edit func(*recordRow)) recordRow {
row := base
edit(&row)
return row
}
for _, tc := range []struct {
name string
current, proposed recordRow
want bool
}{
{"identical", base, base, true},
{"JSON column formatting", with(func(r *recordRow) { r.Content.String = `{"ip": "192.0.2.1"}` }), base, true},
{"NULL original", with(func(r *recordRow) { r.Content = sql.NullString{} }), base, false},
{"corrupt original", with(func(r *recordRow) { r.Content.String = `{"ip":` }), base, false},
{"array original", with(func(r *recordRow) { r.Content.String = `[]` }), base, false},
{"other value", with(func(r *recordRow) { r.Content.String = `{"ip":"192.0.2.2"}` }), base, false},
{"extra key", with(func(r *recordRow) { r.Content.String = `{"ip":"192.0.2.1","x":1}` }), base, false},
{"other TTL", with(func(r *recordRow) { r.TTL.Int64 = 61 }), base, false},
{"other zone spelling", with(func(r *recordRow) { r.Zone = "example.org" }), base, false},
{"other name with JSON column formatting", with(func(r *recordRow) { r.Name, r.Content.String = "web", `{"ip": "192.0.2.1"}` }), base, false},
} {
if got := zoneAPIRecordUnchanged(tc.current, tc.proposed); got != tc.want {
t.Errorf("%s: unchanged = %v, want %v", tc.name, got, tc.want)
}
}
}
func TestZoneAPIImportPreviewCountsSOAOnce(t *testing.T) {
rows := zoneAPITestRows(t)
f := zoneAPITestDBFor(t, rows)
server, _ := f.server()
content := "@ 3600 SOA ns.example.net. hostmaster.example.org. 1 3600 600 604800 900\n"
c := zoneAPITestRequest(server, f.actor, "zone_import_preview", zoneAPITestName, "", "", `{"mode":"merge","content":`+zoneAPITestJSON(t, content)+`}`)
resp := zoneAPITestStatus(t, t.Context(), c, 200)
preview := resp.Body.(zoneAPIImportPreview)
if len(preview.Added) != 0 || len(preview.Deleted) != 0 || len(preview.Updated) != 1 || preview.Updated[0].Type != "SOA" ||
preview.SOA == nil || preview.SOA.MinTTL != 900 || preview.Unchanged != 0 {
t.Fatalf("preview = %+v", preview)
}
body := `{"mode":"merge","content":` + zoneAPITestJSON(t, content) + `,"fingerprint":"` + zoneFingerprint(rows) + `"}`
c = zoneAPITestRequest(server, f.actor, "zone_import", zoneAPITestName, "", "", body)
resp = zoneAPITestStatus(t, t.Context(), c, 200)
if got := zoneAPITestJSON(t, resp.Body); got != `{"added":0,"deleted":0,"updated":1,"warnings":[]}` {
t.Fatalf("apply = %s", got)
}
zoneAPITestSerialOf(t, f.rows[0], newSOASerial(modelNow)+1)
zoneAPITestAuditIDs(t, c.Entry.After, []int64{1})
}
func TestZoneAPIImportInvalidFinalZone(t *testing.T) {
rows := zoneAPITestRows(t)
for _, tc := range []struct {
mode, content, fragment string
}{
{"merge", "first 60 CNAME target.example.net.\n", "an owner with a CNAME cannot have another record"},
{"merge", "@ 60 CNAME target.example.net.\n", "CNAME is not allowed at the apex"},
{"replace", "@ 3600 NS ns.example.net.\nother 60 A 192.0.2.1\n", ""},
{"merge", "@ SOA ns.example.net. hostmaster.example.org. 1 3600 600 604800 900\n@ SOA ns2.example.net. hostmaster.example.org. 1 3600 600 604800 900\n", "the zone file contains more than one SOA"},
} {
t.Run(tc.content, func(t *testing.T) {
f := zoneAPITestDBFor(t, rows)
server, state := f.server()
body := `{"mode":"` + tc.mode + `","content":` + zoneAPITestJSON(t, tc.content) + `,"fingerprint":"` + zoneFingerprint(rows) + `"}`
c := zoneAPITestRequest(server, f.actor, "zone_import", zoneAPITestName, "", "", body)
resp, err := zoneAPITestCall(t.Context(), c)
if tc.fragment == "" {
if err != nil || zoneAPITestJSON(t, resp.Body) != `{"added":1,"deleted":2,"updated":0,"warnings":[]}` {
t.Fatalf("valid replace = %+v, %v", resp, err)
}
return
}
var apiErr *apiError
if !errors.As(err, &apiErr) || apiErr.Status != 422 || !strings.Contains(zoneAPITestJSON(t, apiErr.Extra["errors"]), tc.fragment) {
t.Fatalf("error %#v, want %q", err, tc.fragment)
}
if zoneAPIHasDataWrites(state) {
t.Fatalf("invalid import wrote data: %v", state.Queries())
}
})
}
}
func TestZoneAPIRepairBlockedByBrokenSOA(t *testing.T) {
rows := zoneAPITestRows(t)
rows[0].Content.String = strings.Replace(rows[0].Content.String, `"refresh":3600`, `"refresh":"x"`, 1)
f := zoneAPITestDBFor(t, rows)
server, state := f.server()
c := zoneAPITestRequest(server, f.actor, "record_create", zoneAPITestName, "", "", zoneAPITestRecord)
_, err := zoneAPITestCall(t.Context(), c)
var apiErr *apiError
if !errors.As(err, &apiErr) || apiErr.Status != 422 || apiErr.Fields["type"] != "repair the SOA before changing other records" ||
zoneAPIHasDataWrites(state) {
t.Fatalf("error %#v, SQL %v", err, state.Queries())
}
c = zoneAPITestRequest(server, f.actor, "soa_update", zoneAPITestName, "", recordETag(rows[0]), zoneAPITestSOA)
zoneAPITestStatus(t, t.Context(), c, 200)
zoneAPITestSerialOf(t, f.rows[0], newSOASerial(modelNow)+1)
zoneAPITestStatus(t, t.Context(), zoneAPITestRequest(server, f.actor, "record_create", zoneAPITestName, "", "", zoneAPITestRecord), 201)
if id := strconv.FormatInt(f.rows[len(f.rows)-1].ID, 10); id != "5" {
t.Fatalf("created id %s", id)
}
}
func TestZoneAPIRepairApexCNAMEBeforeSOA(t *testing.T) {
for _, missing := range []bool{false, true} {
name := "non-apex SOA"
if missing {
name = "missing SOA"
}
t.Run(name, func(t *testing.T) {
rows := zoneAPITestRows(t)
rows[0].Name = "below"
if missing {
rows = rows[1:]
}
cname := modelRawRow(5, "", "CNAME", 60, `{"host":"target.example.net."}`)
f := zoneAPITestDBFor(t, append(slices.Clone(rows), cname))
server, state := f.server()
c := zoneAPITestRequest(server, f.actor, opRecordCreate, zoneAPITestName, "", "", zoneAPITestRecord)
zoneAPITestStatus(t, t.Context(), c, 422)
c = zoneAPITestRequest(server, f.actor, opRecordDelete, zoneAPITestName, "5", recordETag(cname), "")
zoneAPITestStatus(t, t.Context(), c, 200)
if state.commits != 1 || !c.auditDone || len(f.rows) != len(rows) {
t.Fatalf("CNAME repair did not commit exactly once: rows %+v, audit %+v", f.rows, c.Entry)
}
if missing {
zoneAPITestAuditIDs(t, c.Entry.Before, []int64{5})
zoneAPITestAuditIDs(t, c.Entry.After, nil)
c = zoneAPITestRequest(server, f.actor, opRecordCreate, zoneAPITestName, "", "", zoneAPITestSOARecord("@"))
zoneAPITestStatus(t, t.Context(), c, 201)
zoneAPITestSerialOf(t, zoneAPIFindSOA(f.rows), newSOASerial(modelNow))
} else {
zoneAPITestAuditIDs(t, c.Entry.Before, []int64{1, 5})
zoneAPITestAuditIDs(t, c.Entry.After, []int64{1})
zoneAPITestSerialOf(t, f.rows[0], newSOASerial(modelNow)+1)
c = zoneAPITestRequest(server, f.actor, opSOAUpdate, zoneAPITestName, "", recordETag(f.rows[0]), zoneAPITestSOA)
zoneAPITestStatus(t, t.Context(), c, 200)
zoneAPITestSerialOf(t, f.rows[0], newSOASerial(modelNow)+2)
}
zoneAPITestPreserved(t, f, rows, 2, 3, 4)
c = zoneAPITestRequest(server, f.actor, opZoneCheck, zoneAPITestName, "", "", "")
if got := zoneAPITestJSON(t, zoneAPITestStatus(t, t.Context(), c, 200).Body); got != `{"problems":[]}` {
t.Fatalf("zone after repair: %s", got)
}
})
}
}