- feat(api): add zone and record handlers - test(api): exercise zone handlers against mysql - fix(api): compute etags from stored rows
680 lines
30 KiB
Go
680 lines
30 KiB
Go
// SPDX-License-Identifier: GPL-2.0-or-later
|
|
// Copyright (C) 2026 Bryan Joshua Pedini
|
|
|
|
package main
|
|
|
|
import (
|
|
"context"
|
|
"database/sql"
|
|
"database/sql/driver"
|
|
"encoding/json"
|
|
"errors"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"slices"
|
|
"strconv"
|
|
"strings"
|
|
"testing"
|
|
)
|
|
|
|
const zoneAPITestName = "example.org."
|
|
const zoneAPITestSOA = `{"ns":"ns.example.net","mbox":"hostmaster@example.org","ttl":3600,"refresh":3600,"retry":600,"expire":604800,"minttl":300}`
|
|
|
|
var zoneAPITestCreate = `{"name":"Example.ORG","extra_ns":["backup.example.net"],` + zoneAPITestSOA[1:]
|
|
|
|
const zoneAPITestRecord = `{"name":"new","type":"A","ttl":60,"data":{"ip":"192.0.2.10"}}`
|
|
|
|
func zoneAPITestRequest(server *WebServer, actor userRow, operation, zone, id, etag, body string) *apiContext {
|
|
method := http.MethodGet
|
|
switch operation {
|
|
case "zone_create", "record_create", "record_bulk_delete", "zone_import_preview", "zone_import":
|
|
method = http.MethodPost
|
|
case "record_update", "soa_update":
|
|
method = http.MethodPut
|
|
case "zone_delete", "record_delete":
|
|
method = http.MethodDelete
|
|
}
|
|
req := httptest.NewRequest(method, "/api/v1/test", strings.NewReader(body))
|
|
if body != "" {
|
|
req.Header.Set("Content-Type", "application/json")
|
|
}
|
|
if etag != "" {
|
|
req.Header.Set("If-Match", etag)
|
|
}
|
|
entry := &auditEntry{
|
|
Time: modelNow, UserID: sql.NullInt64{Int64: actor.ID, Valid: true}, Actor: actor.Username,
|
|
Origin: "127.0.0.1", Operation: operation, Zone: sql.NullString{String: zone, Valid: zone != ""},
|
|
}
|
|
return &apiContext{
|
|
Request: req, Principal: principal{User: actor}, Zone: zone, Vars: map[string]string{"id": id},
|
|
Now: modelNow, Entry: entry, Server: server,
|
|
}
|
|
}
|
|
|
|
func zoneAPITestCall(ctx context.Context, c *apiContext) (apiResponse, error) {
|
|
return zoneAPIHandlers(c.Server)[c.Entry.Operation](ctx, c)
|
|
}
|
|
|
|
func zoneAPITestStatus(t *testing.T, ctx context.Context, c *apiContext, status int) apiResponse {
|
|
t.Helper()
|
|
resp, err := zoneAPITestCall(ctx, c)
|
|
if status >= 400 {
|
|
var apiErr *apiError
|
|
if !errors.As(err, &apiErr) || apiErr.Status != status {
|
|
t.Fatalf("%s: got response %+v, error %v, want %d", c.Entry.Operation, resp, err, status)
|
|
}
|
|
return resp
|
|
}
|
|
if err != nil || resp.Status != status {
|
|
t.Fatalf("%s: got response %+v, error %v, want %d", c.Entry.Operation, resp, err, status)
|
|
}
|
|
return resp
|
|
}
|
|
|
|
func zoneAPITestJSON(t *testing.T, value any) string {
|
|
t.Helper()
|
|
body, err := json.Marshal(value)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
return string(body)
|
|
}
|
|
|
|
func zoneAPITestRows(t *testing.T) []recordRow {
|
|
t.Helper()
|
|
rows, fields := newZoneRows(newZoneSpec{
|
|
Zone: zoneAPITestName, PrimaryNS: "ns.example.net", Mailbox: "hostmaster@example.org",
|
|
TTL: 3600, Refresh: 3600, Retry: 600, Expire: 604800, MinTTL: 300,
|
|
}, modelNow)
|
|
if len(fields) != 0 {
|
|
t.Fatal(fields)
|
|
}
|
|
for _, name := range []string{"first", "second"} {
|
|
row, fields := validateRecord(zoneAPITestName, name, "A", 60, []byte(`{"ip":"192.0.2.1"}`), modelNow)
|
|
if len(fields) != 0 {
|
|
t.Fatal(fields)
|
|
}
|
|
rows = append(rows, row)
|
|
}
|
|
for i := range rows {
|
|
rows[i].ID = int64(i + 1)
|
|
}
|
|
return rows
|
|
}
|
|
|
|
type zoneAPITestDB struct {
|
|
t *testing.T
|
|
rows []recordRow
|
|
foreign recordRow
|
|
actor userRow
|
|
hasActor bool
|
|
delegated bool
|
|
stale bool
|
|
locked bool
|
|
auditError error
|
|
writeError error
|
|
lastID int64
|
|
}
|
|
|
|
func zoneAPITestDBFor(t *testing.T, rows []recordRow) *zoneAPITestDB {
|
|
t.Helper()
|
|
return &zoneAPITestDB{
|
|
t: t, rows: slices.Clone(rows), actor: userRow{ID: 17, Username: "alice", Role: "admin"},
|
|
hasActor: true, delegated: true,
|
|
}
|
|
}
|
|
|
|
func zoneAPITestValues(row recordRow) []driver.Value {
|
|
ttl, _ := row.TTL.Value()
|
|
content, _ := row.Content.Value()
|
|
return []driver.Value{row.ID, row.Zone, row.Name, ttl, content, row.RecordType}
|
|
}
|
|
|
|
func (f *zoneAPITestDB) server() (*WebServer, *fdbState) {
|
|
for _, row := range f.rows {
|
|
f.lastID = max(f.lastID, row.ID)
|
|
}
|
|
db, state := newFakeDB(f.t, f.query)
|
|
return &WebServer{db: db, tables: fdbTables(f.t), log: discardLogger()}, state
|
|
}
|
|
|
|
func (f *zoneAPITestDB) query(query string, args []any) fdbResponse {
|
|
has := func(value string) bool { return strings.Contains(query, value) }
|
|
switch {
|
|
case has("GET_LOCK"):
|
|
if f.locked {
|
|
return fdbResponse{rows: fdbRow(int64(0))}
|
|
}
|
|
return fdbResponse{rows: fdbRow(int64(1))}
|
|
case has("RELEASE_LOCK"):
|
|
return fdbResponse{rows: fdbRow(int64(1))}
|
|
case has("SELECT u.") && has("FOR SHARE"):
|
|
if !f.hasActor {
|
|
return fdbResponse{}
|
|
}
|
|
deleted, _ := f.actor.DeletedAt.Value()
|
|
return fdbResponse{rows: fdbRow(f.actor.ID, f.actor.Username, f.actor.Role, "hash", modelNow, modelNow, nil, deleted)}
|
|
case has("SELECT 1 FROM") && has("zone_delegations") && has("FOR SHARE"):
|
|
if f.delegated {
|
|
return fdbResponse{rows: fdbRow(int64(1))}
|
|
}
|
|
return fdbResponse{}
|
|
case has("COUNT(*)") && has("GROUP BY"):
|
|
if len(f.rows) == 0 || has("WHERE r.") && !f.delegated {
|
|
return fdbResponse{}
|
|
}
|
|
var rows [][]driver.Value
|
|
soa := zoneAPIFindSOA(f.rows)
|
|
content, _ := soa.Content.Value()
|
|
rows = append(rows, []driver.Value{f.rows[0].Zone, int64(len(f.rows)), content})
|
|
if !has("WHERE r.") && f.foreign.ID != 0 {
|
|
rows = append(rows, []driver.Value{f.foreign.Zone, int64(1), nil})
|
|
}
|
|
return fdbResponse{rows: rows}
|
|
case has("SELECT d.") && has("FOR UPDATE OF d"):
|
|
if f.stale {
|
|
return fdbResponse{rows: fdbRow(args[0], int64(18), "bob", modelNow, f.actor.ID)}
|
|
}
|
|
return fdbResponse{}
|
|
case has("SELECT `id`") && has("WHERE `zone`"):
|
|
var rows [][]driver.Value
|
|
for _, row := range append(slices.Clone(f.rows), f.foreign) {
|
|
if row.Zone == args[0] {
|
|
rows = append(rows, zoneAPITestValues(row))
|
|
}
|
|
}
|
|
return fdbResponse{rows: rows}
|
|
case has("SELECT `id`") && has("WHERE `id`"):
|
|
if f.foreign.ID == args[0] {
|
|
return fdbResponse{rows: fdbRow(zoneAPITestValues(f.foreign)...)}
|
|
}
|
|
return fdbResponse{}
|
|
case has("INSERT INTO `coredns_webui_audit`"):
|
|
return fdbResponse{lastInsertID: 1, err: f.auditError}
|
|
case has("INSERT INTO `coredns_records`"):
|
|
f.lastID++
|
|
f.rows = append(f.rows, recordRow{
|
|
ID: f.lastID, Zone: args[0].(string), Name: args[1].(string), TTL: sql.NullInt64{Int64: args[2].(int64), Valid: true},
|
|
Content: sql.NullString{String: args[3].(string), Valid: true}, RecordType: args[4].(string),
|
|
})
|
|
return fdbResponse{lastInsertID: f.lastID, err: f.writeError}
|
|
case has("UPDATE `coredns_records`"):
|
|
if i := slices.IndexFunc(f.rows, func(row recordRow) bool { return row.ID == args[5] }); i >= 0 {
|
|
f.rows[i] = recordRow{
|
|
ID: args[5].(int64), Zone: args[0].(string), Name: args[1].(string), RecordType: args[4].(string),
|
|
TTL: sql.NullInt64{Int64: args[2].(int64), Valid: true}, Content: sql.NullString{String: args[3].(string), Valid: true},
|
|
}
|
|
}
|
|
return fdbResponse{rowsAffected: 1, err: f.writeError}
|
|
case has("DELETE FROM `coredns_records`"):
|
|
f.rows = slices.DeleteFunc(f.rows, func(row recordRow) bool {
|
|
return row.ID == args[0] || row.Zone == args[0]
|
|
})
|
|
return fdbResponse{rowsAffected: 1, err: f.writeError}
|
|
case has("DELETE FROM"):
|
|
return fdbResponse{rowsAffected: 1, err: f.writeError}
|
|
default:
|
|
f.t.Errorf("unexpected SQL: %s", query)
|
|
return fdbResponse{err: errors.New("unexpected SQL")}
|
|
}
|
|
}
|
|
|
|
func zoneAPITestingSQL(state *fdbState, contains string) []fdbCall {
|
|
var result []fdbCall
|
|
for _, call := range state.Calls() {
|
|
if strings.Contains(call.query, contains) {
|
|
result = append(result, call)
|
|
}
|
|
}
|
|
return result
|
|
}
|
|
|
|
func TestZoneAPIReadHandlers(t *testing.T) {
|
|
rows := zoneAPITestRows(t)
|
|
broken := recordRow{ID: 5, Zone: zoneAPITestName, Name: "bad", RecordType: "A", Content: sql.NullString{String: "{", Valid: true}}
|
|
f := zoneAPITestDBFor(t, append(rows, broken))
|
|
f.foreign = recordRow{ID: 90, Zone: "private.example.", RecordType: "unknown"}
|
|
server, state := f.server()
|
|
for _, tc := range []struct {
|
|
operation string
|
|
fragment string
|
|
}{
|
|
{"zone_list", `"records":5`},
|
|
{"zone_read", `"mbox":"hostmaster.example.org."`},
|
|
{"record_list", `"data":null,"raw":"{"`},
|
|
{"zone_check", `"zone":"example.org.","id":5,"name":"bad","type":"A"`},
|
|
{"check_all", `"zone":"private.example.","id":null,"name":null,"type":null`},
|
|
{"zone_export", ""},
|
|
} {
|
|
t.Run(tc.operation, func(t *testing.T) {
|
|
c := zoneAPITestRequest(server, f.actor, tc.operation, zoneAPITestName, "", "", "")
|
|
resp := zoneAPITestStatus(t, t.Context(), c, http.StatusOK)
|
|
if !strings.Contains(zoneAPITestJSON(t, resp.Body), tc.fragment) {
|
|
t.Fatalf("body = %s", zoneAPITestJSON(t, resp.Body))
|
|
}
|
|
if tc.operation == "zone_read" && resp.Header.Get("ETag") != recordETag(rows[0]) {
|
|
t.Fatalf("ETag = %q", resp.Header.Get("ETag"))
|
|
}
|
|
if tc.operation == "zone_export" && (resp.ContentType != "text/plain" ||
|
|
resp.Header.Get("Content-Disposition") != `attachment; filename="example.org.zone"` ||
|
|
!strings.HasPrefix(string(resp.Raw), "$ORIGIN example.org.\n") ||
|
|
!strings.Contains(string(resp.Raw), "; skipped id=5: ttl_null")) {
|
|
t.Fatalf("response = %+v, file %s", resp, resp.Raw)
|
|
}
|
|
if c.auditDone || c.Entry.Before != nil || c.Entry.After != nil {
|
|
t.Fatalf("read wrote change audit: %+v", c.Entry)
|
|
}
|
|
})
|
|
}
|
|
if len(zoneAPITestingSQL(state, "INSERT INTO")) != 0 {
|
|
t.Fatal("read wrote to the database")
|
|
}
|
|
user := userRow{ID: 17, Role: "user", Username: "alice"}
|
|
for _, operation := range []string{"zone_list", "check_all"} {
|
|
c := zoneAPITestRequest(server, user, operation, "", "", "", "")
|
|
resp := zoneAPITestStatus(t, t.Context(), c, http.StatusOK)
|
|
if encoded := zoneAPITestJSON(t, resp.Body); strings.Contains(encoded, "private.example.") || !strings.Contains(encoded, zoneAPITestName) {
|
|
t.Fatalf("visibility: %s", encoded)
|
|
}
|
|
}
|
|
f.delegated = false
|
|
for _, operation := range []string{"zone_list", "check_all"} {
|
|
c := zoneAPITestRequest(server, user, operation, "", "", "", "")
|
|
resp := zoneAPITestStatus(t, t.Context(), c, http.StatusOK)
|
|
if encoded := zoneAPITestJSON(t, resp.Body); !strings.HasSuffix(encoded, "[]}") {
|
|
t.Fatalf("empty visibility: %s", encoded)
|
|
}
|
|
}
|
|
for _, zone := range []string{"missing.example.", zoneAPITestName} {
|
|
f.rows = nil
|
|
c := zoneAPITestRequest(server, f.actor, "zone_read", zone, "", "", "")
|
|
_, err := zoneAPITestCall(t.Context(), c)
|
|
if e, ok := err.(*apiError); !ok || e.Status != 404 || e.Message != "zone not found" {
|
|
t.Fatalf("absent zone: %v", err)
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestZoneAPIWriteHandlers(t *testing.T) {
|
|
rows := zoneAPITestRows(t)
|
|
bulk := zoneAPITestJSON(t, map[string]any{"records": []map[string]any{
|
|
{"id": 3, "etag": recordETag(rows[2])}, {"id": 4, "etag": recordETag(rows[3])},
|
|
}})
|
|
for _, tc := range []struct {
|
|
operation string
|
|
id string
|
|
etag string
|
|
body string
|
|
status int
|
|
before, after []int64
|
|
recordID int64
|
|
serial bool
|
|
}{
|
|
{"zone_create", "", "", zoneAPITestCreate, 201, nil, []int64{1, 2, 3}, 0, false},
|
|
{"zone_delete", "", "", `{"confirm":"EXAMPLE.ORG"}`, 204, []int64{1, 2, 3, 4}, nil, 0, false},
|
|
{"record_create", "", "", zoneAPITestRecord, 201, []int64{1}, []int64{1, 5}, 5, true},
|
|
{"record_update", "3", recordETag(rows[2]), zoneAPITestRecord, 200, []int64{1, 3}, []int64{1, 3}, 3, true},
|
|
{"record_delete", "3", recordETag(rows[2]), "", 204, []int64{1, 3}, []int64{1}, 3, true},
|
|
{"record_bulk_delete", "", "", bulk, 200, []int64{1, 3, 4}, []int64{1}, 0, true},
|
|
{"soa_update", "", recordETag(rows[0]), strings.Replace(zoneAPITestSOA, "3600", "1500", 1), 200, []int64{1}, []int64{1}, 1, true},
|
|
} {
|
|
t.Run(tc.operation, func(t *testing.T) {
|
|
f := zoneAPITestDBFor(t, slices.Clone(rows))
|
|
f.stale = tc.operation == "zone_create" || tc.operation == "zone_delete"
|
|
zone := zoneAPITestName
|
|
if tc.operation == "zone_create" {
|
|
f.rows, zone = nil, ""
|
|
}
|
|
server, state := f.server()
|
|
c := zoneAPITestRequest(server, f.actor, tc.operation, zone, tc.id, tc.etag, tc.body)
|
|
resp := zoneAPITestStatus(t, t.Context(), c, tc.status)
|
|
audits := zoneAPITestingSQL(state, "INSERT INTO `coredns_webui_audit`")
|
|
if len(audits) != 1 || state.commits != 1 || state.rollbacks != 0 || !c.auditDone ||
|
|
c.Entry.RecordID.Int64 != tc.recordID || c.Entry.RecordID.Valid != (tc.recordID != 0) ||
|
|
audits[0].args[5] != int64(tc.status) || audits[0].args[7] != zoneAPITestName {
|
|
t.Fatalf("change audit = %+v, record ID %+v, commits %d, rollbacks %d", audits, c.Entry.RecordID, state.commits, state.rollbacks)
|
|
}
|
|
zoneAPITestAuditIDs(t, c.Entry.Before, tc.before)
|
|
zoneAPITestAuditIDs(t, c.Entry.After, tc.after)
|
|
if f.stale && (!strings.Contains(string(c.Entry.Before)+string(c.Entry.After), `{"zone":"example.org.","username":"bob"}`) ||
|
|
len(zoneAPITestingSQL(state, "DELETE FROM `coredns_webui_zone_delegations`")) != 1) {
|
|
t.Fatal("delegation cleanup is missing")
|
|
}
|
|
if tc.serial {
|
|
var serials []uint32
|
|
for _, update := range zoneAPITestingSQL(state, "UPDATE `coredns_records`") {
|
|
if update.args[4] == "SOA" {
|
|
row := recordRow{Content: sql.NullString{String: update.args[3].(string), Valid: true}}
|
|
serial, _ := storedSOASerial(row)
|
|
serials = append(serials, serial)
|
|
}
|
|
}
|
|
if !slices.Equal(serials, []uint32{newSOASerial(modelNow) + 1}) {
|
|
t.Fatalf("serials = %v", serials)
|
|
}
|
|
}
|
|
if tc.status != 204 && tc.operation != "record_bulk_delete" && resp.Header.Get("ETag") == "" {
|
|
t.Fatal("missing response ETag")
|
|
}
|
|
calls := state.Queries()
|
|
if !strings.Contains(calls[0], "GET_LOCK") || !strings.HasSuffix(calls[1], "FOR SHARE") ||
|
|
!strings.HasSuffix(calls[2], "FOR UPDATE") || !strings.Contains(calls[len(calls)-2], "INSERT INTO `coredns_webui_audit`") ||
|
|
!strings.Contains(calls[len(calls)-1], "RELEASE_LOCK") {
|
|
t.Fatalf("write query order: %v", calls)
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
func zoneAPITestAuditIDs(t *testing.T, body []byte, want []int64) {
|
|
t.Helper()
|
|
if want == nil {
|
|
if body != nil {
|
|
t.Fatalf("audit = %s, want SQL NULL", body)
|
|
}
|
|
return
|
|
}
|
|
var objects []map[string]json.RawMessage
|
|
if len(body) > 0 && body[0] == '{' {
|
|
body = append(append([]byte{'['}, body...), ']')
|
|
}
|
|
if err := json.Unmarshal(body, &objects); err != nil {
|
|
t.Fatalf("audit %s: %v", body, err)
|
|
}
|
|
var ids []int64
|
|
for _, object := range objects {
|
|
id, record := object["id"]
|
|
if !record {
|
|
continue
|
|
}
|
|
var idValue int64
|
|
if err := json.Unmarshal(id, &idValue); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if _, ok := object["record_type"]; !ok || len(object) != 6 || object["ttl"] == nil || object["content"] == nil || object["zone"] == nil || object["name"] == nil {
|
|
t.Fatalf("unexpected record audit fields: %v", object)
|
|
}
|
|
ids = append(ids, idValue)
|
|
}
|
|
if !slices.Equal(ids, want) {
|
|
t.Fatalf("audit ids = %v, want %v; values %s", ids, want, body)
|
|
}
|
|
}
|
|
|
|
func TestZoneAPIWriteRefusals(t *testing.T) {
|
|
rows := zoneAPITestRows(t)
|
|
padded := `{"content":"` + strings.Repeat("x", zoneFileMaxBytes) + `","mode":"merge"}`
|
|
for _, tc := range []struct {
|
|
operation string
|
|
id string
|
|
etag string
|
|
body string
|
|
status int
|
|
field string
|
|
setup func(*zoneAPITestDB, *apiContext)
|
|
}{
|
|
{operation: "zone_create", status: 409, body: zoneAPITestCreate},
|
|
{operation: "zone_create", status: 403, body: zoneAPITestCreate, setup: func(_ *zoneAPITestDB, c *apiContext) { c.Principal.User.Role = "user" }},
|
|
{operation: "zone_delete", status: 403, body: `{"confirm":"example.org"}`, setup: func(_ *zoneAPITestDB, c *apiContext) { c.Principal.User.Role = "user" }},
|
|
{operation: "zone_create", status: 422, field: "name", body: `{"name":".."}`},
|
|
{operation: "zone_create", status: 422, field: "extra_ns", body: strings.Replace(zoneAPITestCreate, "backup.example.net", "ns.example.net.", 1), setup: func(f *zoneAPITestDB, _ *apiContext) { f.rows = nil }},
|
|
{operation: "zone_create", status: 422, field: "mbox", body: strings.Replace(zoneAPITestCreate, "hostmaster@example.org", "bad mailbox", 1), setup: func(f *zoneAPITestDB, _ *apiContext) { f.rows = nil }},
|
|
{operation: "zone_create", status: 422, field: "ttl", body: strings.Replace(zoneAPITestCreate, `"ttl":3600`, `"ttl":"3600"`, 1), setup: func(f *zoneAPITestDB, _ *apiContext) { f.rows = nil }},
|
|
{operation: "zone_delete", status: 422, field: "confirm", body: `{"confirm":"different.example"}`},
|
|
{operation: "zone_delete", status: 404, body: `{"confirm":"example.org"}`, setup: func(f *zoneAPITestDB, _ *apiContext) { f.rows = nil }},
|
|
{operation: "record_create", status: 422, field: "data.ip", body: `{"name":"new","type":"A","ttl":60,"data":{"ip":"::1"}}`},
|
|
{operation: "record_create", status: 422, field: "name", body: `{"name":"elsewhere.example.","type":"A","ttl":60,"data":{"ip":"192.0.2.1"}}`},
|
|
{operation: "record_create", status: 422, field: "type", body: `{"name":"new","type":"NONE","ttl":60,"data":{}}`},
|
|
{operation: "record_create", status: 422, field: "name", body: `{"name":"first","type":"A","ttl":61,"data":{"ip":"192.0.2.1"}}`},
|
|
{operation: "record_create", status: 422, field: "data.preference", body: `{"name":"new","type":"MX","ttl":60,"data":{"host":"mx.example","preference":"10"}}`},
|
|
{operation: "record_create", status: 422, field: "ttl", body: `{"name":"new","type":"A","ttl":"60","data":{"ip":"192.0.2.1"}}`},
|
|
{operation: "record_create", status: 400, body: `{"unknown":true}`},
|
|
{operation: "record_create", status: 400, body: zoneAPITestRecord + "{}"},
|
|
{operation: "record_create", status: 415, body: zoneAPITestRecord, setup: func(_ *zoneAPITestDB, c *apiContext) { c.Request.Header.Del("Content-Type") }},
|
|
{operation: "record_create", status: 413, body: `{"data":"` + strings.Repeat("x", 64<<10) + `"}`},
|
|
{operation: "record_create", status: 503, body: zoneAPITestRecord, setup: func(f *zoneAPITestDB, _ *apiContext) { f.locked = true }},
|
|
{operation: "record_create", status: 404, body: zoneAPITestRecord, setup: func(f *zoneAPITestDB, c *apiContext) {
|
|
f.actor.Role, c.Principal.User.Role, f.delegated = "user", "user", false
|
|
}},
|
|
{operation: "record_create", status: 404, body: zoneAPITestRecord, setup: func(f *zoneAPITestDB, _ *apiContext) { f.hasActor = false }},
|
|
{operation: "record_create", status: 404, body: zoneAPITestRecord, setup: func(f *zoneAPITestDB, _ *apiContext) { f.actor.DeletedAt = sql.NullTime{Time: modelNow, Valid: true} }},
|
|
{operation: "record_create", status: 404, body: zoneAPITestRecord, setup: func(f *zoneAPITestDB, _ *apiContext) { f.actor.Role = "user" }},
|
|
{operation: "record_update", id: "3", status: 428, body: zoneAPITestRecord},
|
|
{operation: "record_update", id: "3", status: 412, etag: `"old"`, body: zoneAPITestRecord},
|
|
{operation: "record_update", id: "99", status: 412, etag: `"old"`, body: zoneAPITestRecord},
|
|
{operation: "record_update", id: "wrong", status: 400, etag: `"old"`, body: zoneAPITestRecord},
|
|
{operation: "record_update", id: "2147483648", status: 400, etag: `"old"`, body: zoneAPITestRecord},
|
|
{operation: "record_update", id: "90", status: 404, etag: `"old"`, body: zoneAPITestRecord},
|
|
{operation: "record_delete", id: "3", status: 428},
|
|
{operation: "record_delete", id: "3", status: 412, etag: "*"},
|
|
{operation: "record_delete", id: "90", status: 404, etag: `"old"`},
|
|
{operation: "record_delete", id: "1", status: 422, field: "type", etag: recordETag(rows[0])},
|
|
{operation: "record_delete", id: "2", status: 422, field: "type", etag: recordETag(rows[1])},
|
|
{operation: "record_bulk_delete", status: 412, body: `{"records":[{"id":3,"etag":` + zoneAPITestJSON(t, recordETag(rows[2])) + `},{"id":4,"etag":"old"}]}`},
|
|
{operation: "record_bulk_delete", status: 422, field: "records", body: `{"records":[]}`},
|
|
{operation: "record_bulk_delete", status: 422, field: "records", body: `{"records":[{"id":"3","etag":"old"}]}`},
|
|
{operation: "record_bulk_delete", status: 404, body: `{"records":[{"id":90,"etag":"old"}]}`},
|
|
{operation: "soa_update", status: 428, body: zoneAPITestSOA},
|
|
{operation: "soa_update", status: 412, etag: `"old"`, body: zoneAPITestSOA},
|
|
{operation: "soa_update", status: 412, etag: recordETag(rows[0]), body: zoneAPITestSOA, setup: func(f *zoneAPITestDB, _ *apiContext) { f.rows = f.rows[1:] }},
|
|
{operation: "soa_update", status: 422, field: "refresh", etag: recordETag(rows[0]), body: strings.Replace(zoneAPITestSOA, `"refresh":3600`, `"refresh":"3600"`, 1)},
|
|
{operation: "soa_update", status: 422, field: "mbox", etag: recordETag(rows[0]), body: strings.Replace(zoneAPITestSOA, "hostmaster@example.org", "@example.org", 1)},
|
|
{operation: "zone_import_preview", status: 413, body: padded},
|
|
{operation: "zone_import", status: 413, body: padded},
|
|
{operation: "zone_import", status: 409, body: `{"mode":"merge","content":"","fingerprint":"stale"}`},
|
|
{operation: "zone_import_preview", status: 422, field: "mode", body: `{"mode":"invalid","content":""}`},
|
|
} {
|
|
t.Run(tc.operation+"/"+strconv.Itoa(tc.status)+"/"+tc.field, func(t *testing.T) {
|
|
f := zoneAPITestDBFor(t, slices.Clone(rows))
|
|
f.foreign = recordRow{ID: 90, Zone: "private.example.", RecordType: "TXT"}
|
|
server, state := f.server()
|
|
c := zoneAPITestRequest(server, f.actor, tc.operation, zoneAPITestName, tc.id, tc.etag, tc.body)
|
|
if tc.setup != nil {
|
|
tc.setup(f, c)
|
|
}
|
|
_, err := zoneAPITestCall(t.Context(), c)
|
|
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, field %q", err, tc.status, tc.field)
|
|
}
|
|
if tc.status == 503 && apiErr.Message != "zone busy" {
|
|
t.Fatalf("busy error = %q", apiErr.Message)
|
|
}
|
|
if c.auditDone || c.Entry.Before != nil || c.Entry.After != nil ||
|
|
len(zoneAPITestingSQL(state, "INSERT INTO"))+len(zoneAPITestingSQL(state, "UPDATE `"))+len(zoneAPITestingSQL(state, "DELETE FROM")) != 0 {
|
|
t.Fatalf("refusal wrote data: %+v, queries %v", c.Entry, state.Queries())
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
func TestZoneAPIWarningsAndSerialModes(t *testing.T) {
|
|
rows := zoneAPITestRows(t)
|
|
var err error
|
|
rows[0], err = withSOASerial(rows[0], 0, false)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
f := zoneAPITestDBFor(t, rows)
|
|
f.actor.Role = "user"
|
|
server, state := f.server()
|
|
body := `{"name":"new","type":"MX","ttl":60,"data":{"host":"missing.example.org.","preference":10}}`
|
|
c := zoneAPITestRequest(server, f.actor, "record_create", zoneAPITestName, "", "", body)
|
|
resp := zoneAPITestStatus(t, t.Context(), c, 201)
|
|
if !strings.Contains(zoneAPITestJSON(t, resp.Body), "target_no_address") ||
|
|
len(zoneAPITestingSQL(state, "UPDATE `coredns_records`")) != 0 ||
|
|
len(zoneAPITestingSQL(state, "zone_delegations` WHERE `zone` = ? AND `user_id` = ? FOR SHARE")) != 1 {
|
|
t.Fatalf("response = %+v, SQL = %v", resp, state.Queries())
|
|
}
|
|
c = zoneAPITestRequest(server, f.actor, "soa_update", zoneAPITestName, "", recordETag(rows[0]), zoneAPITestSOA)
|
|
resp = zoneAPITestStatus(t, t.Context(), c, 200)
|
|
if c.auditDone || c.Entry.Before != nil || c.Entry.After != nil ||
|
|
resp.Header.Get("ETag") != recordETag(rows[0]) || !strings.Contains(zoneAPITestJSON(t, resp.Body), `"serial":null`) {
|
|
t.Fatalf("unexpected SOA no-op: %+v, %s", c.Entry, zoneAPITestJSON(t, resp.Body))
|
|
}
|
|
c = zoneAPITestRequest(server, f.actor, "soa_update", zoneAPITestName, "", recordETag(rows[0]), `{"managed_serial":true,`+zoneAPITestSOA[1:])
|
|
resp = zoneAPITestStatus(t, t.Context(), c, 200)
|
|
if !c.auditDone || !strings.Contains(zoneAPITestJSON(t, resp.Body), `"serial":`+strconv.FormatUint(uint64(newSOASerial(modelNow)), 10)) ||
|
|
len(zoneAPITestingSQL(state, "UPDATE `coredns_records`")) != 1 {
|
|
t.Fatalf("SOA managed update: %+v, %s, SQL = %v", c.Entry, zoneAPITestJSON(t, resp.Body), state.Queries())
|
|
}
|
|
}
|
|
|
|
func TestZoneAPISOAFieldNames(t *testing.T) {
|
|
for _, field := range []string{"ns", "mbox", "ttl", "refresh", "retry", "expire", "minttl"} {
|
|
for _, operation := range []string{"zone_create", "soa_update"} {
|
|
t.Run(operation+"/"+field, func(t *testing.T) {
|
|
rows := zoneAPITestRows(t)
|
|
f := zoneAPITestDBFor(t, rows)
|
|
var body map[string]any
|
|
input, zone, etag := zoneAPITestSOA, zoneAPITestName, recordETag(rows[0])
|
|
if operation == "zone_create" {
|
|
f.rows, input, zone, etag = nil, zoneAPITestCreate, "", ""
|
|
}
|
|
if err := json.Unmarshal([]byte(input), &body); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
body[field] = "invalid field"
|
|
server, state := f.server()
|
|
c := zoneAPITestRequest(server, f.actor, operation, zone, "", etag, zoneAPITestJSON(t, body))
|
|
_, err := zoneAPITestCall(t.Context(), c)
|
|
var invalid *apiError
|
|
if !errors.As(err, &invalid) || invalid.Status != 422 || len(invalid.Fields) != 1 || invalid.Fields[field] == "" {
|
|
t.Fatalf("field %q: error %+v", field, err)
|
|
}
|
|
if c.auditDone || len(zoneAPITestingSQL(state, "INSERT INTO")) != 0 || len(zoneAPITestingSQL(state, "UPDATE `")) != 0 {
|
|
t.Fatalf("invalid field wrote data: %v", state.Queries())
|
|
}
|
|
})
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestZoneAPIRollback(t *testing.T) {
|
|
for _, failAt := range []string{"write", "audit", "commit"} {
|
|
t.Run(failAt, func(t *testing.T) {
|
|
f := zoneAPITestDBFor(t, zoneAPITestRows(t))
|
|
failure := errors.New(failAt + " failed")
|
|
server, state := f.server()
|
|
switch failAt {
|
|
case "write":
|
|
f.writeError = failure
|
|
case "audit":
|
|
f.auditError = failure
|
|
case "commit":
|
|
state.commitErr = failure
|
|
}
|
|
c := zoneAPITestRequest(server, f.actor, "record_create", zoneAPITestName, "", "", zoneAPITestRecord)
|
|
resp, err := zoneAPITestCall(t.Context(), c)
|
|
if !errors.Is(err, failure) || resp.Status != 0 || c.auditDone || c.Entry.Before != nil || c.Entry.After != nil ||
|
|
state.commits != 0 || (failAt != "commit" && state.rollbacks != 1) ||
|
|
!strings.Contains(state.Queries()[len(state.Queries())-1], "RELEASE_LOCK") {
|
|
t.Fatalf("response %+v, err %v, audit %+v, SQL %v", resp, err, c.Entry, state.Queries())
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
func TestZoneAPIImport(t *testing.T) {
|
|
rows := zoneAPITestRows(t)
|
|
f := zoneAPITestDBFor(t, rows)
|
|
server, state := f.server()
|
|
content := "$ORIGIN example.org.\nfirst 180 A 192.0.2.1\nlast TXT \"one\" \"two\"\nother PTR ptr.example.net.\n" +
|
|
"@ SOA ns.example.net. hostmaster.example.org. 99 3600 600 604800 600\n" +
|
|
"@ 3600 NS ns.example.net.\n"
|
|
makeBody := func(content string, apply bool) string {
|
|
body := map[string]any{"mode": "replace", "content": content}
|
|
if apply {
|
|
body["fingerprint"] = zoneFingerprint(f.rows)
|
|
}
|
|
return zoneAPITestJSON(t, body)
|
|
}
|
|
c := zoneAPITestRequest(server, f.actor, "zone_import_preview", zoneAPITestName, "", "", makeBody(content, false))
|
|
resp := zoneAPITestStatus(t, t.Context(), c, 200)
|
|
for _, fragment := range []string{`"fingerprint":"` + zoneFingerprint(rows), `"old_ttl":60`,
|
|
`"name":"last","type":"TXT","ttl":3600,"value":"onetwo"`, `"minttl":600`, `"line":4,"text":`, `"line":3,"message":"TXT strings`} {
|
|
if encoded := zoneAPITestJSON(t, resp.Body); !strings.Contains(encoded, fragment) {
|
|
t.Fatalf("missing %q in %s", fragment, encoded)
|
|
}
|
|
}
|
|
c = zoneAPITestRequest(server, f.actor, "zone_import", zoneAPITestName, "", "", makeBody(content, true))
|
|
resp = zoneAPITestStatus(t, t.Context(), c, 200)
|
|
if zoneAPITestJSON(t, resp.Body) != `{"added":1,"deleted":1,"updated":2}` {
|
|
t.Fatalf("apply response = %s", zoneAPITestJSON(t, resp.Body))
|
|
}
|
|
zoneAPITestAuditIDs(t, c.Entry.Before, []int64{1, 3, 4})
|
|
zoneAPITestAuditIDs(t, c.Entry.After, []int64{1, 3, 5})
|
|
updates := zoneAPITestingSQL(state, "UPDATE `coredns_records`")
|
|
if len(updates) != 2 || updates[0].args[4] != "SOA" || !strings.Contains(updates[0].args[3].(string), strconv.FormatUint(uint64(newSOASerial(modelNow)+1), 10)) ||
|
|
len(zoneAPITestingSQL(state, "INSERT INTO `coredns_webui_audit`")) != 1 {
|
|
t.Fatalf("incorrect import SQL: %v", state.Calls())
|
|
}
|
|
for _, tc := range []struct {
|
|
content string
|
|
fragment string
|
|
}{
|
|
{"\n; comment\nother.example. A 192.0.2.1\n", `"line":3,"message":"record has an owner outside the zone"`},
|
|
{"\n; comment\nwww A not-an-address\n", `"line":3,"message":`},
|
|
{"\n; comment\nwww AAAA ::ffff:192.0.2.1\n", `"line":3,"message":"ip:`},
|
|
{"$INCLUDE ignored\n", `"line":1,"message":`},
|
|
{"", "last apex NS"},
|
|
} {
|
|
for _, operation := range []string{"zone_import_preview", "zone_import"} {
|
|
c := zoneAPITestRequest(server, f.actor, operation, zoneAPITestName, "", "", makeBody(tc.content, operation == "zone_import"))
|
|
_, err := zoneAPITestCall(t.Context(), c)
|
|
var apiErr *apiError
|
|
if !errors.As(err, &apiErr) || apiErr.Status != 422 || apiErr.Message != "the file has errors" ||
|
|
!strings.Contains(zoneAPITestJSON(t, apiErr.Extra["errors"]), tc.fragment) {
|
|
t.Fatalf("%q yielded %#v, expected %q", tc.content, err, tc.fragment)
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestZoneAPIAbsence(t *testing.T) {
|
|
for _, operation := range []string{
|
|
"zone_read", "zone_delete", "record_list", "record_create", "record_update", "record_delete",
|
|
"record_bulk_delete", "soa_update", "zone_check", "zone_export", "zone_import_preview", "zone_import",
|
|
} {
|
|
t.Run(operation, func(t *testing.T) {
|
|
f := zoneAPITestDBFor(t, nil)
|
|
server, _ := f.server()
|
|
c := zoneAPITestRequest(server, f.actor, operation, zoneAPITestName, "1", "", "")
|
|
_, err := zoneAPITestCall(t.Context(), c)
|
|
if e, ok := err.(*apiError); !ok || e.Status != 404 || e.Message != "zone not found" {
|
|
t.Fatalf("absent zone: %v", err)
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
func TestZoneAPIUnreadableSOA(t *testing.T) {
|
|
rows := zoneAPITestRows(t)
|
|
rows[0].Content = sql.NullString{String: "{", Valid: true}
|
|
f := zoneAPITestDBFor(t, rows)
|
|
server, _ := f.server()
|
|
c := zoneAPITestRequest(server, f.actor, "zone_read", zoneAPITestName, "", "", "")
|
|
resp := zoneAPITestStatus(t, t.Context(), c, 200)
|
|
if resp.Header.Get("ETag") != "" || !strings.Contains(zoneAPITestJSON(t, resp.Body), `"serial":null,"soa":null`) {
|
|
t.Fatalf("broken SOA summary = %+v", resp)
|
|
}
|
|
c = zoneAPITestRequest(server, f.actor, "soa_update", zoneAPITestName, "", recordETag(rows[0]), zoneAPITestSOA)
|
|
resp = zoneAPITestStatus(t, t.Context(), c, 200)
|
|
if resp.Header.Get("ETag") == "" || resp.Header.Get("ETag") == recordETag(rows[0]) || !c.auditDone {
|
|
t.Fatalf("SOA was not repaired: %+v", resp)
|
|
}
|
|
}
|
|
|
|
func TestZoneAPIReadErrors(t *testing.T) {
|
|
failure := errors.New("database read failed")
|
|
db, _ := newFakeDB(t, func(string, []any) fdbResponse { return fdbResponse{err: failure} })
|
|
server := &WebServer{db: db, tables: fdbTables(t), log: discardLogger()}
|
|
for _, operation := range []string{"zone_list", "zone_read", "record_list", "zone_check", "check_all", "zone_export", "zone_import_preview", "record_create"} {
|
|
c := zoneAPITestRequest(server, userRow{ID: 17, Role: "admin"}, operation, zoneAPITestName, "", "", "")
|
|
_, err := zoneAPITestCall(t.Context(), c)
|
|
if !errors.Is(err, failure) {
|
|
t.Errorf("%s = %v", operation, err)
|
|
}
|
|
}
|
|
}
|