feat(api): add zone and record handlers

- feat(api): add zone and record handlers
- test(api): exercise zone handlers against mysql
- fix(api): compute etags from stored rows
This commit is contained in:
bryanpedini committed 2026-11-19 15:46:12 +01:00
1 parent b5dc255e17
commit 23bec143e3
6 files changed
+2391 -12

No files matched your search

+445
View File
@@ -0,0 +1,445 @@
// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright (C) 2026 Bryan Joshua Pedini
//go:build integration
package main
import (
"context"
"database/sql"
"errors"
"fmt"
"net/http"
"strconv"
"strings"
"testing"
"time"
)
type itZoneAPI struct {
db *itDatabase
server *WebServer
admin userRow
user userRow
records recordStore
delegations delegationStore
}
func newITZoneAPI(t *testing.T) itZoneAPI {
t.Helper()
d := newITDatabase(t, itOptions{prefix: "zones_"})
db, tables := d.migrated(t)
users := newUserStore(db, tables)
admin, err := users.CreateUser(t.Context(), "alice", "admin", "test", modelNow)
if err != nil {
t.Fatal(err)
}
user, err := users.CreateUser(t.Context(), "bob", "user", "test", modelNow)
if err != nil {
t.Fatal(err)
}
return itZoneAPI{d, &WebServer{db: db, tables: tables, log: discardLogger()}, admin, user,
newRecordStore(db, tables), newDelegationStore(db, tables)}
}
func (it itZoneAPI) request(actor userRow, operation, id, etag, body string) *apiContext {
zone := zoneAPITestName
switch operation {
case "zone_create", "zone_list", "check_all":
zone = ""
}
return zoneAPITestRequest(it.server, actor, operation, zone, id, etag, body)
}
func (it itZoneAPI) call(t *testing.T, actor userRow, operation, id, etag, body string, status int) apiResponse {
t.Helper()
return zoneAPITestStatus(t, t.Context(), it.request(actor, operation, id, etag, body), status)
}
func (it itZoneAPI) grant(t *testing.T, zone string) {
t.Helper()
changed, err := it.delegations.GrantDelegation(t.Context(), zone, it.user.ID, it.admin.ID, modelNow)
if !changed || err != nil {
t.Fatalf("grant delegation: %v, %v", changed, err)
}
}
func (it itZoneAPI) rows(t *testing.T) []recordRow {
t.Helper()
rows, err := it.records.ZoneRows(t.Context(), zoneAPITestName)
if err != nil {
t.Fatal(err)
}
return rows
}
func (it itZoneAPI) serial(t *testing.T, want uint32) {
t.Helper()
serial, _ := storedSOASerial(zoneAPIFindSOA(it.rows(t)))
if serial != want {
t.Fatalf("serial = %d, want %d", serial, want)
}
}
func (it itZoneAPI) audit(t *testing.T, operation string, want int) []auditRow {
t.Helper()
rows, err := newAuditStore(it.server.db, it.server.tables).ListAudit(t.Context(), auditFilter{Operation: operation, Limit: 20})
if err != nil || len(rows) != want {
t.Fatalf("%s audit: got %d rows, want %d, error %v", operation, len(rows), want, err)
}
return rows
}
func TestIntegrationZoneAPIHandlers(t *testing.T) {
it := newITZoneAPI(t)
admin, user := it.admin, it.user
it.grant(t, zoneAPITestName)
response := it.call(t, admin, "zone_create", "", "", zoneAPITestCreate, 201)
if response.Header.Get("ETag") == "" {
t.Fatal("zone creation returned no SOA ETag")
}
it.call(t, admin, "zone_create", "", "", zoneAPITestCreate, 409)
it.call(t, user, "zone_create", "", "", zoneAPITestCreate, 403)
if !strings.Contains(string(it.audit(t, "zone_create", 1)[0].After), `"username": "bob"`) {
t.Fatal("zone creation audit omitted the stale delegation")
}
if allowed, err := it.delegations.HasDelegation(t.Context(), zoneAPITestName, user.ID); allowed || err != nil {
t.Fatalf("stale delegation retained: %v, %v", allowed, err)
}
it.grant(t, zoneAPITestName)
it.grant(t, "gone.example.")
it.call(t, admin, "zone_create", "", "", strings.Replace(zoneAPITestCreate, "Example.ORG", "private.example", 1), 201)
serial := newSOASerial(modelNow)
for _, actor := range []userRow{admin, user} {
body := zoneAPITestJSON(t, it.call(t, actor, "zone_list", "", "", "", 200).Body)
if !strings.Contains(body, zoneAPITestName) || strings.Contains(body, "gone.example.") ||
strings.Contains(body, "private.example.") != (actor.Role == "admin") {
t.Fatalf("%s zone list: %s", actor.Role, body)
}
}
view := it.call(t, user, "zone_read", "", "", "", 200)
if view.Body.(zoneAPIView).SOA.ETag != view.Header.Get("ETag") || *view.Body.(zoneAPIView).Serial != serial {
t.Fatalf("zone read = %+v", view)
}
created := it.call(t, user, "record_create", "", "", zoneAPITestRecord, 201)
record := created.Body.(map[string]any)["record"].(zoneAPIRecord)
id := strconv.FormatInt(record.ID, 10)
if record.ETag != created.Header.Get("ETag") {
t.Fatalf("record create ETag = %q, header = %q", record.ETag, created.Header.Get("ETag"))
}
it.serial(t, serial+1)
tables := it.server.tables
it.db.rootExec(t, tables.sql("UPDATE {records} SET ttl = 180 WHERE id = ?"), record.ID)
it.call(t, user, "record_update", id, record.ETag, zoneAPITestRecord, 412)
it.call(t, user, "record_delete", id, record.ETag, "", 412)
it.call(t, user, "record_update", id, "", zoneAPITestRecord, 428)
it.serial(t, serial+1)
list := it.call(t, user, "record_list", "", "", "", 200).Body.(map[string]any)["records"].([]zoneAPIRecord)
record = list[len(list)-1]
if record.Name != "new" || *record.TTL != 180 {
t.Fatalf("record list = %+v", list)
}
updated := it.call(t, user, "record_update", id, record.ETag, zoneAPITestRecord, 200)
it.serial(t, serial+2)
audit := it.audit(t, "record_update", 1)[0]
soaID := view.Body.(zoneAPIView).SOA.ID
zoneAPITestAuditIDs(t, audit.Before, []int64{soaID, record.ID})
zoneAPITestAuditIDs(t, audit.After, []int64{soaID, record.ID})
if !strings.Contains(string(audit.Before), `"ttl": 180`) || !strings.Contains(string(audit.After), `"ttl": 60`) {
t.Fatalf("update audit values: %s, %s", audit.Before, audit.After)
}
it.call(t, user, "record_delete", id, updated.Header.Get("ETag"), "", 204)
it.serial(t, serial+3)
var deletes []map[string]any
for _, name := range []string{"one", "two"} {
body := strings.Replace(zoneAPITestRecord, "new", name, 1)
response := it.call(t, user, "record_create", "", "", body, 201)
row := response.Body.(map[string]any)["record"].(zoneAPIRecord)
deletes = append(deletes, map[string]any{"id": row.ID, "etag": row.ETag})
}
it.serial(t, serial+5)
secondETag := deletes[1]["etag"]
deletes[1]["etag"] = "stale"
it.call(t, user, "record_bulk_delete", "", "", zoneAPITestJSON(t, map[string]any{"records": deletes}), 412)
if len(it.rows(t)) != 5 {
t.Fatal("stale bulk delete removed records")
}
deletes[1]["etag"] = secondETag
it.call(t, user, "record_bulk_delete", "", "", zoneAPITestJSON(t, map[string]any{"records": deletes}), 200)
it.serial(t, serial+6)
soa := zoneAPIFindSOA(it.rows(t))
it.call(t, user, "soa_update", "", recordETag(soa), strings.Replace(zoneAPITestSOA, `"minttl":300`, `"minttl":60`, 1), 200)
it.serial(t, serial+7)
for _, zone := range []string{zoneAPITestName, "private.example."} {
it.db.rootExec(t, tables.sql("INSERT INTO {records} (zone, name, record_type) VALUES (?, 'broken', 'A')"), zone)
}
body := zoneAPITestJSON(t, it.call(t, user, "zone_check", "", "", "", 200).Body)
if !strings.Contains(body, "ttl_null") {
t.Fatalf("zone check = %s", body)
}
for _, actor := range []userRow{admin, user} {
body := zoneAPITestJSON(t, it.call(t, actor, "check_all", "", "", "", 200).Body)
if !strings.Contains(body, zoneAPITestName) || strings.Contains(body, "private.example.") != (actor.Role == "admin") {
t.Fatalf("%s check all = %s", actor.Role, body)
}
}
export := it.call(t, user, "zone_export", "", "", "", 200)
if export.ContentType != "text/plain" || export.Header.Get("Content-Disposition") != `attachment; filename="example.org.zone"` ||
!strings.Contains(string(export.Raw), "ttl_null") {
t.Fatalf("export = %+v", export)
}
file := string(export.Raw) + "first 60 A 192.0.2.1\nsecond 60 A 192.0.2.2\n"
input := map[string]string{"mode": "replace", "content": file}
preview := func() zoneAPIImportPreview {
return it.call(t, user, "zone_import_preview", "", "", zoneAPITestJSON(t, input), 200).Body.(zoneAPIImportPreview)
}
diff := preview()
if len(diff.Added) != 2 || len(diff.Deleted) != 1 || diff.SOA != nil {
t.Fatalf("preview = %+v", diff)
}
it.db.rootExec(t, tables.sql("UPDATE {records} SET ttl = -1 WHERE zone = ? AND name = 'broken'"), zoneAPITestName)
input["fingerprint"] = diff.Fingerprint
it.call(t, user, "zone_import", "", "", zoneAPITestJSON(t, input), 409)
delete(input, "fingerprint")
input["fingerprint"] = preview().Fingerprint
it.call(t, user, "zone_import", "", "", zoneAPITestJSON(t, input), 200)
it.serial(t, serial+8)
imports := it.audit(t, "zone_import", 1)
if !strings.Contains(string(imports[0].Before), `"name": "broken"`) ||
!strings.Contains(string(imports[0].After), `"name": "second"`) ||
strings.Contains(string(imports[0].After), "backup") {
t.Fatalf("import audit: %s, %s", imports[0].Before, imports[0].After)
}
delete(input, "fingerprint")
if diff := preview(); len(diff.Added)+len(diff.Updated)+len(diff.Deleted) != 0 {
t.Fatalf("reimport diff = %+v", diff)
} else {
input["fingerprint"] = diff.Fingerprint
}
it.call(t, user, "zone_import", "", "", zoneAPITestJSON(t, input), 200)
it.serial(t, serial+8)
it.audit(t, "zone_import", 1)
it.audit(t, "zone_read", 0)
it.call(t, user, "zone_delete", "", "", `{"confirm":"example.org"}`, 403)
it.call(t, admin, "zone_delete", "", "", `{"confirm":"wrong.example.org"}`, 422)
it.call(t, admin, "zone_delete", "", "", `{"confirm":"EXAMPLE.ORG"}`, 204)
if len(it.rows(t)) != 0 || !strings.Contains(string(it.audit(t, "zone_delete", 1)[0].Before), `"username": "bob"`) {
t.Fatal("zone deletion did not remove and audit the records and delegation")
}
it.call(t, admin, "zone_read", "", "", "", 404)
if allowed, err := it.delegations.HasDelegation(t.Context(), zoneAPITestName, user.ID); allowed || err != nil {
t.Fatalf("zone delegation retained: %v, %v", allowed, err)
}
}
func TestIntegrationZoneAPILockTimeout(t *testing.T) {
it := newITZoneAPI(t)
it.call(t, it.admin, "zone_create", "", "", zoneAPITestCreate, 201)
conn, err := it.db.root.Conn(t.Context())
if err != nil {
t.Fatal(err)
}
defer conn.Close()
lock, err := acquireNamedLock(t.Context(), conn, it.server.tables.zoneLockName(zoneAPITestName), 0)
if err != nil {
t.Fatal(err)
}
defer func() {
if err := lock.release(t.Context()); err != nil {
t.Error(err)
}
}()
ctx, cancel := context.WithTimeout(t.Context(), zoneLockTimeout+5*time.Second)
defer cancel()
c := it.request(it.admin, "record_create", "", "", zoneAPITestRecord)
_, err = zoneAPITestCall(ctx, c)
var apiErr *apiError
if !errors.As(err, &apiErr) || apiErr.Status != http.StatusServiceUnavailable || apiErr.Message != "zone busy" {
t.Fatalf("contended write error = %v", err)
}
it.audit(t, "record_create", 0)
it.serial(t, newSOASerial(modelNow))
}
func TestIntegrationZoneAPIJSONColumnETags(t *testing.T) {
it := newITZoneAPI(t)
it.db.rootExec(t, it.server.tables.sql("ALTER TABLE {records} MODIFY content JSON"))
admin := it.admin
created := it.call(t, admin, "zone_create", "", "", zoneAPITestCreate, 201)
soaTag := created.Header.Get("ETag")
if soaTag != recordETag(zoneAPIFindSOA(it.rows(t))) {
t.Fatal("zone create ETag does not reflect stored SOA")
}
it.call(t, admin, "soa_update", "", soaTag, zoneAPITestSOA, 200)
it.audit(t, "soa_update", 0)
response := it.call(t, admin, "record_create", "", "", zoneAPITestRecord, 201)
row := response.Body.(map[string]any)["record"].(zoneAPIRecord)
stored, err := it.records.RecordByID(t.Context(), row.ID)
if err != nil || row.ETag != recordETag(stored) || !strings.Contains(stored.Content.String, `": "`) {
t.Fatalf("record create ETag = %q, stored row %+v, error %v", row.ETag, stored, err)
}
id := strconv.FormatInt(row.ID, 10)
it.call(t, admin, "record_update", id, row.ETag, zoneAPITestRecord, 200)
it.audit(t, "record_update", 0)
it.serial(t, newSOASerial(modelNow)+1)
newBody := strings.Replace(zoneAPITestRecord, "192.0.2.10", "192.0.2.20", 1)
newTag := it.call(t, admin, "record_update", id, row.ETag, newBody, 200).Header.Get("ETag")
stored, err = it.records.RecordByID(t.Context(), row.ID)
if err != nil || newTag == row.ETag || newTag != recordETag(stored) {
t.Fatalf("record update ETag = %q, stored row %+v, error %v", newTag, stored, err)
}
it.audit(t, "record_update", 1)
it.serial(t, newSOASerial(modelNow)+2)
it.call(t, admin, "record_delete", id, newTag, "", 204)
}
func TestIntegrationZoneAPIAuditRollback(t *testing.T) {
it := newITZoneAPI(t)
it.call(t, it.admin, "zone_create", "", "", zoneAPITestCreate, 201)
tn := it.server.tables
it.db.rootExec(t, tn.sql("CREATE TRIGGER fail_zone_audit BEFORE INSERT ON {audit} FOR EACH ROW "+
"BEGIN IF NEW.operation = 'record_create' AND EXISTS (SELECT 1 FROM {records} WHERE name = 'new') "+
"THEN SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'forced audit failure'; END IF; END"))
c := it.request(it.admin, "record_create", "", "", zoneAPITestRecord)
response, err := zoneAPITestCall(t.Context(), c)
if response.Status != 0 || mysqlErrNumber(err) != 1644 || !strings.Contains(err.Error(), "forced audit failure") ||
c.auditDone || c.Entry.Before != nil || c.Entry.After != nil {
t.Fatalf("audit failure = %+v, %v, audit = %+v", response, err, c.Entry)
}
if len(it.rows(t)) != 3 {
t.Fatal("record survived the failed audit insert")
}
it.audit(t, "record_create", 0)
it.serial(t, newSOASerial(modelNow))
it.db.rootExec(t, "DROP TRIGGER fail_zone_audit")
it.call(t, it.admin, "record_create", "", "", zoneAPITestRecord, 201)
}
func (it itZoneAPI) waitForRowLock(t *testing.T, ctx context.Context, suffix string) {
t.Helper()
ticker := time.NewTicker(25 * time.Millisecond)
defer ticker.Stop()
for {
var waiting bool
err := it.db.root.QueryRowContext(ctx, "SELECT EXISTS (SELECT 1 FROM performance_schema.data_lock_waits w "+
"JOIN performance_schema.data_locks l ON l.ENGINE = w.ENGINE AND l.ENGINE_LOCK_ID = w.REQUESTING_ENGINE_LOCK_ID "+
"WHERE l.OBJECT_SCHEMA = ? AND l.OBJECT_NAME = ?)", it.db.name, it.db.prefix+suffix).Scan(&waiting)
if err != nil {
t.Fatal(err)
}
if waiting {
return
}
select {
case <-ticker.C:
case <-ctx.Done():
t.Fatalf("no row lock wait in %s: %v", suffix, ctx.Err())
}
}
}
type itZoneResult struct {
response apiResponse
err error
}
func TestIntegrationZoneAPIAuthorizationRace(t *testing.T) {
for _, operation := range []struct {
name, table string
mutate func(ctx context.Context, tx *sql.Tx, it itZoneAPI, actor userRow) error
}{
{"revocation", "webui_zone_delegations", func(ctx context.Context, tx *sql.Tx, it itZoneAPI, actor userRow) error {
changed, err := newDelegationStore(tx, it.server.tables).RevokeDelegation(ctx, zoneAPITestName, actor.ID)
if err == nil && !changed {
return errors.New("no delegation revoked")
}
return err
}},
{"demotion", "webui_users", func(ctx context.Context, tx *sql.Tx, it itZoneAPI, actor userRow) error {
return newUserStore(tx, it.server.tables).SetRole(ctx, actor.ID, "user", modelNow)
}},
{"deletion", "webui_users", func(ctx context.Context, tx *sql.Tx, it itZoneAPI, actor userRow) error {
return newUserStore(tx, it.server.tables).MarkDeleted(ctx, actor.ID, modelNow)
}},
} {
for _, writeFirst := range []bool{true, false} {
t.Run(fmt.Sprintf("%s/write_first_%t", operation.name, writeFirst), func(t *testing.T) {
it := newITZoneAPI(t)
it.call(t, it.admin, "zone_create", "", "", zoneAPITestCreate, 201)
it.grant(t, zoneAPITestName)
actor := it.user
if operation.name == "demotion" {
var err error
actor, err = newUserStore(it.server.db, it.server.tables).CreateUser(t.Context(), "carol", "admin", "test", modelNow)
if err != nil {
t.Fatal(err)
}
}
ctx, cancel := context.WithTimeout(t.Context(), 8*time.Second)
defer cancel()
gate, err := it.db.root.BeginTx(ctx, nil)
if err != nil {
t.Fatal(err)
}
defer gate.Rollback()
if writeFirst {
if _, err := newRecordStore(gate, it.server.tables).ZoneRowsForUpdate(ctx, zoneAPITestName); err != nil {
t.Fatal(err)
}
} else if err := operation.mutate(ctx, gate, it, actor); err != nil {
t.Fatal(err)
}
result := make(chan itZoneResult, 1)
c := it.request(actor, "record_create", "", "", zoneAPITestRecord)
go func() {
response, err := zoneAPITestCall(ctx, c)
result <- itZoneResult{response, err}
}()
if writeFirst {
it.waitForRowLock(t, ctx, "records")
mutated := make(chan error, 1)
go func() {
mutated <- runInTx(ctx, it.server.db, func(tx *sql.Tx) error {
return operation.mutate(ctx, tx, it, actor)
})
}()
it.waitForRowLock(t, ctx, operation.table)
if err := gate.Commit(); err != nil {
t.Fatal(err)
}
if write := <-result; write.err != nil || write.response.Status != 201 {
t.Fatalf("write should win: %+v", write)
}
if err := <-mutated; err != nil {
t.Fatal(err)
}
it.audit(t, "record_create", 1)
it.serial(t, newSOASerial(modelNow)+1)
} else {
it.waitForRowLock(t, ctx, operation.table)
if err := gate.Commit(); err != nil {
t.Fatal(err)
}
write := <-result
var apiErr *apiError
if !errors.As(write.err, &apiErr) || apiErr.Status != 404 || apiErr.Message != "zone not found" {
t.Fatalf("authorization change should win: %+v", write)
}
it.audit(t, "record_create", 0)
it.serial(t, newSOASerial(modelNow))
}
})
}
}
}