Add a Zones console: create and manage local zones, records and delegations

The console could not see local zones at all. `blocklist.local_zones` compiled
a store that nothing read back: there was no API for a zone, its records, its
delegations or the file a record came from, and no way to change one without
editing YAML and reloading. The Domains page is the blocklist's inline rules,
not local data, so nothing in the console covered the half of the server that
answers authoritatively from disk. There is now a Zones page and the endpoints
behind it: `GET /api/zones`, `POST`/`PUT`/`DELETE /api/zones/records`,
`POST`/`DELETE /api/zones/delegations` and `DELETE /api/zones?zone=`.

**The console owns one directory and nothing else.** `blocklist.managed_zones`
holds one `<apex>.zone` per zone, with that zone's SOA, apex NS set and the
records added there, and it is compiled by the same `localzone.Load` as the
operator's files — so a record added from the console is served on the next
query, with no reload and no restart. Files in `blocklist.local_zones` are
listed and shown read-only and are never rewritten; the key defaults to empty,
so a deployment that never sets it gets a zone browser and no zone writes.
Which file a record came from is now part of the store (`zone.files`, keyed by
the index the store already uses), so the snapshot can say "console" or "your
file" per record; the query path does not read it.

**The writer proves its own output.** A record is validated by the project's own
master-file parser, so `www` means `www.<zone>` and a bare CNAME target is
completed exactly as it would be in a zone file; the file is rendered, and the
rendering is re-parsed and compared with the records it meant to write before
the file is renamed into place. A writer bug that dropped a record would
otherwise present as a zone that silently stopped answering. A zone that cannot
answer is refused rather than created: no SOA means no NXDOMAIN or NODATA
authority, and no apex NS means nothing is delegated and no server is named. The
SOA's primary follows the apex NS set — a zone whose SOA names a server outside
its own NS set hands out a referral no resolver can follow — and the serial
moves on every write.

**A delegation takes the names under it, so a record below a cut is refused.**
The store answers those names as delegated without reading the zone file, which
would make the record data that looks alive and never answers. `DELETE
/api/zones?zone=` exists for the same reason from the other side: a zone the
console created is a real zone, so it says NXDOMAIN for what it does not hold,
and deleting a record is not what gives a name back to upstream. It is
refused for a zone that also has records outside the managed directory, because
removing that file would remove none of the zone.

**Two bugs the work turned up.** `engine.applyConfig` published local-record
metrics only when `blocklist.local_zones` was non-empty, so a zone the console
created was served but never counted; the gate is now the store's own record
count. And the record-value renderer fell back to `RR.String()` for every type
it did not know, which is the whole line rather than the RDATA — it wrote a
name and a TTL into the value column for DHCID, LOC, SSHFP and SVCB, and would
have fed that back as a record value on the next edit.

Every write recompiles the store and flushes the cache. Which names changed is
not knowable from the API, and a cached upstream answer for a name the zone now
answers is simply wrong, so the flush is blunt on purpose.

The wire shapes are type aliases in `internal/api` rather than copies, so there
is one set of json tags, and `TestZoneEndpointKeySets` pins the key set at every
level with a record and a delegation actually present — an empty list only
proves the envelope. `TestZoneWritesNeedAManagedDirectory` pins the read-only
default, and `TestZoneConsoleRoundTrip` walks the whole thing: a record added
through the API is answered authoritatively on the next query, a cut stops the
parent answering below it, and deleting the zone hands the name back.

Verified against a running instance built from this tree: records and
wildcards answer with `aa`, relative names are qualified, a record below a cut
is refused with a message that says why, and the file on disk is a zone file
an operator can read. The console page is typechecked and built; the browser was
not available in this round, so it has not been looked at.
This commit is contained in:
developer committed 2026-09-28 07:45:16 +00:00
1 parent 32f940b763
commit 504512f247
25 files changed
+4064 -56

No files matched your search

+241
View File
@@ -4,6 +4,8 @@ import (
"encoding/json"
"fmt"
"net/http"
"os"
"path/filepath"
"strings"
"testing"
"time"
@@ -13,6 +15,245 @@ import (
"git.k8s-git-k6n.net/mats/fancy-dns/internal/config"
)
// TestZoneConsoleRoundTrip is the console's zone page, end to end: a record
// added through the admin API is answered by this resolver on the next query,
// with no reload and no restart, because a zone the console created is
// compiled into the same store the operator's master files go into.
func TestZoneConsoleRoundTrip(t *testing.T) {
managed := filepath.Join(t.TempDir(), "zones")
h := newHarness(t, func(c *config.Config) { c.Block.ManagedZones = managed })
do := func(method, path, body string) (int, string) {
t.Helper()
code, out := h.do(method, path, body)
return code, string(out)
}
mustWrite := func(method, path, body string) string {
t.Helper()
code, out := do(method, path, body)
if code != http.StatusOK {
t.Fatalf("%s %s = %d: %s", method, path, code, out)
}
return out
}
// Before anything is written the page is empty but honest: no zones, the
// managed directory named, and the types the API accepts so the console
// builds its picker from the server.
_, body := h.get("/api/zones")
var empty zonesPayload
if err := json.Unmarshal(body, &empty); err != nil {
t.Fatalf("zones: %v: %s", err, body)
}
// The operator's own zone is listed before the console has written
// anything, and it is not the console's to edit.
if len(empty.Zones) != 1 || empty.Zones[0].Origin != "local." {
t.Fatalf("zones = %+v, want just the operator's local. zone", empty.Zones)
}
if empty.Zones[0].Managed {
t.Error("the operator's zone is reported as managed")
}
if empty.ManagedDir != managed {
t.Errorf("managed_dir = %q, want %q", empty.ManagedDir, managed)
}
if !empty.Writable {
t.Error("writable = false, but the harness's temp dir is writable")
}
if len(empty.Types) == 0 {
t.Error("types is empty, so the console has no record types to offer")
}
// A zone starts with a server list: without one it cannot say NXDOMAIN,
// and the writer refuses to invent it.
mustWrite(http.MethodPost, "/api/zones/records", `{"zone":"console.test.","name":"console.test.","type":"NS","value":"ns1.console.test."}`)
mustWrite(http.MethodPost, "/api/zones/records", `{"zone":"console.test.","name":"www.console.test.","type":"A","ttl":60,"value":"10.9.9.9"}`)
m := h.query("www.console.test", dns.TypeA)
if len(m.Answer) != 1 {
t.Fatalf("query www.console.test = %v, want one answer", m)
}
a, ok := m.Answer[0].(*dns.A)
if !ok || a.A.String() != "10.9.9.9" {
t.Errorf("www.console.test A = %v, want the console's record, not the upstream's", m.Answer[0])
}
if m.Authoritative != true {
t.Error("the local answer is not authoritative")
}
// The file is on disk where the operator can read it, and it is a zone
// file rather than a JSON dump.
raw, err := os.ReadFile(filepath.Join(managed, "console.test.zone"))
if err != nil {
t.Fatalf("read the managed zone file: %v", err)
}
for _, want := range []string{"$ORIGIN console.test.", "IN SOA", "IN NS", "10.9.9.9"} {
if !strings.Contains(string(raw), want) {
t.Errorf("the zone file is missing %q:\n%s", want, raw)
}
}
// A delegation is a cut: the parent stops answering below it and the
// query goes upstream, which is the whole point of making one.
mustWrite(http.MethodPost, "/api/zones/delegations", `{"zone":"console.test.","name":"sub.console.test.","targets":["ns1.sub.console.test."]}`)
m = h.query("www.sub.console.test", dns.TypeA)
if len(m.Answer) != 1 {
t.Fatalf("query below the cut = %v, want the upstream answer", m)
}
if a, ok := m.Answer[0].(*dns.A); !ok || a.A.String() != "203.0.113.7" {
t.Errorf("below the cut = %v, want the upstream's 203.0.113.7", m.Answer[0])
}
// And the cut itself is answerable, or no resolver could ever learn it.
m = h.query("sub.console.test", dns.TypeNS)
if len(m.Answer) != 1 {
t.Errorf("NS at the cut = %v, want the delegation itself", m)
}
// A record below a cut is dead data, so it is refused rather than
// written and silently never answered.
if code, _ := do(http.MethodPost, "/api/zones/records", `{"zone":"console.test.","name":"host.sub.console.test.","type":"A","value":"10.9.9.10"}`); code != http.StatusBadRequest {
t.Errorf("a record below a delegation = %d, want 400", code)
}
// Deleting the record leaves the zone authoritative, and a zone that
// exists says NXDOMAIN for the names it does not hold. That is what
// creating a zone means, and it is why deleting a zone is a separate
// action below rather than a side effect of deleting a record.
mustWrite(http.MethodDelete, "/api/zones/records?zone=console.test.&name=www.console.test.&type=A", "")
m = h.query("www.console.test", dns.TypeA)
if m.Rcode != dns.RcodeNameError || len(m.Answer) != 0 {
t.Errorf("query after the record was deleted = %v, want NXDOMAIN from the zone", m)
}
if m.Authoritative != true {
t.Error("the NXDOMAIN is not authoritative, so the zone is not serving")
}
// Deleting something that is not there is a 404, not a 500.
if code, _ := do(http.MethodDelete, "/api/zones/records?zone=console.test.&name=nope.console.test.&type=A", ""); code != http.StatusNotFound {
t.Errorf("deleting an absent record = %d, want 404", code)
}
// Removing the zone is what hands the name back to upstream, and the
// cached NXDOMAIN goes with it.
mustWrite(http.MethodDelete, "/api/zones?zone=console.test.", "")
if _, err := os.Stat(filepath.Join(managed, "console.test.zone")); !os.IsNotExist(err) {
t.Errorf("the managed zone file is still there (stat err = %v)", err)
}
m = h.query("www.console.test", dns.TypeA)
if len(m.Answer) != 1 {
t.Fatalf("query after the zone was deleted = %v, want the upstream answer", m)
}
if a, ok := m.Answer[0].(*dns.A); !ok || a.A.String() != "203.0.113.7" {
t.Errorf("after the zone was deleted = %v, want the upstream's 203.0.113.7", m.Answer[0])
}
// And the zone is gone from the page.
_, body = h.get("/api/zones")
var gone zonesPayload
if err := json.Unmarshal(body, &gone); err != nil {
t.Fatalf("zones: %v: %s", err, body)
}
for _, zone := range gone.Zones {
if zone.Origin == "console.test." {
t.Errorf("the deleted zone is still listed: %+v", zone)
}
}
// An operator's zone is not the console's to delete.
if code, _ := do(http.MethodDelete, "/api/zones?zone=local.", ""); code != http.StatusNotFound {
t.Errorf("deleting the operator's zone = %d, want 404", code)
}
// The operator's master file is still theirs: it is listed, and it is not
// reported as console-managed.
var sawLocal bool
for _, zone := range gone.Zones {
if zone.Origin != "local." {
continue
}
sawLocal = true
if zone.Managed {
t.Error("the operator's zone is reported as managed, so the console would offer to rewrite it")
}
}
if !sawLocal {
t.Errorf("the operator's zone is missing from the list: %+v", gone.Zones)
}
}
// zonesPayload is the slice of GET /api/zones this test reads. It is declared
// here rather than imported so the assertions name the fields the console
// depends on; the contract test in this package pins the whole key set.
type zonesPayload struct {
Zones []struct {
Origin string `json:"origin"`
Managed bool `json:"managed"`
Serial uint32 `json:"serial"`
Records []any `json:"records"`
RecordCount int `json:"record_count"`
Delegations []struct {
Name string `json:"name"`
Targets []string `json:"targets"`
Managed bool `json:"managed"`
} `json:"delegations"`
} `json:"zones"`
Files []string `json:"files"`
ManagedDir string `json:"managed_dir"`
Writable bool `json:"writable"`
Types []string `json:"types"`
Records int `json:"records"`
}
// TestZoneWritesNeedAManagedDirectory pins the read-only default: a
// deployment that never sets blocklist.managed_zones can browse its local zones
// and cannot have one rewritten behind its back.
func TestZoneWritesNeedAManagedDirectory(t *testing.T) {
h := newHarness(t, nil)
code, body := h.get("/api/zones")
if code != http.StatusOK {
t.Fatalf("GET /api/zones = %d: %s", code, body)
}
var zones zonesPayload
if err := json.Unmarshal(body, &zones); err != nil {
t.Fatalf("zones: %v: %s", err, body)
}
if zones.Writable {
t.Error("writable = true with no managed zone directory configured")
}
if zones.ManagedDir != "" {
t.Errorf("managed_dir = %q, want empty", zones.ManagedDir)
}
if len(zones.Zones) == 0 {
t.Error("the operator's local zone is missing, so the page would be blank rather than read-only")
}
for _, zone := range zones.Zones {
if zone.Managed {
t.Errorf("zone %s is reported as managed without a managed directory", zone.Origin)
}
}
// Every write route refuses, and says what to configure.
writes := []struct {
method string
path string
body string
}{
{http.MethodPost, "/api/zones/records", `{"zone":"console.test.","name":"console.test.","type":"NS","value":"ns1.console.test."}`},
{http.MethodPut, "/api/zones/records", `{"zone":"console.test.","name":"www","type":"A","value":"10.0.0.1"}`},
{http.MethodDelete, "/api/zones/records?zone=console.test.&name=www&type=A", ""},
{http.MethodPost, "/api/zones/delegations", `{"zone":"console.test.","name":"sub","targets":["ns1.sub.console.test."]}`},
{http.MethodDelete, "/api/zones/delegations?zone=console.test.&name=sub.console.test.", ""},
{http.MethodDelete, "/api/zones?zone=console.test.", ""},
}
for _, w := range writes {
code, out := h.do(w.method, w.path, w.body)
if code != http.StatusBadRequest {
t.Errorf("%s %s = %d, want 400: %s", w.method, w.path, code, out)
continue
}
if !strings.Contains(string(out), "managed_zones") {
t.Errorf("%s %s did not say what to configure: %s", w.method, w.path, out)
}
}
}
// TestResolveUpstream covers the happy path: a name nobody blocks is forwarded
// to the upstream and the answer is cached.
func TestResolveUpstream(t *testing.T) {