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
This commit is contained in:
1 parent
53444bec7a
commit
a7ba01fc77
21 files changed
+1310
-165
No files matched your search
@@ -4,7 +4,9 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"cmp"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"maps"
|
||||
"slices"
|
||||
"strings"
|
||||
@@ -102,7 +104,7 @@ func checkRecord(row recordRow, now time.Time) []zoneProblem {
|
||||
if soa, ok := decoded.data.(soaData); ok && soa.Serial == 0 && fields["serial"] == "" {
|
||||
warn("soa_dynamic_serial", "SOA uses a dynamic Unix time serial")
|
||||
}
|
||||
if canonical, _ := encodeRecord(normalized); len(fields) == 0 && canonical != row.Content.String {
|
||||
if canonical, _ := encodeRecord(normalized); len(fields) == 0 && !canonicalContent(row.Content.String, canonical) {
|
||||
warn("content_not_canonical", "stored content differs from its canonical form")
|
||||
}
|
||||
if decoded.decodeErr == nil && row.TTL.Valid && row.TTL.Int64 >= 0 && row.TTL.Int64 <= int64(^uint32(0)) {
|
||||
@@ -114,6 +116,60 @@ func checkRecord(row recordRow, now time.Time) []zoneProblem {
|
||||
return problems
|
||||
}
|
||||
|
||||
type contentMember struct {
|
||||
key string
|
||||
value any
|
||||
}
|
||||
|
||||
func contentMembers(content string) ([]contentMember, bool) {
|
||||
decoder := json.NewDecoder(strings.NewReader(content))
|
||||
decoder.UseNumber()
|
||||
if token, err := decoder.Token(); err != nil || token != json.Delim('{') {
|
||||
return nil, false
|
||||
}
|
||||
var members []contentMember
|
||||
for decoder.More() {
|
||||
key, err := decoder.Token()
|
||||
if err != nil {
|
||||
return nil, false
|
||||
}
|
||||
value, err := decoder.Token()
|
||||
if err != nil {
|
||||
return nil, false
|
||||
}
|
||||
if _, nested := value.(json.Delim); nested {
|
||||
return nil, false
|
||||
}
|
||||
members = append(members, contentMember{key.(string), value})
|
||||
}
|
||||
if _, err := decoder.Token(); err != nil {
|
||||
return nil, false
|
||||
}
|
||||
if _, err := decoder.Token(); err != io.EOF {
|
||||
return nil, false
|
||||
}
|
||||
return members, true
|
||||
}
|
||||
|
||||
func canonicalContent(stored, canonical string) bool {
|
||||
if stored == canonical {
|
||||
return true
|
||||
}
|
||||
have, ok := contentMembers(stored)
|
||||
want, _ := contentMembers(canonical)
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
if last := len(want) - 1; last >= 0 && want[last].key == "serial" && want[last].value == json.Number("0") &&
|
||||
!slices.ContainsFunc(have, func(m contentMember) bool { return m.key == "serial" }) {
|
||||
want = want[:last]
|
||||
}
|
||||
mysqlOrder := slices.SortedStableFunc(slices.Values(want), func(a, b contentMember) int {
|
||||
return cmp.Or(cmp.Compare(len(a.key), len(b.key)), strings.Compare(a.key, b.key))
|
||||
})
|
||||
return slices.Equal(have, want) || slices.Equal(have, mysqlOrder)
|
||||
}
|
||||
|
||||
func hasContentKey(object map[string]json.RawMessage, key string) bool {
|
||||
for name := range object {
|
||||
if strings.EqualFold(name, key) {
|
||||
|
||||
+136
@@ -4,6 +4,7 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"cmp"
|
||||
"database/sql"
|
||||
"slices"
|
||||
"strings"
|
||||
@@ -111,3 +112,138 @@ func TestCheckMixedBrokenRows(t *testing.T) {
|
||||
t.Fatalf("reported problems for good rows: %+v", problems)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCheckCanonicalContentStorage(t *testing.T) {
|
||||
soaJSONColumn := `{"ns": "ns.example.net.", "MBox": "hostmaster.example.org.", "retry": 600, "expire": 604800, "minttl": 300, "serial": 2026111800, "refresh": 3600}`
|
||||
for _, tc := range []struct {
|
||||
name, recordType, content string
|
||||
codes []string
|
||||
}{
|
||||
{"text canonical", "A", `{"ip":"192.0.2.1"}`, nil},
|
||||
{"json column spacing", "A", `{"ip": "192.0.2.1"}`, nil},
|
||||
{"text whitespace", "A", "{ \"ip\" :\n\"192.0.2.1\" }", nil},
|
||||
{"extra key", "A", `{"ip": "192.0.2.1", "x": 1}`, []string{"content_not_canonical"}},
|
||||
{"duplicate key", "A", `{"ip":"192.0.2.1","ip":"192.0.2.1"}`, []string{"content_not_canonical"}},
|
||||
{"json column MX", "MX", `{"host": "mx.example.org.", "preference": 10}`, []string{"target_no_address"}},
|
||||
{"reordered MX", "MX", `{"preference":10,"host":"mx.example.org."}`, []string{"content_not_canonical", "target_no_address"}},
|
||||
{"json column SRV", "SRV", `{"port": 443, "target": ".", "weight": 5, "priority": 10}`, nil},
|
||||
{"text canonical SOA", "SOA", modelSOAContent, nil},
|
||||
{"json column SOA", "SOA", soaJSONColumn, nil},
|
||||
{"text SOA in key length order", "SOA", strings.ReplaceAll(soaJSONColumn, ": ", ":"), nil},
|
||||
{"partly reordered SOA", "SOA", `{"MBox":"hostmaster.example.org.","ns":"ns.example.net.","refresh":3600,"retry":600,"expire":604800,"minttl":300,"serial":2026111800}`, []string{"content_not_canonical"}},
|
||||
{"lowercase mbox key", "SOA", strings.Replace(modelSOAContent, `"MBox"`, `"mbox"`, 1), []string{"content_not_canonical"}},
|
||||
{"dynamic SOA without serial", "SOA", strings.Replace(modelSOAContent, `,"serial":2026111800`, "", 1), []string{"soa_dynamic_serial"}},
|
||||
{"dynamic SOA with serial zero", "SOA", strings.Replace(modelSOAContent, `2026111800`, "0", 1), []string{"soa_dynamic_serial"}},
|
||||
{"json column dynamic SOA", "SOA", strings.Replace(soaJSONColumn, `"serial": 2026111800, `, "", 1), []string{"soa_dynamic_serial"}},
|
||||
{"text escaped character", "TXT", `{"text":"a<b"}`, nil},
|
||||
{"json column raw character", "TXT", `{"text": "a<b"}`, nil},
|
||||
{"nested extra key", "A", `{"ip":"192.0.2.1","x":{"y":1}}`, []string{"content_not_canonical"}},
|
||||
{"number spelled differently", "MX", `{"host":"mx.example.org.","preference":10.0}`, []string{"field_invalid"}},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
name := ""
|
||||
if tc.recordType == "SRV" {
|
||||
name = "_sip._tcp"
|
||||
}
|
||||
row := modelRawRow(9, name, tc.recordType, 3600, tc.content)
|
||||
rows := append(modelBaseZone(), row)
|
||||
if tc.recordType == "SOA" {
|
||||
rows = []recordRow{row, modelBaseZone()[1]}
|
||||
}
|
||||
var codes []string
|
||||
for _, p := range checkZone("example.org.", rows, modelNow) {
|
||||
if p.RecordID == 9 {
|
||||
codes = append(codes, p.Code)
|
||||
}
|
||||
}
|
||||
if !slices.Equal(codes, tc.codes) {
|
||||
t.Fatalf("codes = %v, want %v", codes, tc.codes)
|
||||
}
|
||||
})
|
||||
}
|
||||
for _, content := range []string{`[]`, `{"ip":{"nested":1}}`, `{"ip":"x"} {}`, `{"ip"`, `{1:2}`, `{"ip":"x"`} {
|
||||
if _, ok := contentMembers(content); ok {
|
||||
t.Fatalf("contentMembers accepted %q", content)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type modelFinding struct {
|
||||
id int64
|
||||
severity string
|
||||
code string
|
||||
}
|
||||
|
||||
func modelFindings(problems []zoneProblem) []modelFinding {
|
||||
var findings []modelFinding
|
||||
for _, p := range problems {
|
||||
findings = append(findings, modelFinding{p.RecordID, p.Severity, p.Code})
|
||||
}
|
||||
slices.SortFunc(findings, func(a, b modelFinding) int {
|
||||
return cmp.Or(cmp.Compare(a.id, b.id), strings.Compare(a.severity, b.severity), strings.Compare(a.code, b.code))
|
||||
})
|
||||
return findings
|
||||
}
|
||||
|
||||
func TestCheckZonePairs(t *testing.T) {
|
||||
soa := func(content string) []recordRow {
|
||||
return []recordRow{modelRawRow(1, "", "SOA", 3600, content), modelRawRow(2, "", "NS", 3600, `{"host":"ns.example.net."}`)}
|
||||
}
|
||||
with := func(extra ...recordRow) []recordRow { return append(modelBaseZone(), extra...) }
|
||||
txt := func(size int) string { return `{"text":"` + strings.Repeat("x", size) + `"}` }
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
triggered []recordRow
|
||||
want []modelFinding
|
||||
control []recordRow
|
||||
}{
|
||||
{"MX priority key", with(modelRawRow(3, "", "MX", 3600, `{"host":"mail.example.net.","priority":10}`)),
|
||||
[]modelFinding{{3, "error", "field_invalid"}, {3, "error", "mx_priority_key"}},
|
||||
with(modelRawRow(3, "", "MX", 3600, `{"host":"mail.example.net.","preference":10}`))},
|
||||
{"relative NS host", with(modelRawRow(3, "", "NS", 3600, `{"host":"ns2.example.net"}`)),
|
||||
[]modelFinding{{3, "error", "name_not_fqdn"}, {3, "error", "pack_failed"}, {3, "warning", "content_not_canonical"}},
|
||||
with(modelRawRow(3, "", "NS", 3600, `{"host":"ns2.example.net."}`))},
|
||||
{"relative MX host", with(modelRawRow(3, "", "MX", 3600, `{"host":"mail.example.net","preference":10}`)),
|
||||
[]modelFinding{{3, "error", "name_not_fqdn"}, {3, "error", "pack_failed"}, {3, "warning", "content_not_canonical"}},
|
||||
with(modelRawRow(3, "", "MX", 3600, `{"host":"mail.example.net.","preference":10}`))},
|
||||
{"relative SRV target", with(modelRawRow(3, "_sip._tcp", "SRV", 3600, `{"priority":1,"weight":1,"port":5060,"target":"sip.example.net"}`)),
|
||||
[]modelFinding{{3, "error", "name_not_fqdn"}, {3, "error", "pack_failed"}, {3, "warning", "content_not_canonical"}},
|
||||
with(modelRawRow(3, "_sip._tcp", "SRV", 3600, `{"priority":1,"weight":1,"port":5060,"target":"sip.example.net."}`))},
|
||||
{"relative SOA ns", soa(strings.Replace(modelSOAContent, "ns.example.net.", "ns.example.net", 1)),
|
||||
[]modelFinding{{1, "error", "name_not_fqdn"}, {1, "error", "pack_failed"}, {1, "warning", "content_not_canonical"}},
|
||||
soa(modelSOAContent)},
|
||||
{"relative SOA MBox", soa(strings.Replace(modelSOAContent, "hostmaster.example.org.", "hostmaster.example.org", 1)),
|
||||
[]modelFinding{{1, "error", "name_not_fqdn"}, {1, "error", "pack_failed"}, {1, "warning", "content_not_canonical"}},
|
||||
soa(modelSOAContent)},
|
||||
{"SOA mailbox stored as an address", soa(strings.Replace(modelSOAContent, "hostmaster.example.org.", "hostmaster@example.org.", 1)),
|
||||
[]modelFinding{{1, "error", "field_invalid"}},
|
||||
soa(modelSOAContent)},
|
||||
{"TXT of 256 bytes", with(modelRawRow(3, "text", "TXT", 3600, txt(256))),
|
||||
[]modelFinding{{3, "warning", "txt_split"}},
|
||||
with(modelRawRow(3, "text", "TXT", 3600, txt(255)))},
|
||||
{"different TTL in an RRset", with(modelRawRow(3, "www", "A", 3600, `{"ip":"192.0.2.1"}`), modelRawRow(4, "www", "A", 7200, `{"ip":"192.0.2.2"}`)),
|
||||
[]modelFinding{{3, "warning", "rrset_ttl_mismatch"}, {4, "warning", "rrset_ttl_mismatch"}},
|
||||
with(modelRawRow(3, "www", "A", 3600, `{"ip":"192.0.2.1"}`), modelRawRow(4, "www", "A", 3600, `{"ip":"192.0.2.2"}`))},
|
||||
{"same canonical identity", with(modelRawRow(3, "www", "A", 3600, `{"ip":"192.0.2.1"}`), modelRawRow(4, "www", "A", 3600, `{"ip": "192.0.2.1"}`)),
|
||||
[]modelFinding{{3, "warning", "duplicate"}, {4, "warning", "duplicate"}},
|
||||
with(modelRawRow(3, "www", "A", 3600, `{"ip":"192.0.2.1"}`), modelRawRow(4, "www", "A", 3600, `{"ip": "192.0.2.10"}`))},
|
||||
{"below a zone cut", with(modelRawRow(3, "sub", "NS", 3600, `{"host":"ns.example.net."}`), modelRawRow(4, "www.sub", "A", 3600, `{"ip":"192.0.2.1"}`)),
|
||||
[]modelFinding{{4, "warning", "below_zone_cut"}},
|
||||
with(modelRawRow(3, "sub", "NS", 3600, `{"host":"ns.example.net."}`), modelRawRow(4, "sub", "A", 3600, `{"ip":"192.0.2.1"}`))},
|
||||
{"dynamic SOA serial", soa(strings.Replace(modelSOAContent, `,"serial":2026111800`, "", 1)),
|
||||
[]modelFinding{{1, "warning", "soa_dynamic_serial"}},
|
||||
soa(modelSOAContent)},
|
||||
{"in-zone target without address", with(modelRawRow(3, "", "MX", 3600, `{"host":"mail.example.org.","preference":10}`)),
|
||||
[]modelFinding{{3, "warning", "target_no_address"}},
|
||||
with(modelRawRow(3, "", "MX", 3600, `{"host":"mail.example.org.","preference":10}`), modelRawRow(4, "mail", "AAAA", 3600, `{"ip":"2001:db8::1"}`))},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
if got := modelFindings(checkZone("example.org.", tc.triggered, modelNow)); !slices.Equal(got, tc.want) {
|
||||
t.Errorf("triggered: got %v, want %v", got, tc.want)
|
||||
}
|
||||
if got := modelFindings(checkZone("example.org.", tc.control, modelNow)); len(got) != 0 {
|
||||
t.Errorf("control: got %v", got)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
+39
@@ -1001,3 +1001,42 @@ func TestSQLUserBackend(t *testing.T) {
|
||||
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)
|
||||
}
|
||||
}
|
||||
+63
-38
@@ -781,21 +781,21 @@ func handleAuditRead(ctx context.Context, c *apiContext) (apiResponse, error) {
|
||||
func zoneAPIHandlers(s *WebServer) map[string]apiHandler {
|
||||
h := zoneHandlers{s}
|
||||
return map[string]apiHandler{
|
||||
"zone_list": h.listZones,
|
||||
"zone_create": h.createZone,
|
||||
"zone_read": h.readZone,
|
||||
"zone_delete": h.deleteZone,
|
||||
"record_list": h.listRecords,
|
||||
"record_create": h.createRecord,
|
||||
"record_update": h.updateRecord,
|
||||
"record_delete": h.deleteRecord,
|
||||
"record_bulk_delete": h.bulkDelete,
|
||||
"soa_update": h.updateSOA,
|
||||
"zone_check": h.checkZone,
|
||||
"check_all": h.checkAll,
|
||||
"zone_export": h.exportZone,
|
||||
"zone_import_preview": h.previewImport,
|
||||
"zone_import": h.applyImport,
|
||||
opZoneList: h.listZones,
|
||||
opZoneCreate: h.createZone,
|
||||
opZoneRead: h.readZone,
|
||||
opZoneDelete: h.deleteZone,
|
||||
opRecordList: h.listRecords,
|
||||
opRecordCreate: h.createRecord,
|
||||
opRecordUpdate: h.updateRecord,
|
||||
opRecordDelete: h.deleteRecord,
|
||||
opRecordBulkDelete: h.bulkDelete,
|
||||
opSOAUpdate: h.updateSOA,
|
||||
opZoneCheck: h.checkZone,
|
||||
opCheckAll: h.checkAll,
|
||||
opZoneExport: h.exportZone,
|
||||
opZoneImportPreview: h.previewImport,
|
||||
opZoneImport: h.applyImport,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -803,10 +803,6 @@ type zoneHandlers struct {
|
||||
server *WebServer
|
||||
}
|
||||
|
||||
func zoneAPINotFound() *apiError {
|
||||
return &apiError{Status: http.StatusNotFound, Message: "zone not found"}
|
||||
}
|
||||
|
||||
func zoneAPIFields(fields map[string]string) *apiError {
|
||||
return &apiError{Status: http.StatusUnprocessableEntity, Message: "validation failed", Fields: fields}
|
||||
}
|
||||
@@ -837,7 +833,7 @@ func (h zoneHandlers) visibleZones(ctx context.Context, c *apiContext) ([]zoneSu
|
||||
func (h zoneHandlers) readRows(ctx context.Context, zone string) ([]recordRow, error) {
|
||||
rows, err := newRecordStore(h.server.db, h.server.tables).ZoneRows(ctx, zone)
|
||||
if err == nil && len(rows) == 0 {
|
||||
return nil, zoneAPINotFound()
|
||||
return nil, errZoneNotFound()
|
||||
}
|
||||
return rows, err
|
||||
}
|
||||
@@ -861,7 +857,7 @@ func (h zoneHandlers) writeZone(ctx context.Context, c *apiContext, creating boo
|
||||
return err
|
||||
}
|
||||
if err != nil || actor.DeletedAt.Valid || actor.Role != c.Principal.User.Role {
|
||||
return zoneAPINotFound()
|
||||
return errZoneNotFound()
|
||||
}
|
||||
if actor.Role == "user" {
|
||||
allowed, err := w.delegations.HasDelegationForShare(ctx, c.Zone, actor.ID)
|
||||
@@ -869,7 +865,7 @@ func (h zoneHandlers) writeZone(ctx context.Context, c *apiContext, creating boo
|
||||
return err
|
||||
}
|
||||
if !allowed {
|
||||
return zoneAPINotFound()
|
||||
return errZoneNotFound()
|
||||
}
|
||||
}
|
||||
w.rows, err = w.records.ZoneRowsForUpdate(ctx, c.Zone)
|
||||
@@ -880,7 +876,7 @@ func (h zoneHandlers) writeZone(ctx context.Context, c *apiContext, creating boo
|
||||
return &apiError{Status: http.StatusConflict, Message: "zone already exists"}
|
||||
}
|
||||
if !creating && len(w.rows) == 0 {
|
||||
return zoneAPINotFound()
|
||||
return errZoneNotFound()
|
||||
}
|
||||
response, err = change(w)
|
||||
if err != nil {
|
||||
@@ -988,6 +984,11 @@ type zoneAPIView struct {
|
||||
SOA *zoneAPISOAView `json:"soa"`
|
||||
}
|
||||
|
||||
type zoneAPICreated struct {
|
||||
zoneAPIView
|
||||
Warnings []zoneAPIProblem `json:"warnings"`
|
||||
}
|
||||
|
||||
func zoneAPISerial(row recordRow) *uint32 {
|
||||
serial, _ := storedSOASerial(row)
|
||||
return zoneAPINullable(serial, serial != 0)
|
||||
@@ -1008,6 +1009,15 @@ func zoneAPIFindSOA(rows []recordRow) recordRow {
|
||||
return first
|
||||
}
|
||||
|
||||
func zoneAPISelectSOA(rows []recordRow, etag string) recordRow {
|
||||
for _, row := range rows {
|
||||
if row.RecordType == "SOA" && recordETag(row) == etag {
|
||||
return row
|
||||
}
|
||||
}
|
||||
return zoneAPIFindSOA(rows)
|
||||
}
|
||||
|
||||
func zoneAPISOADetails(row recordRow, soa soaData) zoneAPISOAFields {
|
||||
return zoneAPISOAFields{soa.NS, soa.MBox, zoneAPINullable(row.TTL.Int64, row.TTL.Valid), soa.Refresh, soa.Retry, soa.Expire, soa.MinTTL}
|
||||
}
|
||||
@@ -1124,6 +1134,10 @@ func (h zoneHandlers) createZone(ctx context.Context, c *apiContext) (apiRespons
|
||||
}
|
||||
return apiResponse{}, zoneAPIFields(mapped)
|
||||
}
|
||||
problems, warnings := validateZoneChanges(zone, nil, zoneChanges{Creates: rows})
|
||||
if err := zoneAPIRuleError(problems, "name"); err != nil {
|
||||
return apiResponse{}, err
|
||||
}
|
||||
deleted, err := w.delegations.DeleteZoneDelegations(ctx, zone)
|
||||
if err != nil {
|
||||
return apiResponse{}, err
|
||||
@@ -1141,7 +1155,9 @@ func (h zoneHandlers) createZone(ctx context.Context, c *apiContext) (apiRespons
|
||||
if err := zoneAPIAuditChange(c, zoneAPIAuditRows(nil, deleted), zoneAPIAuditRows(rows, nil), true); err != nil {
|
||||
return apiResponse{}, err
|
||||
}
|
||||
return zoneAPISummary(zone, rows, c.Now, http.StatusCreated), nil
|
||||
response := zoneAPISummary(zone, rows, c.Now, http.StatusCreated)
|
||||
response.Body = zoneAPICreated{response.Body.(zoneAPIView), zoneAPIProblems(warnings)}
|
||||
return response, nil
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1206,9 +1222,11 @@ func zoneAPIRecordView(row recordRow, problems []zoneProblem) zoneAPIRecord {
|
||||
var raw *string
|
||||
if row.Content.Valid {
|
||||
decoded, err := inspectRecordContent(row.RecordType, row.Content.String)
|
||||
if err == nil && len(decoded.fields) == 0 && decoded.decodeErr == nil {
|
||||
parsed := err == nil && len(decoded.fields) == 0 && decoded.decodeErr == nil
|
||||
if parsed {
|
||||
data = decoded.data
|
||||
} else {
|
||||
}
|
||||
if !parsed || slices.ContainsFunc(problems, func(p zoneProblem) bool { return p.Severity == "error" }) {
|
||||
raw = &row.Content.String
|
||||
}
|
||||
}
|
||||
@@ -1578,14 +1596,14 @@ func (h zoneHandlers) deleteRecord(ctx context.Context, c *apiContext) (apiRespo
|
||||
return apiResponse{}, err
|
||||
}
|
||||
changes := zoneChanges{Deletes: []int64{id}}
|
||||
problems, _ := validateZoneChanges(c.Zone, w.rows, changes)
|
||||
problems, warnings := validateZoneChanges(c.Zone, w.rows, changes)
|
||||
if err := zoneAPIRuleError(problems, "type"); err != nil {
|
||||
return apiResponse{}, err
|
||||
}
|
||||
if _, err := w.persist(changes, false); err != nil {
|
||||
return apiResponse{}, err
|
||||
}
|
||||
return apiResponse{Status: http.StatusNoContent}, nil
|
||||
return apiResponse{Status: http.StatusOK, Body: map[string]any{"warnings": zoneAPIProblems(warnings)}}, nil
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1622,14 +1640,14 @@ func (h zoneHandlers) bulkDelete(ctx context.Context, c *apiContext) (apiRespons
|
||||
seen[id] = true
|
||||
changes.Deletes = append(changes.Deletes, id)
|
||||
}
|
||||
problems, _ := validateZoneChanges(c.Zone, w.rows, changes)
|
||||
problems, warnings := validateZoneChanges(c.Zone, w.rows, changes)
|
||||
if err := zoneAPIRuleError(problems, "records"); err != nil {
|
||||
return apiResponse{}, err
|
||||
}
|
||||
if _, err := w.persist(changes, true); err != nil {
|
||||
return apiResponse{}, err
|
||||
}
|
||||
return apiResponse{Status: http.StatusOK, Body: map[string]int{"deleted": len(changes.Deletes)}}, nil
|
||||
return apiResponse{Status: http.StatusOK, Body: map[string]any{"deleted": len(changes.Deletes), "warnings": zoneAPIProblems(warnings)}}, nil
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1640,7 +1658,7 @@ func (h zoneHandlers) updateSOA(ctx context.Context, c *apiContext) (apiResponse
|
||||
}
|
||||
decodeErr := c.decodeJSON(&in)
|
||||
return h.writeZone(ctx, c, false, func(w zoneAPIWrite) (apiResponse, error) {
|
||||
current := zoneAPIFindSOA(w.rows)
|
||||
current := zoneAPISelectSOA(w.rows, c.Request.Header.Get("If-Match"))
|
||||
if current.ID != 0 {
|
||||
c.Entry.RecordID = sql.NullInt64{Int64: current.ID, Valid: true}
|
||||
}
|
||||
@@ -1688,9 +1706,10 @@ func (h zoneHandlers) updateSOA(ctx context.Context, c *apiContext) (apiResponse
|
||||
if err != nil {
|
||||
return apiResponse{}, err
|
||||
}
|
||||
soa := zoneAPISOA(zoneAPIUpdatedRow(after, current), c.Now)
|
||||
row := zoneAPIUpdatedRow(after, current)
|
||||
soa := zoneAPISOA(row, c.Now)
|
||||
return apiResponse{
|
||||
Status: http.StatusOK, Header: zoneAPIETag(soa.ETag),
|
||||
Status: http.StatusOK, Header: zoneAPIETag(recordETag(row)),
|
||||
Body: map[string]any{"soa": soa, "warnings": zoneAPIProblems(warnings)},
|
||||
}, nil
|
||||
})
|
||||
@@ -1813,7 +1832,6 @@ func zoneAPIImportPreviewView(diff zoneImportDiff, lines []int, now time.Time) z
|
||||
Updated: make([]zoneAPIImportUpdate, 0, len(diff.Updated)),
|
||||
Deleted: make([]zoneAPIImportRow, 0, len(diff.Deleted)),
|
||||
Skipped: make([]zoneAPIImportSkip, 0, len(diff.Skipped)),
|
||||
Warnings: make([]zoneAPIImportMessage, 0, len(diff.Warnings)),
|
||||
}
|
||||
view := func(row recordRow) zoneAPIImportRow {
|
||||
return zoneAPIImportRow{row.Name, row.RecordType, zoneAPINullable(row.TTL.Int64, row.TTL.Valid), recordValue(row, now)}
|
||||
@@ -1836,14 +1854,20 @@ func zoneAPIImportPreviewView(diff zoneImportDiff, lines []int, now time.Time) z
|
||||
for _, item := range diff.Skipped {
|
||||
result.Skipped = append(result.Skipped, zoneAPIImportSkip{item.Line, item.Text, item.Reason})
|
||||
}
|
||||
result.Warnings = zoneAPIImportWarnings(diff, lines)
|
||||
return result
|
||||
}
|
||||
|
||||
func zoneAPIImportWarnings(diff zoneImportDiff, lines []int) []zoneAPIImportMessage {
|
||||
warnings := make([]zoneAPIImportMessage, 0, len(diff.Warnings))
|
||||
for i, problem := range diff.Warnings {
|
||||
message := zoneAPIImportMessage{Message: problem.Message}
|
||||
if i < len(lines) {
|
||||
message.Line = lines[i]
|
||||
}
|
||||
result.Warnings = append(result.Warnings, message)
|
||||
warnings = append(warnings, message)
|
||||
}
|
||||
return result
|
||||
return warnings
|
||||
}
|
||||
|
||||
func (h zoneHandlers) previewImport(ctx context.Context, c *apiContext) (apiResponse, error) {
|
||||
@@ -1881,15 +1905,16 @@ func (h zoneHandlers) applyImport(ctx context.Context, c *apiContext) (apiRespon
|
||||
if in.Fingerprint != zoneFingerprint(w.rows) {
|
||||
return apiResponse{}, &apiError{Status: http.StatusConflict, Message: "zone changed since preview"}
|
||||
}
|
||||
diff, _, err := in.diff(c, w.rows)
|
||||
diff, lines, err := in.diff(c, w.rows)
|
||||
if err != nil {
|
||||
return apiResponse{}, err
|
||||
}
|
||||
if _, err := w.persist(diff.Changes, true); err != nil {
|
||||
return apiResponse{}, err
|
||||
}
|
||||
return apiResponse{Status: http.StatusOK, Body: map[string]int{
|
||||
return apiResponse{Status: http.StatusOK, Body: map[string]any{
|
||||
"added": len(diff.Changes.Creates), "updated": len(diff.Updated), "deleted": len(diff.Deleted),
|
||||
"warnings": zoneAPIImportWarnings(diff, lines),
|
||||
}}, nil
|
||||
})
|
||||
}
|
||||
+248
-8
@@ -20,6 +20,47 @@ import (
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestZoneAPIRecordViewErrorContent(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
row recordRow
|
||||
wantRaw bool
|
||||
wantData bool
|
||||
codes []string
|
||||
}{
|
||||
{"valid", modelRawRow(1, "www", "A", 3600, `{"ip":"192.0.2.1"}`), false, true, nil},
|
||||
{"invalid address", modelRawRow(1, "www", "A", 3600, `{"ip":"invalid"}`), true, true, []string{"field_invalid"}},
|
||||
{"malformed", modelRawRow(2, "www", "A", 3600, `{`), true, false, []string{"content_json"}},
|
||||
{"null", recordRow{ID: 3, Zone: "example.org.", Name: "www", RecordType: "A", TTL: sql.NullInt64{Int64: 3600, Valid: true}}, false, false, []string{"content_null"}},
|
||||
{"unknown", modelRawRow(4, "www", "UNKNOWN", 3600, `{}`), true, false, []string{"type_unknown"}},
|
||||
{"warning only", modelRawRow(5, "www", "A", 0, `{"ip":"192.0.2.1"}`), false, true, []string{"ttl_zero"}},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
view := zoneAPIRecordView(tc.row, checkRecord(tc.row, modelNow))
|
||||
if (view.Raw != nil) != tc.wantRaw || (view.Data != nil) != tc.wantData {
|
||||
t.Fatalf("unexpected view: %+v", view)
|
||||
}
|
||||
if view.Raw != nil && *view.Raw != tc.row.Content.String {
|
||||
t.Fatalf("raw = %q, want the stored content", *view.Raw)
|
||||
}
|
||||
var codes []string
|
||||
for _, p := range view.Problems {
|
||||
codes = append(codes, p.Code)
|
||||
}
|
||||
if !slices.Equal(codes, tc.codes) {
|
||||
t.Fatalf("problems = %v, want %v", codes, tc.codes)
|
||||
}
|
||||
})
|
||||
}
|
||||
rows := append(zoneAPITestRows(t), modelRawRow(9, "bad", "A", 60, `{"ip":"invalid"}`))
|
||||
f := zoneAPITestDBFor(t, rows)
|
||||
server, _ := f.server()
|
||||
resp := zoneAPITestStatus(t, t.Context(), zoneAPITestRequest(server, f.actor, "record_list", zoneAPITestName, "", "", ""), 200)
|
||||
if body := zoneAPITestJSON(t, resp.Body); !strings.Contains(body, `"data":{"ip":"invalid"},"raw":"{\"ip\":\"invalid\"}"`) {
|
||||
t.Fatalf("record list = %s", body)
|
||||
}
|
||||
}
|
||||
|
||||
func (h *webHarness) stored(username string) userRow {
|
||||
h.t.Helper()
|
||||
u, err := h.store.UserByUsername(context.Background(), username)
|
||||
@@ -980,6 +1021,8 @@ type zoneAPITestDB struct {
|
||||
auditError error
|
||||
writeError error
|
||||
lastID int64
|
||||
fail func(query string) error
|
||||
hideInsert bool
|
||||
}
|
||||
|
||||
func zoneAPITestDBFor(t *testing.T, rows []recordRow) *zoneAPITestDB {
|
||||
@@ -1006,6 +1049,11 @@ func (f *zoneAPITestDB) server() (*WebServer, *fdbState) {
|
||||
|
||||
func (f *zoneAPITestDB) query(query string, args []any) fdbResponse {
|
||||
has := func(value string) bool { return strings.Contains(query, value) }
|
||||
if f.fail != nil {
|
||||
if err := f.fail(query); err != nil {
|
||||
return fdbResponse{err: err}
|
||||
}
|
||||
}
|
||||
switch {
|
||||
case has("GET_LOCK"):
|
||||
if f.locked {
|
||||
@@ -1026,14 +1074,14 @@ func (f *zoneAPITestDB) query(query string, args []any) fdbResponse {
|
||||
}
|
||||
return fdbResponse{}
|
||||
case has("COUNT(*)") && has("GROUP BY"):
|
||||
if len(f.rows) == 0 || has("WHERE r.") && !f.delegated {
|
||||
if len(f.rows) == 0 || has("d.`user_id`") && !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 {
|
||||
if !has("d.`user_id`") && f.foreign.ID != 0 {
|
||||
rows = append(rows, []driver.Value{f.foreign.Zone, int64(1), nil})
|
||||
}
|
||||
return fdbResponse{rows: rows}
|
||||
@@ -1042,10 +1090,10 @@ func (f *zoneAPITestDB) query(query string, args []any) fdbResponse {
|
||||
return fdbResponse{rows: fdbRow(args[0], int64(18), "bob", modelNow, f.actor.ID)}
|
||||
}
|
||||
return fdbResponse{}
|
||||
case has("SELECT `id`") && has("WHERE `zone`"):
|
||||
case has("SELECT `id`") && has(zoneRowsWhere):
|
||||
var rows [][]driver.Value
|
||||
for _, row := range append(slices.Clone(f.rows), f.foreign) {
|
||||
if row.Zone == args[0] {
|
||||
if zoneAPITestKey(row.Zone) == args[0] {
|
||||
rows = append(rows, zoneAPITestValues(row))
|
||||
}
|
||||
}
|
||||
@@ -1059,6 +1107,9 @@ func (f *zoneAPITestDB) query(query string, args []any) fdbResponse {
|
||||
return fdbResponse{lastInsertID: 1, err: f.auditError}
|
||||
case has("INSERT INTO `coredns_records`"):
|
||||
f.lastID++
|
||||
if f.hideInsert {
|
||||
return fdbResponse{lastInsertID: 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),
|
||||
@@ -1074,7 +1125,7 @@ func (f *zoneAPITestDB) query(query string, args []any) fdbResponse {
|
||||
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 row.ID == args[0] || has(zoneRowsWhere) && zoneAPITestKey(row.Zone) == args[0]
|
||||
})
|
||||
return fdbResponse{rowsAffected: 1, err: f.writeError}
|
||||
case has("DELETE FROM"):
|
||||
@@ -1085,6 +1136,14 @@ func (f *zoneAPITestDB) query(query string, args []any) fdbResponse {
|
||||
}
|
||||
}
|
||||
|
||||
func zoneAPITestKey(zone string) string {
|
||||
zone = strings.ToLower(zone)
|
||||
if !strings.HasSuffix(zone, ".") {
|
||||
zone += "."
|
||||
}
|
||||
return zone
|
||||
}
|
||||
|
||||
func zoneAPITestingSQL(state *fdbState, contains string) []fdbCall {
|
||||
var result []fdbCall
|
||||
for _, call := range state.Calls() {
|
||||
@@ -1180,7 +1239,7 @@ func TestZoneAPIWriteHandlers(t *testing.T) {
|
||||
{"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_delete", "3", recordETag(rows[2]), "", 200, []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},
|
||||
} {
|
||||
@@ -1219,9 +1278,15 @@ func TestZoneAPIWriteHandlers(t *testing.T) {
|
||||
t.Fatalf("serials = %v", serials)
|
||||
}
|
||||
}
|
||||
if tc.status != 204 && tc.operation != "record_bulk_delete" && resp.Header.Get("ETag") == "" {
|
||||
if tc.status != 204 && tc.operation != "record_bulk_delete" && tc.operation != "record_delete" && resp.Header.Get("ETag") == "" {
|
||||
t.Fatal("missing response ETag")
|
||||
}
|
||||
if body := zoneAPITestJSON(t, resp.Body); tc.status != 204 && !strings.Contains(body, `"warnings":[`) {
|
||||
t.Fatalf("response without warnings: %s", body)
|
||||
}
|
||||
if f.stale && strings.Contains(string(c.Entry.After), `"username"`) {
|
||||
t.Fatalf("delegations in the after snapshot: %s", c.Entry.After)
|
||||
}
|
||||
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`") ||
|
||||
@@ -1465,7 +1530,7 @@ func TestZoneAPIImport(t *testing.T) {
|
||||
}
|
||||
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}` {
|
||||
if zoneAPITestJSON(t, resp.Body) != `{"added":1,"deleted":1,"updated":2,"warnings":[{"line":3,"message":"TXT strings were joined and the plugin will re-split them at 255 bytes"}]}` {
|
||||
t.Fatalf("apply response = %s", zoneAPITestJSON(t, resp.Body))
|
||||
}
|
||||
zoneAPITestAuditIDs(t, c.Entry.Before, []int64{1, 3, 4})
|
||||
@@ -1543,3 +1608,178 @@ func TestZoneAPIReadErrors(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func zoneAPITestSOARecord(name string) string {
|
||||
return `{"name":"` + name + `","type":"SOA","ttl":3600,"data":{"ns":"ns.example.net","MBox":"hostmaster.example.org","refresh":3600,"retry":600,"expire":604800,"minttl":300}}`
|
||||
}
|
||||
|
||||
func zoneAPITestRepair(t *testing.T, f *zoneAPITestDB, operation, id, etag, body string, status int) apiResponse {
|
||||
t.Helper()
|
||||
server, _ := f.server()
|
||||
return zoneAPITestStatus(t, t.Context(), zoneAPITestRequest(server, f.actor, operation, zoneAPITestName, id, etag, body), status)
|
||||
}
|
||||
|
||||
func zoneAPITestPreserved(t *testing.T, f *zoneAPITestDB, original []recordRow, ids ...int64) {
|
||||
t.Helper()
|
||||
byID := zoneAPIRowsByID(f.rows)
|
||||
for _, row := range original {
|
||||
if slices.Contains(ids, row.ID) && byID[row.ID] != row {
|
||||
t.Fatalf("record %d changed: %+v, want %+v", row.ID, byID[row.ID], row)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func zoneAPITestSerialOf(t *testing.T, row recordRow, want uint32) {
|
||||
t.Helper()
|
||||
if serial, _ := storedSOASerial(row); serial != want {
|
||||
t.Fatalf("serial of %d = %d, want %d", row.ID, serial, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestZoneAPIRepairNonCanonicalZone(t *testing.T) {
|
||||
serial := newSOASerial(modelNow)
|
||||
for _, stored := range []string{"example.org", "EXAMPLE.ORG.", "Example.Org"} {
|
||||
t.Run(stored, func(t *testing.T) {
|
||||
rows := zoneAPITestRows(t)
|
||||
rows[3].Zone = stored
|
||||
f := zoneAPITestDBFor(t, rows)
|
||||
f.foreign = recordRow{ID: 90, Zone: "example.org.example.", Name: "x", RecordType: "A"}
|
||||
list := zoneAPITestJSON(t, zoneAPITestRepair(t, f, "record_list", "", "", "", 200).Body)
|
||||
if !strings.Contains(list, `"id":4,"name":"second"`) || strings.Contains(list, `"id":90`) {
|
||||
t.Fatalf("record list = %s", list)
|
||||
}
|
||||
check := zoneAPITestJSON(t, zoneAPITestRepair(t, f, "zone_check", "", "", "", 200).Body)
|
||||
code := "zone_case"
|
||||
if !strings.HasSuffix(stored, ".") {
|
||||
code = "zone_not_fqdn"
|
||||
}
|
||||
if !strings.Contains(check, `"code":"`+code+`","severity":"error"`) || !strings.Contains(check, `"id":4`) {
|
||||
t.Fatalf("check = %s", check)
|
||||
}
|
||||
body := `{"name":"second","type":"A","ttl":60,"data":{"ip":"192.0.2.1"}}`
|
||||
zoneAPITestRepair(t, f, "record_update", "4", recordETag(rows[3]), body, 200)
|
||||
if f.rows[3].Zone != zoneAPITestName || f.rows[3].Content != rows[3].Content || f.rows[3].Name != "second" {
|
||||
t.Fatalf("row was not repaired: %+v", f.rows[3])
|
||||
}
|
||||
zoneAPITestPreserved(t, f, rows, 2, 3)
|
||||
zoneAPITestSerialOf(t, f.rows[0], serial+1)
|
||||
after := zoneAPITestJSON(t, zoneAPITestRepair(t, f, "zone_check", "", "", "", 200).Body)
|
||||
if after != `{"problems":[]}` {
|
||||
t.Fatalf("problems after the repair: %s", after)
|
||||
}
|
||||
})
|
||||
}
|
||||
t.Run("every row", func(t *testing.T) {
|
||||
rows := zoneAPITestRows(t)
|
||||
for i := range rows {
|
||||
rows[i].Zone = "Example.ORG"
|
||||
}
|
||||
f := zoneAPITestDBFor(t, rows)
|
||||
summary := zoneAPITestRepair(t, f, "zone_read", "", "", "", 200)
|
||||
if body := zoneAPITestJSON(t, summary.Body); !strings.Contains(body, `"name":"example.org.","records":4`) {
|
||||
t.Fatalf("summary = %s", body)
|
||||
}
|
||||
zoneAPITestRepair(t, f, "record_delete", "4", recordETag(rows[3]), "", 200)
|
||||
if len(f.rows) != 3 || slices.ContainsFunc(f.rows, func(r recordRow) bool { return r.ID == 4 }) {
|
||||
t.Fatalf("rows after delete: %+v", f.rows)
|
||||
}
|
||||
zoneAPITestRepair(t, f, "zone_delete", "", "", `{"confirm":"example.org"}`, 204)
|
||||
if len(f.rows) != 0 {
|
||||
t.Fatalf("zone delete left %+v", f.rows)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestZoneAPIRepairSOASet(t *testing.T) {
|
||||
serial := newSOASerial(modelNow)
|
||||
t.Run("non-apex SOA through soa_update", func(t *testing.T) {
|
||||
rows := zoneAPITestRows(t)
|
||||
rows[0].Name = "below"
|
||||
f := zoneAPITestDBFor(t, rows)
|
||||
summary := zoneAPITestJSON(t, zoneAPITestRepair(t, f, "zone_read", "", "", "", 200).Body)
|
||||
if !strings.Contains(summary, `"soa":null`) {
|
||||
t.Fatalf("summary = %s", summary)
|
||||
}
|
||||
resp := zoneAPITestRepair(t, f, "soa_update", "", recordETag(rows[0]), zoneAPITestSOA, 200)
|
||||
if f.rows[0].Name != "" || f.rows[0].ID != 1 || resp.Header.Get("ETag") != recordETag(f.rows[0]) ||
|
||||
!strings.Contains(zoneAPITestJSON(t, resp.Body), `"soa":{"ns":"ns.example.net."`) {
|
||||
t.Fatalf("SOA not moved: %+v, %+v", f.rows[0], resp)
|
||||
}
|
||||
zoneAPITestSerialOf(t, f.rows[0], serial+1)
|
||||
zoneAPITestPreserved(t, f, rows, 2, 3, 4)
|
||||
})
|
||||
t.Run("non-apex SOA through record_update", func(t *testing.T) {
|
||||
rows := zoneAPITestRows(t)
|
||||
rows[0].Name = "below"
|
||||
f := zoneAPITestDBFor(t, rows)
|
||||
zoneAPITestRepair(t, f, "record_update", "1", recordETag(rows[0]), zoneAPITestSOARecord("below"), 422)
|
||||
zoneAPITestRepair(t, f, "record_update", "1", recordETag(rows[0]), zoneAPITestSOARecord("@"), 200)
|
||||
if f.rows[0].Name != "" {
|
||||
t.Fatalf("SOA not moved: %+v", f.rows[0])
|
||||
}
|
||||
zoneAPITestSerialOf(t, f.rows[0], serial+1)
|
||||
zoneAPITestPreserved(t, f, rows, 2, 3, 4)
|
||||
})
|
||||
t.Run("duplicate apex SOA", func(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)
|
||||
f := zoneAPITestDBFor(t, rows)
|
||||
for _, tc := range []struct{ operation, id, etag, body string }{
|
||||
{"record_create", "", "", zoneAPITestRecord},
|
||||
{"record_delete", "3", recordETag(rows[2]), ""},
|
||||
{"soa_update", "", recordETag(rows[0]), strings.Replace(zoneAPITestSOA, "3600", "1500", 1)},
|
||||
{"record_bulk_delete", "", "", `{"records":[{"id":1,"etag":` + zoneAPITestJSON(t, recordETag(rows[0])) + `},{"id":5,"etag":` + zoneAPITestJSON(t, recordETag(extra)) + `}]}`},
|
||||
} {
|
||||
server, _ := f.server()
|
||||
c := zoneAPITestRequest(server, f.actor, tc.operation, zoneAPITestName, tc.id, tc.etag, tc.body)
|
||||
if _, err := zoneAPITestCall(t.Context(), c); err == nil || err.(*apiError).Status != 422 {
|
||||
t.Fatalf("%s in a zone with two SOA records: %v", tc.operation, err)
|
||||
}
|
||||
}
|
||||
resp := zoneAPITestRepair(t, f, "record_delete", "5", recordETag(extra), "", 200)
|
||||
if len(f.rows) != 4 || zoneAPITestJSON(t, resp.Body) != `{"warnings":[]}` {
|
||||
t.Fatalf("duplicate SOA not deleted: %+v, %+v", f.rows, resp)
|
||||
}
|
||||
zoneAPITestSerialOf(t, f.rows[0], serial+1)
|
||||
zoneAPITestPreserved(t, f, rows, 2, 3, 4)
|
||||
zoneAPITestRepair(t, f, "record_delete", "1", recordETag(f.rows[0]), "", 422)
|
||||
})
|
||||
t.Run("two non-apex SOA", func(t *testing.T) {
|
||||
rows := zoneAPITestRows(t)
|
||||
rows[0].Name = "one"
|
||||
extra := rows[0]
|
||||
extra.ID, extra.Name = 5, "two"
|
||||
rows = append(rows, extra)
|
||||
f := zoneAPITestDBFor(t, rows)
|
||||
zoneAPITestRepair(t, f, "record_delete", "5", recordETag(extra), "", 200)
|
||||
zoneAPITestSerialOf(t, f.rows[0], serial+1)
|
||||
zoneAPITestRepair(t, f, "record_delete", "1", recordETag(f.rows[0]), "", 422)
|
||||
zoneAPITestRepair(t, f, "soa_update", "", recordETag(f.rows[0]), zoneAPITestSOA, 200)
|
||||
if f.rows[0].Name != "" || len(f.rows) != 4 {
|
||||
t.Fatalf("SOA set not repaired: %+v", f.rows)
|
||||
}
|
||||
zoneAPITestSerialOf(t, f.rows[0], serial+2)
|
||||
zoneAPITestPreserved(t, f, rows, 2, 3, 4)
|
||||
})
|
||||
t.Run("apex and non-apex SOA selected by ETag", func(t *testing.T) {
|
||||
rows := zoneAPITestRows(t)
|
||||
extra := rows[0]
|
||||
extra.ID, extra.Name = 5, "below"
|
||||
rows = append(rows, extra)
|
||||
f := zoneAPITestDBFor(t, rows)
|
||||
server, _ := f.server()
|
||||
body := strings.NewReplacer(`"ttl":3600`, `"ttl":1200`, "ns.example.net", "other.example.net").Replace(zoneAPITestSOA)
|
||||
c := zoneAPITestRequest(server, f.actor, "soa_update", zoneAPITestName, "", recordETag(extra), body)
|
||||
resp := zoneAPITestStatus(t, t.Context(), c, 200)
|
||||
if c.Entry.RecordID.Int64 != 5 || f.rows[4].Name != "" || f.rows[4].TTL.Int64 != 1200 || f.rows[0] != rows[0] {
|
||||
t.Fatalf("selected SOA not updated: %+v, %+v", f.rows, resp)
|
||||
}
|
||||
zoneAPITestSerialOf(t, f.rows[4], serial)
|
||||
zoneAPITestRepair(t, f, "record_delete", "1", recordETag(rows[0]), "", 200)
|
||||
zoneAPITestSerialOf(t, f.rows[3], serial+1)
|
||||
zoneAPITestPreserved(t, f, rows, 2, 3, 4)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,372 @@
|
||||
// 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", "FOR SHARE"}},
|
||||
{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{"FOR UPDATE OF d"}},
|
||||
{name: "create after removing stale grants", operation: "zone_create", body: zoneAPITestCreate, setup: rowsWithStale,
|
||||
failOn: []string{"INSERT INTO `coredns_records`"}, ran: "DELETE FROM `coredns_webui_zone_delegations`"},
|
||||
{name: "create written rows", operation: "zone_create", body: zoneAPITestCreate, setup: rowsWithStale, failOn: zoneRead, ran: "INSERT INTO `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 `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_records`"}, ran: "DELETE FROM `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_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_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_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_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_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, "GET_LOCK")) != 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 len(zoneAPITestingSQL(state, "UPDATE `")) != 0 || !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 len(zoneAPITestingSQL(state, "INSERT INTO"))+len(zoneAPITestingSQL(state, "UPDATE `"))+len(zoneAPITestingSQL(state, "DELETE FROM")) != 0 {
|
||||
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" ||
|
||||
len(zoneAPITestingSQL(state, "INSERT INTO")) != 0 {
|
||||
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)
|
||||
}
|
||||
}
|
||||
@@ -165,7 +165,7 @@ func TestIntegrationZoneAPIHandlers(t *testing.T) {
|
||||
t.Fatalf("update audit values: %s, %s", audit.Before, audit.After)
|
||||
}
|
||||
|
||||
it.call(t, user, "record_delete", id, updated.Header.Get("ETag"), "", 204)
|
||||
it.call(t, user, "record_delete", id, updated.Header.Get("ETag"), "", 200)
|
||||
it.serial(t, serial+3)
|
||||
var deletes []map[string]any
|
||||
for _, name := range []string{"one", "two"} {
|
||||
@@ -312,7 +312,88 @@ func TestIntegrationZoneAPIJSONColumnETags(t *testing.T) {
|
||||
}
|
||||
it.audit(t, "record_update", 1)
|
||||
it.serial(t, newSOASerial(modelNow)+2)
|
||||
it.call(t, admin, "record_delete", id, newTag, "", 204)
|
||||
it.call(t, admin, "record_delete", id, newTag, "", 200)
|
||||
if check := zoneAPITestJSON(t, it.call(t, admin, "zone_check", "", "", "", 200).Body); check != `{"problems":[]}` {
|
||||
t.Fatalf("JSON column rows reported as not canonical: %s", check)
|
||||
}
|
||||
soa := zoneAPIFindSOA(it.rows(t))
|
||||
if !strings.Contains(soa.Content.String, `"retry": 600, "expire"`) {
|
||||
t.Fatalf("MySQL did not reformat the SOA content: %s", soa.Content.String)
|
||||
}
|
||||
}
|
||||
|
||||
func TestIntegrationZoneAPIRepairs(t *testing.T) {
|
||||
it := newITZoneAPI(t)
|
||||
admin := it.admin
|
||||
it.call(t, admin, "zone_create", "", "", zoneAPITestCreate, 201)
|
||||
tables := it.server.tables
|
||||
insert := func(zone, name, recordType, content string) int64 {
|
||||
id, err := it.db.rootExec(t, tables.sql("INSERT INTO {records} (`zone`, `name`, `ttl`, `content`, `record_type`) VALUES (?, ?, 60, ?, ?)"),
|
||||
zone, name, content, recordType).LastInsertId()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return id
|
||||
}
|
||||
undotted := insert("example.org", "undotted", "A", `{"ip":"192.0.2.1"}`)
|
||||
upper := insert("EXAMPLE.ORG.", "upper", "A", `{"ip":"192.0.2.2"}`)
|
||||
insert("ex\u00e4mple.org.", "accent", "A", `{"ip":"192.0.2.3"}`)
|
||||
insert("example.org..", "dots", "A", `{"ip":"192.0.2.4"}`)
|
||||
insert("sub.example.org.", "", "A", `{"ip":"192.0.2.5"}`)
|
||||
|
||||
zones, err := it.records.ListZones(t.Context())
|
||||
if err != nil || len(zones) != 4 || zones[0].Zone != zoneAPITestName || zones[0].RecordCount != 5 || !zones[0].SOAContent.Valid ||
|
||||
zones[1].Zone != "example.org.." || zones[2].Zone != "ex\u00e4mple.org." || zones[3].Zone != "sub.example.org." {
|
||||
t.Fatalf("zones = %+v, %v", zones, err)
|
||||
}
|
||||
it.grant(t, zoneAPITestName)
|
||||
mine, err := it.records.ListZonesOfUser(t.Context(), it.user.ID)
|
||||
if err != nil || len(mine) != 1 || mine[0].Zone != zoneAPITestName || mine[0].RecordCount != 5 {
|
||||
t.Fatalf("delegated zones = %+v, %v", mine, err)
|
||||
}
|
||||
if exists, err := it.records.ZoneExists(t.Context(), "example.org."); !exists || err != nil {
|
||||
t.Fatal(exists, err)
|
||||
}
|
||||
rows := it.rows(t)
|
||||
if len(rows) != 5 {
|
||||
t.Fatalf("zone rows = %+v", rows)
|
||||
}
|
||||
for _, id := range []int64{undotted, upper} {
|
||||
current, err := it.records.RecordByID(t.Context(), id)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
body := zoneAPITestJSON(t, map[string]any{"name": current.Name, "type": "A", "ttl": 60, "data": json.RawMessage(current.Content.String)})
|
||||
it.call(t, it.user, "record_update", strconv.FormatInt(id, 10), recordETag(current), body, 200)
|
||||
repaired, err := it.records.RecordByID(t.Context(), id)
|
||||
if err != nil || repaired.Zone != zoneAPITestName {
|
||||
t.Fatalf("record %d not repaired: %+v, %v", id, repaired, err)
|
||||
}
|
||||
}
|
||||
it.serial(t, newSOASerial(modelNow)+2)
|
||||
|
||||
soa := zoneAPIFindSOA(it.rows(t))
|
||||
extra := insert(zoneAPITestName, "below", "SOA", strings.Replace(soa.Content.String, "ns.example.net.", "other.example.net.", 1))
|
||||
it.call(t, admin, "record_create", "", "", zoneAPITestRecord, 422)
|
||||
stored, err := it.records.RecordByID(t.Context(), extra)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
it.call(t, admin, "soa_update", "", recordETag(stored), strings.Replace(zoneAPITestSOA, "ns.example.net", "other.example.net", 1), 200)
|
||||
it.call(t, admin, "record_delete", strconv.FormatInt(soa.ID, 10), recordETag(soa), "", 200)
|
||||
rows = it.rows(t)
|
||||
final := zoneAPIFindSOA(rows)
|
||||
if len(rows) != 5 || final.ID != extra || final.Name != "" {
|
||||
t.Fatalf("SOA set not repaired: %+v", rows)
|
||||
}
|
||||
it.serial(t, newSOASerial(modelNow)+3)
|
||||
if check := zoneAPITestJSON(t, it.call(t, admin, "zone_check", "", "", "", 200).Body); strings.Contains(check, `"severity":"error"`) {
|
||||
t.Fatalf("errors after the repairs: %s", check)
|
||||
}
|
||||
it.call(t, admin, "zone_delete", "", "", `{"confirm":"example.org"}`, 204)
|
||||
if n := it.db.count(t, tables.sql("SELECT COUNT(*) FROM {records}")); n != 3 {
|
||||
t.Fatalf("zone delete left %d rows in total, want the 3 rows of other zones", n)
|
||||
}
|
||||
}
|
||||
|
||||
func TestIntegrationZoneAPIAuditRollback(t *testing.T) {
|
||||
|
||||
+19
-10
@@ -27,19 +27,28 @@ func newRecordStore(q dbtx, t tableNames) recordStore {
|
||||
|
||||
const recordColumns = "`id`, `zone`, `name`, `ttl`, `content`, `record_type`"
|
||||
|
||||
const zoneSummarySelect = "SELECT r.`zone`, COUNT(*), " +
|
||||
"(SELECT s.`content` FROM {records} s WHERE s.`zone` = r.`zone` AND CAST(s.`record_type` AS BINARY) = 'SOA' " +
|
||||
"ORDER BY s.`name` <> '', s.`id` LIMIT 1) FROM {records} r "
|
||||
func recordZoneKey(column string) string {
|
||||
return "CAST(CASE WHEN " + column + " LIKE '%.' THEN LOWER(" + column + ") ELSE CONCAT(LOWER(" + column + "), '.') END AS BINARY)"
|
||||
}
|
||||
|
||||
var zoneRowsWhere = " WHERE " + recordZoneKey("`zone`") + " = ?"
|
||||
|
||||
func zoneSummarySelect(filter string) string {
|
||||
return "SELECT k.`zone_key`, k.`record_count`, (SELECT s.`content` FROM {records} s WHERE " + recordZoneKey("s.`zone`") +
|
||||
" = k.`zone_key` AND CAST(s.`record_type` AS BINARY) = 'SOA' ORDER BY s.`name` <> '', s.`id` LIMIT 1) FROM (SELECT " +
|
||||
recordZoneKey("r.`zone`") + " AS `zone_key`, COUNT(*) AS `record_count` FROM {records} r" + filter +
|
||||
" GROUP BY `zone_key`) k ORDER BY k.`zone_key`"
|
||||
}
|
||||
|
||||
func (s recordStore) ListZones(ctx context.Context) ([]zoneSummary, error) {
|
||||
defer traceStore(ctx, "recordStore.ListZones")()
|
||||
return s.queryZones(ctx, s.t.sql(zoneSummarySelect+"GROUP BY r.`zone` ORDER BY r.`zone`"))
|
||||
return s.queryZones(ctx, s.t.sql(zoneSummarySelect("")))
|
||||
}
|
||||
|
||||
func (s recordStore) ListZonesOfUser(ctx context.Context, userID int64) ([]zoneSummary, error) {
|
||||
defer traceStore(ctx, "recordStore.ListZonesOfUser")()
|
||||
return s.queryZones(ctx, s.t.sql(zoneSummarySelect+
|
||||
"WHERE r.`zone` IN (SELECT d.`zone` FROM {delegations} d WHERE d.`user_id` = ?) GROUP BY r.`zone` ORDER BY r.`zone`"), userID)
|
||||
return s.queryZones(ctx, s.t.sql(zoneSummarySelect(" WHERE "+recordZoneKey("r.`zone`")+
|
||||
" IN (SELECT d.`zone` FROM {delegations} d WHERE d.`user_id` = ?)")), userID)
|
||||
}
|
||||
|
||||
func (s recordStore) queryZones(ctx context.Context, query string, args ...any) ([]zoneSummary, error) {
|
||||
@@ -65,7 +74,7 @@ func (s recordStore) queryZones(ctx context.Context, query string, args ...any)
|
||||
func (s recordStore) ZoneExists(ctx context.Context, zone string) (bool, error) {
|
||||
defer traceStore(ctx, "recordStore.ZoneExists")()
|
||||
var one int
|
||||
err := s.q.QueryRowContext(ctx, s.t.sql("SELECT 1 FROM {records} WHERE `zone` = ? LIMIT 1"), zone).Scan(&one)
|
||||
err := s.q.QueryRowContext(ctx, s.t.sql("SELECT 1 FROM {records}"+zoneRowsWhere+" LIMIT 1"), zone).Scan(&one)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return false, nil
|
||||
}
|
||||
@@ -77,12 +86,12 @@ func (s recordStore) ZoneExists(ctx context.Context, zone string) (bool, error)
|
||||
|
||||
func (s recordStore) ZoneRows(ctx context.Context, zone string) ([]recordRow, error) {
|
||||
defer traceStore(ctx, "recordStore.ZoneRows")()
|
||||
return s.queryRecords(ctx, s.t.sql("SELECT "+recordColumns+" FROM {records} WHERE `zone` = ? ORDER BY `id`"), zone)
|
||||
return s.queryRecords(ctx, s.t.sql("SELECT "+recordColumns+" FROM {records}"+zoneRowsWhere+" ORDER BY `id`"), zone)
|
||||
}
|
||||
|
||||
func (s recordStore) ZoneRowsForUpdate(ctx context.Context, zone string) ([]recordRow, error) {
|
||||
defer traceStore(ctx, "recordStore.ZoneRowsForUpdate")()
|
||||
return s.queryRecords(ctx, s.t.sql("SELECT "+recordColumns+" FROM {records} WHERE `zone` = ? ORDER BY `id` FOR UPDATE"), zone)
|
||||
return s.queryRecords(ctx, s.t.sql("SELECT "+recordColumns+" FROM {records}"+zoneRowsWhere+" ORDER BY `id` FOR UPDATE"), zone)
|
||||
}
|
||||
|
||||
func (s recordStore) queryRecords(ctx context.Context, query string, args ...any) ([]recordRow, error) {
|
||||
@@ -168,7 +177,7 @@ func (s recordStore) DeleteRecord(ctx context.Context, id int64) (bool, error) {
|
||||
|
||||
func (s recordStore) DeleteZoneRecords(ctx context.Context, zone string) (int64, error) {
|
||||
defer traceStore(ctx, "recordStore.DeleteZoneRecords")()
|
||||
res, err := s.q.ExecContext(ctx, s.t.sql("DELETE FROM {records} WHERE `zone` = ?"), zone)
|
||||
res, err := s.q.ExecContext(ctx, s.t.sql("DELETE FROM {records}"+zoneRowsWhere), zone)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("delete zone records: %w", err)
|
||||
}
|
||||
|
||||
@@ -9,6 +9,7 @@ import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"reflect"
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
@@ -255,3 +256,59 @@ func TestNewZoneRows(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestRecordFieldBoundaries(t *testing.T) {
|
||||
soa := func(key string, value int64) string {
|
||||
timers := map[string]int64{"refresh": 3600, "retry": 600, "expire": 604800, "minttl": 300}
|
||||
timers[key] = value
|
||||
return fmt.Sprintf(`{"ns":"ns.example.net.","MBox":"hostmaster.example.org.","refresh":%d,"retry":%d,"expire":%d,"minttl":%d}`,
|
||||
timers["refresh"], timers["retry"], timers["expire"], timers["minttl"])
|
||||
}
|
||||
caa := func(value string) string {
|
||||
encoded, _ := json.Marshal(value)
|
||||
return `{"flag":0,"tag":"issue","value":` + string(encoded) + `}`
|
||||
}
|
||||
type boundary struct {
|
||||
typ, name, content, field string
|
||||
}
|
||||
cases := []boundary{
|
||||
{"SRV", "_sip._tcp", `{"priority":65535,"weight":65535,"port":65535,"target":"."}`, ""},
|
||||
{"SRV", "_sip._tcp", `{"priority":0,"weight":0,"port":65536,"target":"."}`, "port"},
|
||||
{"SRV", "_sip._tcp", `{"priority":0,"weight":0,"port":-1,"target":"."}`, "port"},
|
||||
{"CAA", "", caa(" "), ""},
|
||||
{"CAA", "", caa("~"), ""},
|
||||
{"CAA", "", caa(" !\"#$%&'()*+,-./0123456789:;<=>?@AZ[]^_`az{|}~"), ""},
|
||||
{"CAA", "", caa("\x1f"), "value"},
|
||||
{"CAA", "", caa("\x7f"), "value"},
|
||||
{"CAA", "", caa("a\\b"), "value"},
|
||||
{"CAA", "", caa("a\tb"), "value"},
|
||||
{"CAA", "", caa("é"), "value"},
|
||||
}
|
||||
for _, key := range []string{"refresh", "retry", "expire", "minttl"} {
|
||||
cases = append(cases, boundary{"SOA", "", soa(key, 2147483647), ""}, boundary{"SOA", "", soa(key, 2147483648), key})
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.typ+"/"+tc.content, func(t *testing.T) {
|
||||
row, fields := validateRecord("example.org.", tc.name, tc.typ, 3600, json.RawMessage(tc.content), modelNow)
|
||||
if tc.field == "" {
|
||||
if len(fields) != 0 {
|
||||
t.Fatalf("refused: %v", fields)
|
||||
}
|
||||
var want []modelFinding
|
||||
if tc.typ == "SOA" {
|
||||
want = []modelFinding{{0, "warning", "soa_dynamic_serial"}}
|
||||
}
|
||||
if got := modelFindings(checkRecord(row, modelNow)); !slices.Equal(got, want) {
|
||||
t.Fatalf("check of an accepted record: %v, want %v", got, want)
|
||||
}
|
||||
if rr, err := recordRR(row, modelNow); err != nil || packRecordRR(rr) != nil {
|
||||
t.Fatalf("accepted record does not pack: %v, %v", rr, err)
|
||||
}
|
||||
return
|
||||
}
|
||||
if len(fields) != 1 || fields[tc.field] == "" {
|
||||
t.Fatalf("fields = %v, want only %q", fields, tc.field)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -192,13 +192,17 @@ func validateZoneChanges(zone string, current []recordRow, changes zoneChanges)
|
||||
before := summarizeZone(current)
|
||||
after := summarizeZone(result)
|
||||
problems, warnings = zoneRuleProblems(zone, result, after, true)
|
||||
repair := len(after.soa) != 0 && soaDefects(after.soa) < soaDefects(before.soa)
|
||||
if repair {
|
||||
problems = slices.DeleteFunc(problems, func(p zoneProblem) bool { return p.Code == "soa_multiple" || p.Code == "soa_not_apex" })
|
||||
}
|
||||
if len(before.soa) != 0 {
|
||||
afterSOAs := make(map[int64]bool)
|
||||
for _, row := range after.soa {
|
||||
afterSOAs[row.ID] = true
|
||||
}
|
||||
for _, row := range before.soa {
|
||||
if !afterSOAs[row.ID] {
|
||||
if !afterSOAs[row.ID] && !repair {
|
||||
problems = append(problems, recordProblem(row, "error", "soa_delete", "SOA may only be deleted with the zone"))
|
||||
}
|
||||
}
|
||||
@@ -215,6 +219,16 @@ func validateZoneChanges(zone string, current []recordRow, changes zoneChanges)
|
||||
return problems, warnings
|
||||
}
|
||||
|
||||
func soaDefects(soa []recordRow) int {
|
||||
defects := len(soa) - 1
|
||||
for _, row := range soa {
|
||||
if row.Name != "" {
|
||||
defects++
|
||||
}
|
||||
}
|
||||
return defects
|
||||
}
|
||||
|
||||
type recordIdentity struct {
|
||||
name, recordType, content string
|
||||
}
|
||||
|
||||
@@ -4,6 +4,8 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
@@ -74,3 +76,69 @@ func TestZoneRuleWarnings(t *testing.T) {
|
||||
t.Fatalf("clean zone reported %+v %+v", problems, warnings)
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateZoneChangePairs(t *testing.T) {
|
||||
a := func(id int64, name string, ttl int64, ip string) recordRow {
|
||||
return modelRawRow(id, name, "A", ttl, `{"ip":"`+ip+`"}`)
|
||||
}
|
||||
txt := func(size int) recordRow {
|
||||
return modelRawRow(5, "text", "TXT", 3600, `{"text":"`+strings.Repeat("x", size)+`"}`)
|
||||
}
|
||||
cut := modelRawRow(4, "sub", "NS", 3600, `{"host":"ns.example.net."}`)
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
current []recordRow
|
||||
triggered, control zoneChanges
|
||||
problems, warnings []modelFinding
|
||||
}{
|
||||
{"same canonical identity", append(modelBaseZone(), a(3, "www", 3600, "192.0.2.1")),
|
||||
zoneChanges{Creates: []recordRow{modelRawRow(5, "www", "A", 3600, `{"ip": "192.0.2.1"}`)}},
|
||||
zoneChanges{Creates: []recordRow{a(5, "www", 3600, "192.0.2.2")}},
|
||||
[]modelFinding{{3, "error", "duplicate"}, {5, "error", "duplicate"}}, nil},
|
||||
{"different TTL in an RRset", append(modelBaseZone(), a(3, "www", 3600, "192.0.2.1")),
|
||||
zoneChanges{Creates: []recordRow{a(5, "www", 60, "192.0.2.2")}},
|
||||
zoneChanges{Creates: []recordRow{a(5, "www", 3600, "192.0.2.2")}},
|
||||
nil, []modelFinding{{3, "warning", "rrset_ttl_mismatch"}, {5, "warning", "rrset_ttl_mismatch"}}},
|
||||
{"below a zone cut", append(modelBaseZone(), cut),
|
||||
zoneChanges{Creates: []recordRow{a(5, "host.sub", 3600, "192.0.2.1")}},
|
||||
zoneChanges{Creates: []recordRow{a(5, "sub", 3600, "192.0.2.1")}},
|
||||
nil, []modelFinding{{5, "warning", "below_zone_cut"}}},
|
||||
{"TXT of 256 bytes", modelBaseZone(),
|
||||
zoneChanges{Creates: []recordRow{txt(256)}}, zoneChanges{Creates: []recordRow{txt(255)}},
|
||||
nil, []modelFinding{{5, "warning", "txt_split"}}},
|
||||
{"in-zone CNAME target", append(modelBaseZone(), modelRawRow(3, "alias", "CNAME", 3600, `{"host":"www.example.net."}`)),
|
||||
zoneChanges{Creates: []recordRow{modelRawRow(5, "", "MX", 3600, `{"host":"alias.example.org.","preference":10}`)}},
|
||||
zoneChanges{Creates: []recordRow{modelRawRow(5, "", "MX", 3600, `{"host":"mail.example.net.","preference":10}`)}},
|
||||
nil, []modelFinding{{5, "warning", "target_is_cname"}, {5, "warning", "target_no_address"}}},
|
||||
{"SOA moved below the apex", modelBaseZone(),
|
||||
zoneChanges{SOAUpdate: &recordRow{ID: 1, Name: "sub", RecordType: "SOA"}},
|
||||
zoneChanges{SOAUpdate: &recordRow{ID: 1, RecordType: "SOA"}},
|
||||
[]modelFinding{{1, "error", "soa_not_apex"}}, nil},
|
||||
{"extra SOA deleted", append(modelBaseZone(), modelRawRow(3, "", "SOA", 3600, strings.Replace(modelSOAContent, "ns.example.net.", "ns2.example.net.", 1))),
|
||||
zoneChanges{Creates: []recordRow{a(5, "www", 3600, "192.0.2.1")}},
|
||||
zoneChanges{Deletes: []int64{3}},
|
||||
[]modelFinding{{1, "error", "soa_multiple"}, {3, "error", "soa_multiple"}}, nil},
|
||||
{"non-apex SOA moved to the apex", []recordRow{modelRawRow(1, "sub", "SOA", 3600, modelSOAContent), modelBaseZone()[1]},
|
||||
zoneChanges{Creates: []recordRow{a(5, "www", 3600, "192.0.2.1")}},
|
||||
zoneChanges{SOAUpdate: &recordRow{ID: 1, RecordType: "SOA", Content: sql.NullString{String: modelSOAContent, Valid: true}}},
|
||||
[]modelFinding{{1, "error", "soa_not_apex"}}, nil},
|
||||
{"last SOA deleted", []recordRow{modelRawRow(1, "sub", "SOA", 3600, modelSOAContent), modelBaseZone()[1]},
|
||||
zoneChanges{Deletes: []int64{1}},
|
||||
zoneChanges{SOAUpdate: &recordRow{ID: 1, RecordType: "SOA", Content: sql.NullString{String: modelSOAContent, Valid: true}}},
|
||||
[]modelFinding{{0, "error", "soa_missing"}, {1, "error", "soa_delete"}}, nil},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
problems, warnings := validateZoneChanges("example.org.", tc.current, tc.triggered)
|
||||
if got := modelFindings(problems); !slices.Equal(got, tc.problems) {
|
||||
t.Errorf("problems: got %v, want %v", got, tc.problems)
|
||||
}
|
||||
if got := modelFindings(warnings); !slices.Equal(got, tc.warnings) {
|
||||
t.Errorf("warnings: got %v, want %v", got, tc.warnings)
|
||||
}
|
||||
problems, warnings = validateZoneChanges("example.org.", tc.current, tc.control)
|
||||
if len(problems)+len(warnings) != 0 {
|
||||
t.Errorf("control: problems %v, warnings %v", modelFindings(problems), modelFindings(warnings))
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -68,21 +68,27 @@ func updateSOASerial(current []recordRow, changes zoneChanges, now time.Time) (*
|
||||
if changes.empty() {
|
||||
return nil, nil
|
||||
}
|
||||
var original *recordRow
|
||||
original := make(map[int64]recordRow)
|
||||
for _, row := range current {
|
||||
if row.RecordType != "SOA" {
|
||||
continue
|
||||
if row.RecordType == "SOA" {
|
||||
original[row.ID] = row
|
||||
}
|
||||
if original != nil {
|
||||
return nil, errors.New("cannot determine serial with multiple SOA records")
|
||||
}
|
||||
original = &row
|
||||
var soa []recordRow
|
||||
for _, row := range changes.finalRows(current) {
|
||||
if row.RecordType == "SOA" {
|
||||
soa = append(soa, row)
|
||||
}
|
||||
if original == nil {
|
||||
}
|
||||
if len(soa) != 1 {
|
||||
return nil, nil
|
||||
}
|
||||
before, ok := original[soa[0].ID]
|
||||
if !ok {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
serial, _ := storedSOASerial(*original)
|
||||
serial, _ := storedSOASerial(before)
|
||||
switch {
|
||||
case serial != 0:
|
||||
serial = nextSOASerial(serial, now)
|
||||
@@ -91,16 +97,7 @@ func updateSOASerial(current []recordRow, changes zoneChanges, now time.Time) (*
|
||||
default:
|
||||
return nil, nil
|
||||
}
|
||||
row := *original
|
||||
for _, updated := range changes.Updates {
|
||||
if updated.ID == original.ID {
|
||||
row = updated
|
||||
}
|
||||
}
|
||||
if changes.SOAUpdate != nil {
|
||||
row = *changes.SOAUpdate
|
||||
}
|
||||
row, err := withSOASerial(row, serial, true)
|
||||
row, err := withSOASerial(soa[0], serial, true)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
+18
-2
@@ -4,6 +4,7 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
@@ -100,8 +101,23 @@ func TestUpdateSOASerial(t *testing.T) {
|
||||
t.Fatalf("unexpected SOA: %+v, %v", row, err)
|
||||
}
|
||||
}
|
||||
if _, err := updateSOASerial(append(current, current[0]), changes, modelNow); err == nil {
|
||||
t.Fatal("bumped ambiguous SOA")
|
||||
duplicate := current[0]
|
||||
duplicate.ID = 99
|
||||
ambiguous := append(slices.Clone(current), duplicate)
|
||||
if row, err := updateSOASerial(ambiguous, zoneChanges{Creates: changes.Creates}, modelNow); err != nil || row != nil {
|
||||
t.Fatalf("bumped ambiguous SOA: %+v, %v", row, err)
|
||||
}
|
||||
if got := mustBump(ambiguous, zoneChanges{Deletes: []int64{1}}, 2026111801); got.ID != 99 {
|
||||
t.Fatalf("bumped the deleted SOA: %+v", got)
|
||||
}
|
||||
moved := current[0]
|
||||
moved.Name = "below"
|
||||
if got := mustBump([]recordRow{moved, current[1]}, zoneChanges{Updates: []recordRow{current[0]}}, 2026111801); got.Name != "" {
|
||||
t.Fatalf("lost the moved SOA: %+v", got)
|
||||
}
|
||||
converted := modelRawRow(7, "", "A", 1, `{"ip":"192.0.2.1"}`)
|
||||
if row, err := updateSOASerial([]recordRow{converted}, zoneChanges{Updates: []recordRow{modelRawRow(7, "", "SOA", 1, modelSOAContent)}}, modelNow); err != nil || row != nil {
|
||||
t.Fatalf("bumped a row that was not an SOA: %+v, %v", row, err)
|
||||
}
|
||||
if _, err := withSOASerial(recordRow{}, 42, true); err == nil {
|
||||
t.Fatal("bumped absent SOA")
|
||||
|
||||
+29
-3
@@ -20,9 +20,25 @@ function show(value) {
|
||||
return value === undefined ? "(none)" : JSON.stringify(value);
|
||||
}
|
||||
|
||||
export function diffRows(before, after) {
|
||||
const left = flatten(before === undefined ? null : before, "", new Map());
|
||||
const right = flatten(after === undefined ? null : after, "", new Map());
|
||||
function itemLabel(item, index) {
|
||||
if (item !== null && typeof item === "object" && !Array.isArray(item)) {
|
||||
if ("record_type" in item && "id" in item) return "record " + item.id;
|
||||
if ("zone" in item && "username" in item && !("id" in item)) return "delegation " + item.zone + " " + item.username;
|
||||
if ("username" in item && "id" in item) return "user " + item.id;
|
||||
}
|
||||
return "[" + index + "]";
|
||||
}
|
||||
|
||||
function keyed(value) {
|
||||
const out = new Map();
|
||||
const items = Array.isArray(value) ? value : value === null || value === undefined ? [] : [value];
|
||||
items.forEach((item, index) => out.set(itemLabel(item, index), item));
|
||||
return out;
|
||||
}
|
||||
|
||||
function diffValues(before, after, prefix) {
|
||||
const left = before === undefined ? new Map() : flatten(before, prefix, new Map());
|
||||
const right = after === undefined ? new Map() : flatten(after, prefix, new Map());
|
||||
const paths = [...new Set([...left.keys(), ...right.keys()])].filter((path) => path !== "");
|
||||
return paths.map((path) => {
|
||||
const old = left.get(path);
|
||||
@@ -35,6 +51,16 @@ export function diffRows(before, after) {
|
||||
});
|
||||
}
|
||||
|
||||
export function diffRows(before, after) {
|
||||
if (!Array.isArray(before) && !Array.isArray(after)) {
|
||||
return diffValues(before === undefined ? null : before, after === undefined ? null : after, "");
|
||||
}
|
||||
const left = keyed(before);
|
||||
const right = keyed(after);
|
||||
const labels = [...new Set([...left.keys(), ...right.keys()])];
|
||||
return labels.flatMap((label) => diffValues(left.has(label) ? left.get(label) : undefined, right.has(label) ? right.get(label) : undefined, label));
|
||||
}
|
||||
|
||||
function diffTable(entry) {
|
||||
const rows = diffRows(entry.before, entry.after);
|
||||
if (rows.length === 0) return h("p", { class: "muted", text: "No field-level data." });
|
||||
|
||||
+27
-5
@@ -6,6 +6,15 @@ import { $, ApiError, api, appData, busy, clear, clearErrors, flash, formatTTL,
|
||||
const { zone } = appData();
|
||||
const base = zonePath(zone);
|
||||
const state = { fingerprint: null, mode: "merge", content: "" };
|
||||
const MAX_REQUEST_BYTES = 2 * 1024 * 1024;
|
||||
|
||||
function requestBytes(mode, content) {
|
||||
return new TextEncoder().encode(JSON.stringify({ mode, content, fingerprint: "0".repeat(64) })).length;
|
||||
}
|
||||
|
||||
function tooLarge(mode, content) {
|
||||
return requestBytes(mode, content) > MAX_REQUEST_BYTES;
|
||||
}
|
||||
|
||||
function entryTable(title, entries, withOld) {
|
||||
if (!entries || entries.length === 0) return null;
|
||||
@@ -56,7 +65,7 @@ function showPreview(data) {
|
||||
const skipped = data.skipped || [];
|
||||
summary.append(h("p", { text: plural(added.length, "addition", "additions") + ", " + plural(updated.length, "update", "updates") + ", " + plural(deleted.length, "deletion", "deletions") + ", " + (data.unchanged || 0) + " unchanged, " + plural(skipped.length, "skipped entry", "skipped entries") + "." }));
|
||||
if (data.soa) {
|
||||
summary.append(h("p", { text: "The SOA record is replaced: " + data.soa.ns + " " + data.soa.mbox + " refresh " + data.soa.refresh + " retry " + data.soa.retry + " expire " + data.soa.expire + " minimum " + data.soa.minttl + " TTL " + formatTTL(data.soa.ttl) + "." }));
|
||||
summary.append(h("p", { text: "One of the updates replaces the SOA record: " + data.soa.ns + " " + data.soa.mbox + " refresh " + data.soa.refresh + " retry " + data.soa.retry + " expire " + data.soa.expire + " minimum " + data.soa.minttl + " TTL " + formatTTL(data.soa.ttl) + "." }));
|
||||
}
|
||||
for (const warning of data.warnings || []) {
|
||||
summary.append(h("p", { class: "alert alert-warn", text: (warning.line ? "Line " + warning.line + ": " : "") + warning.message }));
|
||||
@@ -67,7 +76,7 @@ function showPreview(data) {
|
||||
if (node) tables.append(node);
|
||||
}
|
||||
state.fingerprint = data.fingerprint;
|
||||
const total = added.length + updated.length + deleted.length + (data.soa ? 1 : 0);
|
||||
const total = added.length + updated.length + deleted.length;
|
||||
$("#import-apply").hidden = total === 0;
|
||||
if (total === 0) summary.append(h("p", { class: "muted", text: "Nothing to apply." }));
|
||||
}
|
||||
@@ -86,6 +95,10 @@ async function preview(event) {
|
||||
showFieldErrors(form, { content: "Paste a zone file or load one." });
|
||||
return;
|
||||
}
|
||||
if (tooLarge(input.mode, input.content)) {
|
||||
showFieldErrors(form, { content: "The zone file is too large: an import request is limited to 2 MiB." });
|
||||
return;
|
||||
}
|
||||
await busy($("#import-preview"), async () => {
|
||||
try {
|
||||
const { data } = await api("POST", base + "/import/preview", { body: input });
|
||||
@@ -112,7 +125,9 @@ async function apply() {
|
||||
await busy($("#import-apply"), async () => {
|
||||
try {
|
||||
const { data } = await api("POST", base + "/import/apply", { body: { mode: state.mode, content: state.content, fingerprint: state.fingerprint } });
|
||||
flash("Import applied: " + plural(data.added || 0, "addition", "additions") + ", " + plural(data.updated || 0, "update", "updates") + ", " + plural(data.deleted || 0, "deletion", "deletions") + ".");
|
||||
const warnings = Array.isArray(data.warnings) ? data.warnings : [];
|
||||
const notes = warnings.map((warning) => (warning.line ? "line " + warning.line + ": " : "") + warning.message);
|
||||
flash("Import applied: " + plural(data.added || 0, "addition", "additions") + ", " + plural(data.updated || 0, "update", "updates") + ", " + plural(data.deleted || 0, "deletion", "deletions") + "." + (notes.length ? " Warnings: " + notes.join("; ") + "." : ""));
|
||||
location.assign("/zones/" + encodeURIComponent(zone));
|
||||
} catch (err) {
|
||||
if (err instanceof ApiError && err.status === 409) {
|
||||
@@ -136,11 +151,18 @@ $("#import-form").addEventListener("input", () => {
|
||||
$("#import-file").addEventListener("change", async (event) => {
|
||||
const file = event.target.files[0];
|
||||
if (!file) return;
|
||||
if (file.size > 2 * 1024 * 1024) {
|
||||
if (file.size > MAX_REQUEST_BYTES) {
|
||||
toast("The file is larger than 2 MiB.", { kind: "error" });
|
||||
event.target.value = "";
|
||||
return;
|
||||
}
|
||||
$("#import-content").value = await file.text();
|
||||
const content = await file.text();
|
||||
if (tooLarge($("#import-form").elements.mode.value, content)) {
|
||||
toast("The file is too large: an import request, which encodes the file as JSON, is limited to 2 MiB.", { kind: "error" });
|
||||
event.target.value = "";
|
||||
return;
|
||||
}
|
||||
$("#import-content").value = content;
|
||||
$("#import-apply").hidden = true;
|
||||
state.fingerprint = null;
|
||||
});
|
||||
+1
-37
@@ -56,7 +56,7 @@ export function presentValue(record) {
|
||||
case "CAA":
|
||||
return data.flag + " " + data.tag + ' "' + data.value + '"';
|
||||
case "SOA":
|
||||
return [data.ns, data.MBox !== undefined ? data.MBox : data.mbox, data.serial === null || data.serial === undefined ? "dynamic" : data.serial, data.refresh, data.retry, data.expire, data.minttl].join(" ");
|
||||
return [data.ns, data.MBox !== undefined ? data.MBox : data.mbox, data.serial == null || data.serial === 0 ? "dynamic (Unix time)" : data.serial, data.refresh, data.retry, data.expire, data.minttl].join(" ");
|
||||
default:
|
||||
return JSON.stringify(data);
|
||||
}
|
||||
@@ -66,42 +66,6 @@ export function displayName(record) {
|
||||
return record.name === "" ? "@" : record.name;
|
||||
}
|
||||
|
||||
function nameLabels(name) {
|
||||
return name === "" ? [] : name.toLowerCase().split(".").reverse();
|
||||
}
|
||||
|
||||
function compareLabels(a, b) {
|
||||
const left = nameLabels(a);
|
||||
const right = nameLabels(b);
|
||||
const length = Math.min(left.length, right.length);
|
||||
for (let i = 0; i < length; i += 1) {
|
||||
if (left[i] < right[i]) return -1;
|
||||
if (left[i] > right[i]) return 1;
|
||||
}
|
||||
return left.length - right.length;
|
||||
}
|
||||
|
||||
function typeRank(type) {
|
||||
if (type === "SOA") return 0;
|
||||
if (type === "NS") return 1;
|
||||
return 2;
|
||||
}
|
||||
|
||||
export function compareRecords(a, b) {
|
||||
const byName = compareLabels(a.name, b.name);
|
||||
if (byName !== 0) return byName;
|
||||
const byRank = typeRank(a.type) - typeRank(b.type);
|
||||
if (byRank !== 0) return byRank;
|
||||
if (a.type !== b.type) return a.type < b.type ? -1 : 1;
|
||||
const left = presentValue(a);
|
||||
const right = presentValue(b);
|
||||
return left.localeCompare(right, "en", { numeric: true });
|
||||
}
|
||||
|
||||
export function sortRecords(records) {
|
||||
return [...records].sort(compareRecords);
|
||||
}
|
||||
|
||||
export function matchesFilter(record, type, text) {
|
||||
if (type && record.type !== type) return false;
|
||||
if (!text) return true;
|
||||
|
||||
+53
-25
@@ -2,7 +2,7 @@
|
||||
// Copyright (C) 2026 Bryan Joshua Pedini
|
||||
|
||||
import { $, api, appData, busy, clear, clearErrors, confirmDialog, flash, formatTTL, handleError, h, icon, openDialog, option, parseNumber, plural, setupDialogs, showFieldErrors, showFlash, toast, zonePath } from "./common.js";
|
||||
import { EDITABLE_TYPES, FIELD_SPECS, displayName, matchesFilter, presentValue, previewName, sortRecords, stripDot } from "./records.js";
|
||||
import { EDITABLE_TYPES, FIELD_SPECS, displayName, matchesFilter, presentValue, previewName, stripDot } from "./records.js";
|
||||
|
||||
const PAGE_SIZE = 100;
|
||||
const { zone: zoneParam, isAdmin } = appData();
|
||||
@@ -22,8 +22,22 @@ function zoneName() {
|
||||
return state.summary ? state.summary.name : zoneParam;
|
||||
}
|
||||
|
||||
function soaRows() {
|
||||
return state.records.filter((record) => record.type === "SOA");
|
||||
}
|
||||
|
||||
function soaRow() {
|
||||
return state.records.find((record) => record.type === "SOA" && record.name === "") || null;
|
||||
const rows = soaRows();
|
||||
const summary = state.summary && state.summary.soa ? rows.find((record) => record.id === state.summary.soa.id) : null;
|
||||
return summary || rows.find((record) => record.name === "") || rows[0] || null;
|
||||
}
|
||||
|
||||
function hasErrors(record) {
|
||||
return (record.problems || []).some((problem) => problem.severity === "error");
|
||||
}
|
||||
|
||||
function isBroken(record) {
|
||||
return record.data === null || record.data === undefined || hasErrors(record);
|
||||
}
|
||||
|
||||
function problemBadge(problem) {
|
||||
@@ -43,12 +57,13 @@ function renderSoa() {
|
||||
clear(summary);
|
||||
managed.hidden = true;
|
||||
const soa = state.summary ? state.summary.soa : null;
|
||||
edit.disabled = !(soa || soaRow());
|
||||
const count = soaRows().length;
|
||||
edit.disabled = count === 0;
|
||||
if (!soa) {
|
||||
status.textContent = soaRow() ? "The SOA record cannot be read. Edit it to replace it." : "This zone has no SOA record.";
|
||||
status.textContent = count === 0 ? "This zone has no SOA record." : count > 1 ? "This zone has " + count + " SOA records. Delete the extra ones in the records table and edit the one to keep." : "The SOA record has errors. Edit it to repair it.";
|
||||
return;
|
||||
}
|
||||
status.textContent = "";
|
||||
status.textContent = count > 1 ? "This zone has " + count + " SOA records. Delete the extra ones in the records table." : "";
|
||||
const dynamic = soa.serial === null || soa.serial === undefined;
|
||||
const items = [
|
||||
["Primary name server", soa.ns],
|
||||
@@ -90,7 +105,7 @@ function typeOptions() {
|
||||
}
|
||||
|
||||
function visibleRecords() {
|
||||
return sortRecords(state.records).filter((record) => matchesFilter(record, state.type, state.text));
|
||||
return state.records.filter((record) => matchesFilter(record, state.type, state.text));
|
||||
}
|
||||
|
||||
function problemsCell(record) {
|
||||
@@ -121,7 +136,7 @@ function renderRecords() {
|
||||
|
||||
function recordRow(record) {
|
||||
const label = displayName(record) + " " + record.type;
|
||||
const broken = record.data === null || record.data === undefined;
|
||||
const broken = isBroken(record);
|
||||
const isSoa = record.type === "SOA";
|
||||
const checkbox = h("input", {
|
||||
type: "checkbox",
|
||||
@@ -134,14 +149,14 @@ function recordRow(record) {
|
||||
updateSelection();
|
||||
},
|
||||
});
|
||||
const hasError = (record.problems || []).some((problem) => problem.severity === "error");
|
||||
const hasError = hasErrors(record);
|
||||
const hasWarning = (record.problems || []).length > 0;
|
||||
const value = h("td", { class: "value" },
|
||||
h("code", { class: broken ? "mono raw" : "mono", text: presentValue(record) }),
|
||||
h("code", { class: broken ? "mono raw" : "mono", text: broken ? (record.raw ?? "") : presentValue(record) }),
|
||||
(record.problems || []).length > 0 ? problemsCell(record) : null);
|
||||
const edit = h("button", { type: "button", class: "btn btn-small", "aria-label": "Edit " + label, onclick: () => (isSoa ? openSoa() : openRecord(record)) }, icon("edit"), " Edit");
|
||||
const edit = h("button", { type: "button", class: "btn btn-small", "aria-label": "Edit " + label, onclick: () => (isSoa ? openSoa(record) : openRecord(record)) }, icon("edit"), " Edit");
|
||||
const actions = h("td", { class: "actions-cell" }, edit);
|
||||
if (!isSoa) {
|
||||
if (!isSoa || soaRows().length > 1) {
|
||||
actions.append(" ", h("button", { type: "button", class: "btn btn-small btn-danger", "aria-label": "Delete " + label, onclick: () => deleteRecord(record) }, icon("trash"), " Delete"));
|
||||
}
|
||||
return h("tr", { class: hasError ? "row-error" : hasWarning ? "row-warning" : null },
|
||||
@@ -206,24 +221,37 @@ function soaBody(form) {
|
||||
};
|
||||
}
|
||||
|
||||
function openSoa() {
|
||||
const soaForm = { etag: null };
|
||||
|
||||
function soaValues(record) {
|
||||
const summary = state.summary ? state.summary.soa : null;
|
||||
if (summary && record && summary.id === record.id && !hasErrors(record)) return summary;
|
||||
const ttl = record && Number.isInteger(record.ttl) && record.ttl >= 0 ? record.ttl : 3600;
|
||||
if (record && !isBroken(record)) {
|
||||
const data = record.data;
|
||||
return { ns: data.ns, mbox: data.MBox !== undefined ? data.MBox : data.mbox, ttl, refresh: data.refresh, retry: data.retry, expire: data.expire, minttl: data.minttl };
|
||||
}
|
||||
return { ns: "", mbox: "", ttl, refresh: 3600, retry: 600, expire: 604800, minttl: 300 };
|
||||
}
|
||||
|
||||
function openSoa(selected) {
|
||||
const form = $("#soa-form");
|
||||
const soa = state.summary ? state.summary.soa : null;
|
||||
const row = soaRow();
|
||||
$("#soa-broken").hidden = Boolean(soa);
|
||||
const values = soa || { ns: "", mbox: "", ttl: row && Number.isInteger(row.ttl) && row.ttl >= 0 ? row.ttl : 3600, refresh: 3600, retry: 600, expire: 604800, minttl: 300 };
|
||||
for (const name of ["ns", "mbox", "ttl", "refresh", "retry", "expire", "minttl"]) form.elements[name].value = String(values[name]);
|
||||
const record = selected || soaRow();
|
||||
soaForm.etag = record ? record.etag : null;
|
||||
$("#soa-broken").hidden = !record || !isBroken(record);
|
||||
const values = soaValues(record);
|
||||
for (const name of ["ns", "mbox", "ttl", "refresh", "retry", "expire", "minttl"]) form.elements[name].value = values[name] === undefined || values[name] === null ? "" : String(values[name]);
|
||||
openDialog($("#soa-dialog"));
|
||||
}
|
||||
|
||||
function setupSoa() {
|
||||
const dialog = $("#soa-dialog");
|
||||
const form = $("#soa-form");
|
||||
$("#soa-edit").addEventListener("click", openSoa);
|
||||
$("#soa-edit").addEventListener("click", () => openSoa(null));
|
||||
form.addEventListener("submit", async (event) => {
|
||||
event.preventDefault();
|
||||
clearErrors(form);
|
||||
const etag = (state.summary && state.summary.soa ? state.summary.soa.etag : null) || (soaRow() ? soaRow().etag : null);
|
||||
const etag = soaForm.etag;
|
||||
await busy(form.querySelector("button[type=submit]"), async () => {
|
||||
try {
|
||||
const { data } = await api("PUT", base + "/soa", { body: soaBody(form), ifMatch: etag });
|
||||
@@ -322,7 +350,7 @@ function applyRrsetTtl(result) {
|
||||
|
||||
function openRecord(record) {
|
||||
const form = $("#record-form");
|
||||
const broken = Boolean(record) && (record.data === null || record.data === undefined);
|
||||
const broken = Boolean(record) && isBroken(record);
|
||||
const known = Boolean(record) && EDITABLE_TYPES.includes(record.type);
|
||||
recordForm.editing = record || null;
|
||||
recordForm.ttlTouched = Boolean(record);
|
||||
@@ -348,7 +376,7 @@ function recordBody(form) {
|
||||
const data = {};
|
||||
for (const spec of FIELD_SPECS[type] || []) {
|
||||
const value = form.elements[spec.key].value;
|
||||
data[spec.key] = spec.numeric || spec.options ? parseNumber(value) : spec.multiline ? value : value.trim();
|
||||
data[spec.key] = spec.numeric || spec.options ? parseNumber(value) : spec.multiline || (type === "CAA" && spec.key === "value") ? value : value.trim();
|
||||
}
|
||||
return { name: form.elements.name.value.trim(), type, ttl: parseNumber(form.elements.ttl.value), data };
|
||||
}
|
||||
@@ -394,9 +422,9 @@ async function deleteRecord(record) {
|
||||
const ok = await confirmDialog({ title: "Delete record", message: "Delete " + label + "?", confirm: "Delete" });
|
||||
if (!ok) return;
|
||||
try {
|
||||
await api("DELETE", base + "/records/" + record.id, { ifMatch: record.etag });
|
||||
const { data } = await api("DELETE", base + "/records/" + record.id, { ifMatch: record.etag });
|
||||
state.selected.delete(record.id);
|
||||
toast("Record deleted.");
|
||||
reportWarnings("Record deleted.", data);
|
||||
await load();
|
||||
} catch (err) {
|
||||
handleError(err, { reload: load });
|
||||
@@ -409,9 +437,9 @@ async function bulkDelete() {
|
||||
const ok = await confirmDialog({ title: "Delete records", message: "Delete " + plural(items.length, "selected record", "selected records") + "? Either all of them are deleted or none.", confirm: "Delete" });
|
||||
if (!ok) return;
|
||||
try {
|
||||
await api("POST", base + "/records/delete", { body: { records: items.map((record) => ({ id: record.id, etag: record.etag })) } });
|
||||
const { data } = await api("POST", base + "/records/delete", { body: { records: items.map((record) => ({ id: record.id, etag: record.etag })) } });
|
||||
state.selected.clear();
|
||||
toast(plural(items.length, "record", "records") + " deleted.");
|
||||
reportWarnings(plural(data && Number.isInteger(data.deleted) ? data.deleted : items.length, "record", "records") + " deleted.", data);
|
||||
await load();
|
||||
} catch (err) {
|
||||
handleError(err, { reload: load });
|
||||
|
||||
+4
-1
@@ -104,8 +104,9 @@ function setupCreate() {
|
||||
event.preventDefault();
|
||||
clearErrors(form);
|
||||
await busy(form.querySelector("button[type=submit]"), async () => {
|
||||
let created;
|
||||
try {
|
||||
await api("POST", "/zones", { body: zoneBody(form) });
|
||||
created = await api("POST", "/zones", { body: zoneBody(form) });
|
||||
} catch (err) {
|
||||
handleError(err, { form });
|
||||
return;
|
||||
@@ -113,6 +114,8 @@ function setupCreate() {
|
||||
dialog.close();
|
||||
form.reset();
|
||||
toast("Zone created. The DNS server serves a new zone after its next zone list reload, which happens every 10 minutes by default.");
|
||||
const warnings = created.data && Array.isArray(created.data.warnings) ? created.data.warnings : [];
|
||||
for (const warning of warnings) toast("Warning: " + warning.message, { kind: "warning" });
|
||||
await load();
|
||||
});
|
||||
});
|
||||
|
||||
+3
-3
@@ -75,7 +75,7 @@ func TestRecordStoreZones(t *testing.T) {
|
||||
t.Fatalf("got %+v", zones)
|
||||
}
|
||||
c := onlyCall(t, st)
|
||||
expectQuery(t, c, "FROM `coredns_records` r", "GROUP BY r.`zone`", "CAST(s.`record_type` AS BINARY) = 'SOA'")
|
||||
expectQuery(t, c, "FROM `coredns_records` r", "GROUP BY `zone_key`", "ORDER BY k.`zone_key`", "CAST(s.`record_type` AS BINARY) = 'SOA'")
|
||||
if _, err := s.ListZonesOfUser(ctx, 7); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -118,7 +118,7 @@ func TestRecordStoreReads(t *testing.T) {
|
||||
if !reflect.DeepEqual(rows, want) {
|
||||
t.Fatalf("got %+v", rows)
|
||||
}
|
||||
expectQuery(t, st.Calls()[1], "WHERE `zone` = ? ORDER BY `id`")
|
||||
expectQuery(t, st.Calls()[1], zoneRowsWhere+" ORDER BY `id`")
|
||||
if strings.Contains(st.Calls()[1].query, "FOR UPDATE") {
|
||||
t.Fatal("plain read locks")
|
||||
}
|
||||
@@ -187,7 +187,7 @@ func TestRecordStoreWrites(t *testing.T) {
|
||||
if n, err := s.DeleteZoneRecords(ctx, "a.org."); err != nil || n != 3 {
|
||||
t.Fatal(n, err)
|
||||
}
|
||||
expectQuery(t, st.Calls()[3], "DELETE FROM `coredns_records` WHERE `zone` = ?")
|
||||
expectQuery(t, st.Calls()[3], "DELETE FROM `coredns_records`"+zoneRowsWhere)
|
||||
db, _ = newFakeDB(t, func(string, []any) fdbResponse { return fdbResponse{rowsAffected: 0} })
|
||||
if ok, err := newRecordStore(db, fdbTables(t)).DeleteRecord(ctx, 5); ok || err != nil {
|
||||
t.Fatal(ok, err)
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
<button type="button" class="btn btn-icon" data-close aria-label="Close">×</button>
|
||||
</div>
|
||||
<div class="dialog-body">
|
||||
<p class="alert alert-warn" id="soa-broken" hidden>The stored SOA cannot be read. Saving replaces it with the values below.</p>
|
||||
<p class="alert alert-warn" id="soa-broken" hidden>This SOA record has errors. Saving replaces it with the values below, at the zone apex.</p>
|
||||
<div class="field">
|
||||
<label for="soa-ns">Primary name server</label>
|
||||
<input id="soa-ns" name="ns" type="text" autocomplete="off" autocapitalize="none" spellcheck="false" required>
|
||||
|
||||
+2
-10
@@ -6,6 +6,7 @@ package main
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"cmp"
|
||||
"crypto/sha256"
|
||||
"errors"
|
||||
"fmt"
|
||||
@@ -337,16 +338,7 @@ func diffZoneImport(zone string, current []recordRow, imported zoneFileRecords,
|
||||
Skipped: imported.Skipped, Warnings: slices.Clone(imported.Warnings), Fingerprint: zoneFingerprint(current),
|
||||
}
|
||||
current = slices.Clone(current)
|
||||
slices.SortStableFunc(current, func(a, b recordRow) int {
|
||||
switch {
|
||||
case a.ID < b.ID:
|
||||
return -1
|
||||
case a.ID > b.ID:
|
||||
return 1
|
||||
default:
|
||||
return 0
|
||||
}
|
||||
})
|
||||
slices.SortStableFunc(current, func(a, b recordRow) int { return cmp.Compare(a.ID, b.ID) })
|
||||
byIdentity := make(map[recordIdentity][]int)
|
||||
var soaIndices []int
|
||||
for i, row := range current {
|
||||
|
||||
Reference in new issue
Block a user