diff --git a/check.go b/check.go index f14bb91..1b398e5 100644 --- a/check.go +++ b/check.go @@ -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) { diff --git a/check_test.go b/check_test.go index 26d5626..361c427 100644 --- a/check_test.go +++ b/check_test.go @@ -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 '', 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) } diff --git a/records_test.go b/records_test.go index 0465b88..591b5a1 100644 --- a/records_test.go +++ b/records_test.go @@ -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) + } + }) + } +} diff --git a/rules.go b/rules.go index 31c42c8..37b1881 100644 --- a/rules.go +++ b/rules.go @@ -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 } diff --git a/rules_test.go b/rules_test.go index b1ae77f..48f67c5 100644 --- a/rules_test.go +++ b/rules_test.go @@ -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)) + } + }) + } +} diff --git a/serial.go b/serial.go index 2eadf91..cdb3deb 100644 --- a/serial.go +++ b/serial.go @@ -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 } - if original == nil { + var soa []recordRow + for _, row := range changes.finalRows(current) { + if row.RecordType == "SOA" { + soa = append(soa, row) + } + } + 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 } diff --git a/serial_test.go b/serial_test.go index 1b6a12f..24c3d58 100644 --- a/serial_test.go +++ b/serial_test.go @@ -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") diff --git a/static/js/audit.js b/static/js/audit.js index a0af2fc..4e9b6fb 100644 --- a/static/js/audit.js +++ b/static/js/audit.js @@ -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." }); diff --git a/static/js/import.js b/static/js/import.js index 67f1a7f..36f283e 100644 --- a/static/js/import.js +++ b/static/js/import.js @@ -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; }); diff --git a/static/js/records.js b/static/js/records.js index bb3fa1c..9ccfb75 100644 --- a/static/js/records.js +++ b/static/js/records.js @@ -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; diff --git a/static/js/zone.js b/static/js/zone.js index 8095b17..3af90c8 100644 --- a/static/js/zone.js +++ b/static/js/zone.js @@ -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 }); diff --git a/static/js/zones.js b/static/js/zones.js index 44f5068..c380951 100644 --- a/static/js/zones.js +++ b/static/js/zones.js @@ -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(); }); }); diff --git a/stores_test.go b/stores_test.go index 973f90f..0445f94 100644 --- a/stores_test.go +++ b/stores_test.go @@ -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) diff --git a/templates/html/partials/soa_dialog.html b/templates/html/partials/soa_dialog.html index c5eac49..2965ecc 100644 --- a/templates/html/partials/soa_dialog.html +++ b/templates/html/partials/soa_dialog.html @@ -7,7 +7,7 @@
- +
diff --git a/zonefile.go b/zonefile.go index 07b334d..6ccb6af 100644 --- a/zonefile.go +++ b/zonefile.go @@ -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 {