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

+37 -22
View File
@@ -56,20 +56,25 @@ type App struct {
cfg *config.Store
ver string
blocks *blocklist.Manager
cache *cache.Manager
cstore *cache.Store
logger *qlog.Logger
aclH *acl.Holder
local *localzone.Holder
zones *kubezones.Client
pool *resolver.Pool
reverse *engine.ReverseCache
engine *engine.Engine
dns *server.Server
api *api.Server
cl *cluster.Cluster
series *seriesStore
blocks *blocklist.Manager
cache *cache.Manager
cstore *cache.Store
logger *qlog.Logger
aclH *acl.Holder
local *localzone.Holder
// zones is the Kubernetes-sourced zone client.
zones *kubezones.Client
// managedZones is the console-managed zone directory: the only zone data
// the admin API may rewrite. An empty directory is what makes the
// console's Zones page read-only.
managedZones *localzone.Managed
pool *resolver.Pool
reverse *engine.ReverseCache
engine *engine.Engine
dns *server.Server
api *api.Server
cl *cluster.Cluster
series *seriesStore
apiServers []*http.Server
apiLn []net.Listener
@@ -321,26 +326,36 @@ func (a *App) startBlocklist() {
// startLocalZones compiles the local master files.
func (a *App) startLocalZones(cfg *config.Config) {
a.local = localzone.NewHolder(nil)
if len(cfg.Block.LocalZones) == 0 {
return
}
a.managedZones = localzone.NewManaged(cfg.AbsPath(cfg.Block.ManagedZones))
a.reloadLocalZones()
}
// managedZoneDir is the directory the console may write zone files into, or
// "" when the console is read-only.
func (a *App) managedZoneDir() string { return a.managedZones.Dir() }
// reloadLocalZones recompiles the local zone store. A failure keeps the
// previous store: serving stale local data beats serving nothing.
func (a *App) reloadLocalZones() {
a.zoneReloadMu.Lock()
defer a.zoneReloadMu.Unlock()
cfg := a.cfg.Get()
if len(cfg.Block.LocalZones) == 0 {
a.local.Set(nil)
return
}
paths := make([]string, 0, len(cfg.Block.LocalZones))
paths := make([]string, 0, len(cfg.Block.LocalZones)+1)
for _, p := range cfg.Block.LocalZones {
paths = append(paths, cfg.AbsPath(p))
}
// The managed directory is a zone source like any other, so a zone the
// console created is served by the same store. It is only added when it
// exists: the loader stats every path it is given, and a directory the
// console has not written to yet is not a broken configuration.
if a.managedZones.Exists() {
paths = append(paths, a.managedZones.Dir())
}
if len(paths) == 0 {
a.local.Set(nil)
metrics.SetLocalRecords(0)
return
}
store, err := localzone.Load(paths, localzone.Options{})
if err != nil {
a.markDegraded("local zones: " + err.Error())
+60
View File
@@ -5,10 +5,13 @@ import (
"encoding/json"
"io"
"net/http"
"path/filepath"
"sort"
"strconv"
"strings"
"testing"
"git.k8s-git-k6n.net/mats/fancy-dns/internal/config"
)
// The contract tests in this file exist because the console's TypeScript types
@@ -550,6 +553,63 @@ func TestRemainingEndpointKeySets(t *testing.T) {
}
// quote renders a Go string as a JSON string literal.
// TestZoneEndpointKeySets pins the zone list and the records inside it.
//
// The zone list is the one shape on this side of the API that a test cannot
// assert from an empty list: an envelope proves nothing about a record, and a
// record is the thing the console renders row by row. So this builds a zone
// through the write endpoint, delegates a name in it, and pins every level.
func TestZoneEndpointKeySets(t *testing.T) {
managed := filepath.Join(t.TempDir(), "zones")
h := newHarness(t, func(c *config.Config) { c.Block.ManagedZones = managed })
write := func(t *testing.T, method, path, body string) {
t.Helper()
code, out := h.do(method, path, body)
if code != http.StatusOK {
t.Fatalf("%s %s = %d: %s", method, path, code, out)
}
}
// A zone needs a server list before it can hold anything, and a
// delegation is the other way to start one.
write(t, http.MethodPost, "/api/zones/records", `{"zone":"console.test.","name":"console.test.","type":"NS","value":"ns1.console.test."}`)
write(t, http.MethodPost, "/api/zones/records", `{"zone":"console.test.","name":"www.console.test.","type":"A","ttl":60,"value":"10.9.9.9"}`)
write(t, http.MethodPost, "/api/zones/delegations", `{"zone":"console.test.","name":"sub.console.test.","targets":["ns1.sub.console.test."]}`)
t.Run("zones", func(t *testing.T) {
code, body := h.get("/api/zones")
if code != http.StatusOK {
t.Fatalf("GET /api/zones = %d: %s", code, body)
}
requireKeys(t, "GET /api/zones", keysOf(t, body),
wantKeys("built_at", "error", "files", "managed_dir", "records", "types", "writable", "zones"))
})
t.Run("zone", func(t *testing.T) {
code, body := h.get("/api/zones")
if code != http.StatusOK {
t.Fatalf("GET /api/zones = %d: %s", code, body)
}
requireKeys(t, "GET /api/zones zones[]", keysOfField(t, body, "zones", "0"),
wantKeys("default_ttl", "delegations", "files", "managed", "origin", "record_count", "records", "serial", "soa"))
})
t.Run("record", func(t *testing.T) {
code, body := h.get("/api/zones")
if code != http.StatusOK {
t.Fatalf("GET /api/zones = %d: %s", code, body)
}
requireKeys(t, "GET /api/zones zones[].records[]", keysOfField(t, body, "zones", "0", "records", "0"),
wantKeys("delegation", "managed", "name", "source", "ttl", "type", "value", "wildcard"))
})
t.Run("delegation", func(t *testing.T) {
code, body := h.get("/api/zones")
if code != http.StatusOK {
t.Fatalf("GET /api/zones = %d: %s", code, body)
}
requireKeys(t, "GET /api/zones zones[].delegations[]", keysOfField(t, body, "zones", "0", "delegations", "0"),
wantKeys("managed", "name", "targets"))
})
}
func quote(s string) string {
b, err := json.Marshal(s)
if err != nil {
+37 -30
View File
@@ -23,36 +23,43 @@ import (
// components. Everything the UI can read or change goes through here.
func (a *App) hooks() api.Hooks {
return api.Hooks{
Store: a.cfg,
Logger: a.log,
Version: a.ver,
StartedAt: a.startedAt,
Dashboard: a.dashboard,
Status: a.status,
Health: a.health,
BlocklistState: a.blocklistState,
BlocklistStats: a.blocklistStats,
RefreshBlocklists: a.refreshBlocklists,
ToggleBlocklist: a.toggleBlocklist,
DomainCheck: a.domainCheck,
ListDomains: a.listDomains,
AddDomain: a.addDomain,
DeleteDomain: a.deleteDomain,
LocalZones: a.listLocalZones,
SaveLocalZone: a.saveLocalZone,
DeleteLocalZone: a.deleteLocalZone,
GetACL: a.getACL,
PutACL: a.putACL,
GetUpstream: a.getUpstreams,
PutUpstream: a.putUpstream,
SearchLog: a.searchLog,
LogStats: a.logStats,
SubscribeLog: a.subscribeLog,
ClearLog: a.clearLog,
CacheStats: a.cacheStats,
CacheTop: a.cacheTop,
FlushCache: a.flushCache,
Flush: a.flush,
Store: a.cfg,
Logger: a.log,
Version: a.ver,
StartedAt: a.startedAt,
Dashboard: a.dashboard,
Status: a.status,
Health: a.health,
BlocklistState: a.blocklistState,
BlocklistStats: a.blocklistStats,
RefreshBlocklists: a.refreshBlocklists,
ToggleBlocklist: a.toggleBlocklist,
DomainCheck: a.domainCheck,
ListDomains: a.listDomains,
AddDomain: a.addDomain,
DeleteDomain: a.deleteDomain,
ListZones: a.listZones,
AddZoneRecord: a.addZoneRecord,
PutZoneRecord: a.putZoneRecord,
DeleteZoneRecord: a.deleteZoneRecord,
DeleteZone: a.deleteZone,
AddZoneDelegation: a.addZoneDelegation,
DeleteZoneDelegation: a.deleteZoneDelegation,
LocalZones: a.listLocalZones,
SaveLocalZone: a.saveLocalZone,
DeleteLocalZone: a.deleteLocalZone,
GetACL: a.getACL,
PutACL: a.putACL,
GetUpstream: a.getUpstreams,
PutUpstream: a.putUpstream,
SearchLog: a.searchLog,
LogStats: a.logStats,
SubscribeLog: a.subscribeLog,
ClearLog: a.clearLog,
CacheStats: a.cacheStats,
CacheTop: a.cacheTop,
FlushCache: a.flushCache,
Flush: a.flush,
}
}
+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) {
+248
View File
@@ -0,0 +1,248 @@
package app
import (
"context"
"errors"
"fmt"
"strings"
"git.k8s-git-k6n.net/mats/fancy-dns/internal/api"
"git.k8s-git-k6n.net/mats/fancy-dns/internal/localzone"
)
// The local-zone write path.
//
// Everything the console changes lives in the managed zone directory
// (blocklist.managed_zones), one <apex>.zone per zone. The operator's own master
// files in blocklist.local_zones are read and reported, never rewritten: a
// deployment that never configures a managed directory gets a read-only zone
// browser, and one that does gets a console whose edits land in a file it
// names and owns.
//
// Every change follows the same four steps: write the file, recompile the
// whole store, drop the cached answers, report. A change that does not
// recompile is a change the query path is not serving, so the store is only
// swapped after the new file parsed, and a failure keeps the previous store.
// listZones renders the compiled store for the console.
func (a *App) listZones() (any, error) {
dir := a.managedZoneDir()
store := a.local.Get()
// The slices are never nil: the console reads lengths and maps without
// a null check, and an empty list is a list.
res := api.ZonesResponse{
Zones: []api.Zone{},
Files: []string{},
ManagedDir: dir,
Writable: a.managedZones.Writable(),
Types: localzone.EditableTypes(),
}
if store != nil {
res.Files = store.Files()
res.BuiltAt = store.BuiltAt()
for _, zone := range store.SnapshotAll(dir) {
res.Zones = append(res.Zones, *zone)
res.Records += zone.RecordCount
}
}
res.Error = a.localZoneError()
return res, nil
}
// addZoneRecord adds one record to a zone.
func (a *App) addZoneRecord(_ context.Context, in api.ZoneRecordInput) (any, error) {
origin, err := a.zoneOrigin(in.Zone)
if err != nil {
return nil, err
}
serial, err := a.managedZones.Add(origin, localzone.Record{
Name: in.Name,
Type: in.Type,
TTL: in.TTL,
Value: in.Value,
}, a.zoneDefaults(origin))
if err != nil {
return nil, err
}
a.afterZoneWrite(origin, "add", serial)
return api.ZoneWriteResponse{OK: true, Zone: origin, Serial: serial}, nil
}
// putZoneRecord replaces the whole RRset of one name and type.
func (a *App) putZoneRecord(_ context.Context, in api.ZoneRecordInput) (any, error) {
origin, err := a.zoneOrigin(in.Zone)
if err != nil {
return nil, err
}
serial, err := a.managedZones.Put(origin, localzone.Record{
Name: in.Name,
Type: in.Type,
TTL: in.TTL,
Value: in.Value,
}, a.zoneDefaults(origin))
if err != nil {
return nil, err
}
a.afterZoneWrite(origin, "replace", serial)
return api.ZoneWriteResponse{OK: true, Zone: origin, Serial: serial}, nil
}
// deleteZoneRecord removes a record, or its whole RRset when value is empty.
func (a *App) deleteZoneRecord(_ context.Context, zone, name, rrtype, value string) error {
origin, err := a.zoneOrigin(zone)
if err != nil {
return err
}
serial, removed, err := a.managedZones.Delete(origin, name, rrtype, value)
if err != nil {
return err
}
a.afterZoneWrite(origin, "delete", serial)
if !removed {
return fmt.Errorf("no managed record matches %s %s in %s", name, rrtype, origin)
}
return nil
}
// addZoneDelegation hands a name below an apex to other servers.
func (a *App) addZoneDelegation(_ context.Context, in api.ZoneDelegationInput) (any, error) {
origin, err := a.zoneOrigin(in.Zone)
if err != nil {
return nil, err
}
targets := make([]string, 0, len(in.Targets))
for _, t := range in.Targets {
if t = strings.TrimSpace(t); t != "" {
targets = append(targets, t)
}
}
if len(targets) == 0 {
return nil, errors.New("a delegation needs at least one NS target")
}
// A brand new zone has no NS set of its own, so the delegation's targets
// are also the zone's. An existing file ignores this.
def := a.zoneDefaults(origin)
def.NS = targets
if def.TTL == 0 {
def.TTL = in.TTL
}
serial, err := a.managedZones.SetDelegation(origin, in.Name, targets, in.TTL, def)
if err != nil {
return nil, err
}
a.afterZoneWrite(origin, "delegate", serial)
return api.ZoneWriteResponse{OK: true, Zone: origin, Serial: serial}, nil
}
// deleteZoneDelegation removes a cut.
func (a *App) deleteZoneDelegation(_ context.Context, zone, name string) error {
origin, err := a.zoneOrigin(zone)
if err != nil {
return err
}
serial, removed, err := a.managedZones.RemoveDelegation(origin, name)
if err != nil {
return err
}
a.afterZoneWrite(origin, "undelegate", serial)
if !removed {
return fmt.Errorf("no delegation for %s in %s", name, origin)
}
return nil
}
// zoneOrigin canonicalises the apex a write names and refuses to go near the
// disk when the console has no managed directory.
func (a *App) zoneOrigin(zone string) (string, error) {
origin, err := localzone.NormalizeOrigin(zone)
if err != nil {
return "", err
}
if err := a.managedZones.Check(); err != nil {
return "", err
}
return origin, nil
}
// deleteZone removes a zone the console created, which is the only way a name
// goes back to upstream once the console has made a zone authoritative for
// it: a zone that exists answers NXDOMAIN for everything it does not hold.
func (a *App) deleteZone(_ context.Context, zone string) error {
origin, err := a.zoneOrigin(zone)
if err != nil {
return err
}
// The zone has to be wholly the console's: deleting a managed file that
// shares its apex with an operator's master file would remove none of
// the zone, only half of it.
whole := false
if store := a.local.Get(); store != nil {
if view := store.Snapshot(origin, a.managedZoneDir()); view != nil {
whole = view.Managed
} else {
return fmt.Errorf("no zone %s is loaded", origin)
}
} else {
return fmt.Errorf("no zone %s is loaded", origin)
}
removed, err := a.managedZones.Remove(origin, whole)
if err != nil {
return err
}
if !removed {
return fmt.Errorf("no managed zone file for %s", origin)
}
a.afterZoneWrite(origin, "delete-zone", 0)
return nil
}
// zoneDefaults seeds a managed file for an apex that has none from the zone
// as it is compiled today, so the console never has to restate a zone's
// server list and never invents one.
func (a *App) zoneDefaults(origin string) localzone.ZoneDefaults {
store := a.local.Get()
if store == nil {
return localzone.ZoneDefaults{}
}
zone := store.Snapshot(origin, a.managedZoneDir())
if zone == nil {
return localzone.ZoneDefaults{}
}
def := localzone.ZoneDefaults{TTL: zone.DefaultTTL, Soa: zone.Soa}
// The apex NS set follows the zone's existing one, from the operator's
// file if that is where it lives. A managed file that already has its own
// is not asked for defaults at all, so this only ever happens once.
for _, rec := range zone.Records {
if rec.Name == origin && rec.Type == "NS" {
def.NS = append(def.NS, rec.Value)
}
}
return def
}
// afterZoneWrite is the tail every change shares: recompile, drop the cached
// answers, log. The flush is the blunt half and it is deliberate — a name the
// zone now answers authoritatively may have an upstream answer cached, and
// which names changed is not knowable from here.
func (a *App) afterZoneWrite(origin, action string, serial uint32) {
a.reloadLocalZones()
if a.cache != nil {
a.cache.Flush()
}
records := 0
if store := a.local.Get(); store != nil {
records = store.Count()
}
a.log.Info("local zone changed", "zone", origin, "action", action, "serial", serial, "records", records)
}
// localZoneError is the reason the store is stale, or "" when it is current.
// It comes from the degraded list, so the console and /healthz agree.
func (a *App) localZoneError() string {
for _, d := range a.Degraded() {
if rest, ok := strings.CutPrefix(d, "local zones: "); ok {
return rest
}
}
return ""
}