761 lines
31 KiB
Go
761 lines
31 KiB
Go
// SPDX-License-Identifier: GPL-2.0-or-later
|
|
// Copyright (C) 2026 Bryan Joshua Pedini
|
|
|
|
//go:build integration
|
|
|
|
package main
|
|
|
|
import (
|
|
"context"
|
|
"database/sql"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"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 TestIntegrationUnsignedRecordIDs(t *testing.T) {
|
|
const firstID, lastID = int64(2147483648), int64(4294967295)
|
|
d := newITDatabase(t, itOptions{prefix: "uint_ids_", recordDDL: strings.Replace(itRecordsDDL, "`id` INT", "`id` INT UNSIGNED", 1)})
|
|
db, tables := d.migrated(t)
|
|
server := newWebServer(d.config(t), discardLogger(), db, tables, func() time.Time { return webNow })
|
|
it := itHTTP{database: d, server: server, handler: server.Handler()}
|
|
admin := it.createUser(t, "alice", roleAdmin)
|
|
token := it.token(t, admin)
|
|
do := func(method, path, etag, body string, status int) *httptest.ResponseRecorder {
|
|
t.Helper()
|
|
res := it.do(t.Context(), webRequest{method: method, path: apiPrefix + path, token: token, body: body,
|
|
header: map[string]string{"If-Match": etag}})
|
|
if res.Code != status {
|
|
t.Fatalf("%s %s: got %d, want %d, body %s", method, path, res.Code, status, res.Body)
|
|
}
|
|
return res
|
|
}
|
|
assertRecord := func(res *httptest.ResponseRecorder, id int64) string {
|
|
t.Helper()
|
|
var body struct {
|
|
Record zoneAPIRecord `json:"record"`
|
|
}
|
|
if err := json.Unmarshal(res.Body.Bytes(), &body); err != nil || body.Record.ID != id || body.Record.ETag == "" || body.Record.ETag != res.Header().Get("ETag") {
|
|
t.Fatalf("record ID or ETag mismatch, want ID %d, got %s, error %v", id, res.Body, err)
|
|
}
|
|
return body.Record.ETag
|
|
}
|
|
do(http.MethodPost, "/zones", "", zoneAPITestCreate, http.StatusCreated)
|
|
store := newRecordStore(db, tables)
|
|
rows, err := store.ZoneRows(t.Context(), zoneAPITestName)
|
|
if err != nil || len(rows) != 3 {
|
|
t.Fatalf("zone creation: %d rows, error %v", len(rows), err)
|
|
}
|
|
soaID := zoneAPIFindSOA(rows).ID
|
|
path := "/zones/" + zoneAPITestName + "/records"
|
|
firstPath := path + "/" + strconv.FormatInt(firstID, 10)
|
|
d.rootExec(t, tables.sql("ALTER TABLE {records} AUTO_INCREMENT = 2147483648"))
|
|
etag := assertRecord(do(http.MethodPost, path, "", zoneAPITestRecord, http.StatusCreated), firstID)
|
|
newRecord := strings.Replace(zoneAPITestRecord, `"ttl":60`, `"ttl":120`, 1)
|
|
newETag := assertRecord(do(http.MethodPut, firstPath, etag, newRecord, http.StatusOK), firstID)
|
|
if newETag == etag {
|
|
t.Fatal("record update kept the original ETag")
|
|
}
|
|
do(http.MethodDelete, firstPath, newETag, "", http.StatusOK)
|
|
d.rootExec(t, tables.sql("ALTER TABLE {records} AUTO_INCREMENT = 4294967295"))
|
|
etag = assertRecord(do(http.MethodPost, path, "", zoneAPITestRecord, http.StatusCreated), lastID)
|
|
bulk := fmt.Sprintf(`{"records":[{"id":%d,"etag":%q}]}`, lastID, etag)
|
|
do(http.MethodPost, path+"/delete", "", bulk, http.StatusOK)
|
|
do(http.MethodPut, path+"/4294967296", etag, zoneAPITestRecord, http.StatusBadRequest)
|
|
do(http.MethodPost, path+"/delete", "", strings.Replace(bulk, "4294967295", "4294967296", 1), http.StatusUnprocessableEntity)
|
|
for _, id := range []int64{firstID, lastID} {
|
|
if _, err := store.RecordByID(t.Context(), id); !errors.Is(err, errRowNotFound) {
|
|
t.Errorf("deleted record %d: %v", id, err)
|
|
}
|
|
}
|
|
audit, err := newAuditStore(db, tables).LatestAudit(t.Context(), 9)
|
|
want := []struct {
|
|
op string
|
|
status int
|
|
id int64
|
|
}{
|
|
{opZoneCreate, 201, 0}, {opRecordCreate, 201, firstID}, {opRecordUpdate, 200, firstID}, {opRecordDelete, 200, firstID},
|
|
{opRecordCreate, 201, lastID}, {opRecordBulkDelete, 200, 0}, {opRecordUpdate, 400, 0}, {opRecordBulkDelete, 422, 0},
|
|
}
|
|
if err != nil || len(audit) != len(want) {
|
|
t.Fatalf("audit: got %d rows, want %d, error %v", len(audit), len(want), err)
|
|
}
|
|
for i, entry := range want {
|
|
row := audit[i]
|
|
assertITHTTPAudit(t, row, entry.op, entry.status, admin)
|
|
if row.RecordID != (sql.NullInt64{Int64: entry.id, Valid: entry.id != 0}) {
|
|
t.Fatalf("%s audit: got ID %+v, want %d", entry.op, row.RecordID, entry.id)
|
|
}
|
|
}
|
|
zoneAPITestAuditIDs(t, audit[5].Before, []int64{soaID, lastID})
|
|
zoneAPITestAuditIDs(t, audit[5].After, []int64{soaID})
|
|
var apiAudit auditResponse
|
|
res := do(http.MethodGet, "/audit?operation=record_create", "", "", http.StatusOK)
|
|
if err := json.Unmarshal(res.Body.Bytes(), &apiAudit); err != nil || len(apiAudit.Entries) != 2 {
|
|
t.Fatalf("API audit: %s, error %v", res.Body, err)
|
|
}
|
|
for i, id := range []int64{lastID, firstID} {
|
|
if got := apiAudit.Entries[i].RecordID; got == nil || *got != id {
|
|
t.Fatalf("API audit record ID at %d: %v, want %d", i, got, id)
|
|
}
|
|
}
|
|
}
|
|
|
|
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)
|
|
createdZone := it.audit(t, "zone_create", 1)[0]
|
|
var before []zoneAPIAuditDelegation
|
|
var after []zoneAPIAuditRecord
|
|
if err := json.Unmarshal(createdZone.Before, &before); err != nil || len(before) != 1 || before[0].Zone != zoneAPITestName || before[0].Username != "bob" {
|
|
t.Fatalf("zone creation before snapshot: %s (%v)", createdZone.Before, err)
|
|
}
|
|
if err := json.Unmarshal(createdZone.After, &after); err != nil || len(after) != 3 {
|
|
t.Fatalf("zone creation after snapshot: %s (%v)", createdZone.After, err)
|
|
}
|
|
for _, record := range after {
|
|
if record.ID <= 0 || record.Zone != zoneAPITestName || (record.Type != "SOA" && record.Type != "NS") {
|
|
t.Fatalf("unexpected zone creation after snapshot: %+v", record)
|
|
}
|
|
}
|
|
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"), "", 200)
|
|
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)
|
|
ctx := t.Context()
|
|
tx, err := it.db.root.BeginTx(ctx, nil)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
defer tx.Rollback()
|
|
tables := it.server.tables
|
|
if _, err := tx.ExecContext(ctx, tables.sql(zoneLockSQL), tables.zoneLockName(zoneAPITestName)); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
ctx, cancel := context.WithTimeout(ctx, zoneLockTimeout+5*time.Second)
|
|
defer cancel()
|
|
start := time.Now()
|
|
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)
|
|
}
|
|
if waited := time.Since(start); waited < zoneLockTimeout-time.Second || waited > zoneLockTimeout+3*time.Second {
|
|
t.Fatalf("contended write waited %v", waited)
|
|
}
|
|
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) {
|
|
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, "", 200)
|
|
if check := zoneAPITestJSON(t, it.call(t, admin, "zone_check", "", "", "", 200).Body); check != `{"problems":[]}` {
|
|
t.Fatalf("JSON column rows reported as not canonical: %s", check)
|
|
}
|
|
}
|
|
|
|
func TestIntegrationZoneAPIRepairs(t *testing.T) {
|
|
it := newITZoneAPI(t)
|
|
admin := it.admin
|
|
it.call(t, admin, "zone_create", "", "", zoneAPITestCreate, 201)
|
|
tables := it.server.tables
|
|
insert := func(zone, name, recordType, content string) int64 {
|
|
id, err := it.db.rootExec(t, tables.sql("INSERT INTO {records} (`zone`, `name`, `ttl`, `content`, `record_type`) VALUES (?, ?, 60, ?, ?)"),
|
|
zone, name, content, recordType).LastInsertId()
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
return id
|
|
}
|
|
undotted := insert("example.org", "undotted", "A", `{"ip":"192.0.2.1"}`)
|
|
upper := insert("EXAMPLE.ORG.", "upper", "A", `{"ip":"192.0.2.2"}`)
|
|
insert("ex\u00e4mple.org.", "accent", "A", `{"ip":"192.0.2.3"}`)
|
|
insert("example.org..", "dots", "A", `{"ip":"192.0.2.4"}`)
|
|
insert("sub.example.org.", "", "A", `{"ip":"192.0.2.5"}`)
|
|
|
|
zones, err := it.records.ListZones(t.Context())
|
|
if err != nil || len(zones) != 4 || zones[0].Zone != zoneAPITestName || zones[0].RecordCount != 5 || !zones[0].SOAContent.Valid ||
|
|
zones[1].Zone != "example.org.." || zones[2].Zone != "ex\u00e4mple.org." || zones[3].Zone != "sub.example.org." {
|
|
t.Fatalf("zones = %+v, %v", zones, err)
|
|
}
|
|
it.grant(t, zoneAPITestName)
|
|
mine, err := it.records.ListZonesOfUser(t.Context(), it.user.ID)
|
|
if err != nil || len(mine) != 1 || mine[0].Zone != zoneAPITestName || mine[0].RecordCount != 5 {
|
|
t.Fatalf("delegated zones = %+v, %v", mine, err)
|
|
}
|
|
if exists, err := it.records.ZoneExists(t.Context(), "example.org."); !exists || err != nil {
|
|
t.Fatal(exists, err)
|
|
}
|
|
rows := it.rows(t)
|
|
if len(rows) != 5 {
|
|
t.Fatalf("zone rows = %+v", rows)
|
|
}
|
|
for _, id := range []int64{undotted, upper} {
|
|
current, err := it.records.RecordByID(t.Context(), id)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
body := zoneAPITestJSON(t, map[string]any{"name": current.Name, "type": "A", "ttl": 60, "data": json.RawMessage(current.Content.String)})
|
|
it.call(t, it.user, "record_update", strconv.FormatInt(id, 10), recordETag(current), body, 200)
|
|
repaired, err := it.records.RecordByID(t.Context(), id)
|
|
if err != nil || repaired.Zone != zoneAPITestName {
|
|
t.Fatalf("record %d not repaired: %+v, %v", id, repaired, err)
|
|
}
|
|
}
|
|
it.serial(t, newSOASerial(modelNow)+2)
|
|
|
|
soa := zoneAPIFindSOA(it.rows(t))
|
|
extra := insert(zoneAPITestName, "below", "SOA", strings.Replace(soa.Content.String, "ns.example.net.", "other.example.net.", 1))
|
|
it.call(t, admin, "record_create", "", "", zoneAPITestRecord, 422)
|
|
stored, err := it.records.RecordByID(t.Context(), extra)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
it.call(t, admin, "soa_update", "", recordETag(stored), strings.Replace(zoneAPITestSOA, "ns.example.net", "other.example.net", 1), 200)
|
|
it.call(t, admin, "record_delete", strconv.FormatInt(soa.ID, 10), recordETag(soa), "", 200)
|
|
rows = it.rows(t)
|
|
final := zoneAPIFindSOA(rows)
|
|
if len(rows) != 5 || final.ID != extra || final.Name != "" {
|
|
t.Fatalf("SOA set not repaired: %+v", rows)
|
|
}
|
|
it.serial(t, newSOASerial(modelNow)+3)
|
|
if check := zoneAPITestJSON(t, it.call(t, admin, "zone_check", "", "", "", 200).Body); strings.Contains(check, `"severity":"error"`) {
|
|
t.Fatalf("errors after the repairs: %s", check)
|
|
}
|
|
it.call(t, admin, "zone_delete", "", "", `{"confirm":"example.org"}`, 204)
|
|
if n := it.db.count(t, tables.sql("SELECT COUNT(*) FROM {records}")); n != 3 {
|
|
t.Fatalf("zone delete left %d rows in total, want the 3 rows of other zones", n)
|
|
}
|
|
}
|
|
|
|
func TestIntegrationUndottedZoneDelegation(t *testing.T) {
|
|
it := newITHTTP(t)
|
|
admin := it.createUser(t, "admin", roleAdmin)
|
|
user := it.createUser(t, "member", roleUser)
|
|
adminToken, userToken := it.token(t, admin), it.token(t, user)
|
|
zonePath := "/zones/" + zoneAPITestName
|
|
request := func(token, method, path, body, etag string, status int) []byte {
|
|
t.Helper()
|
|
r := it.do(t.Context(), webRequest{token: token, method: method, path: apiPrefix + path, body: body,
|
|
header: map[string]string{"If-Match": etag}})
|
|
if r.Code != status {
|
|
t.Fatalf("%s %s: status %d, want %d, body %s", method, path, r.Code, status, r.Body)
|
|
}
|
|
return r.Body.Bytes()
|
|
}
|
|
request(adminToken, http.MethodPost, "/zones", zoneAPITestCreate, "", http.StatusCreated)
|
|
request(adminToken, http.MethodPost, zonePath+"/records", zoneAPITestRecord, "", http.StatusCreated)
|
|
request(adminToken, http.MethodPut, zonePath+"/users/member", "", "", http.StatusNoContent)
|
|
ctx, tables := t.Context(), it.server.tables
|
|
const missing = "missing.example.net."
|
|
if _, err := newDelegationStore(it.server.db, tables).GrantDelegation(ctx, missing, user.ID, admin.ID, webNow); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
undotted := strings.TrimSuffix(zoneAPITestName, ".")
|
|
it.database.rootExec(t, tables.sql("UPDATE {records} SET `zone` = ? WHERE `zone` = ?"), undotted, zoneAPITestName)
|
|
if n := it.database.count(t, tables.sql("SELECT COUNT(*) FROM {records} WHERE `zone` = ?"), zoneAPITestName); n != 0 {
|
|
t.Fatalf("fixture still has %d canonical rows", n)
|
|
}
|
|
var list struct {
|
|
Zones []zoneAPIListItem `json:"zones"`
|
|
}
|
|
if err := json.Unmarshal(request(userToken, http.MethodGet, "/zones", "", "", http.StatusOK), &list); err != nil ||
|
|
len(list.Zones) != 1 || list.Zones[0].Name != zoneAPITestName {
|
|
t.Fatalf("delegated zone list = %+v, error %v", list.Zones, err)
|
|
}
|
|
var account accountResponse
|
|
if err := json.Unmarshal(request(userToken, http.MethodGet, "/account", "", "", http.StatusOK), &account); err != nil ||
|
|
len(account.Zones) != 1 || account.Zones[0] != zoneAPITestName {
|
|
t.Fatalf("delegated account zones = %v, error %v", account.Zones, err)
|
|
}
|
|
var detail userDetail
|
|
if err := json.Unmarshal(request(adminToken, http.MethodGet, "/users/member", "", "", http.StatusOK), &detail); err != nil ||
|
|
len(detail.Zones) != 2 || detail.Zones[0] != (userZoneItem{Zone: zoneAPITestName, Exists: true}) ||
|
|
detail.Zones[1] != (userZoneItem{Zone: missing}) {
|
|
t.Fatalf("admin's view of delegated zones = %+v, error %v", detail.Zones, err)
|
|
}
|
|
records := newRecordStore(it.server.db, tables)
|
|
rows, err := records.ZoneRows(ctx, zoneAPITestName)
|
|
if err != nil || len(rows) != 4 {
|
|
t.Fatalf("zone rows = %+v, error %v", rows, err)
|
|
}
|
|
record := rows[len(rows)-1]
|
|
request(userToken, http.MethodPut, zonePath+"/records/"+strconv.FormatInt(record.ID, 10), zoneAPITestRecord, recordETag(record), http.StatusOK)
|
|
repaired, err := records.RecordByID(ctx, record.ID)
|
|
if err != nil || repaired.Zone != zoneAPITestName {
|
|
t.Fatalf("record not repaired: %+v, error %v", repaired, err)
|
|
}
|
|
}
|
|
|
|
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(itLockPollInterval)
|
|
defer ticker.Stop()
|
|
for {
|
|
waiting, err := it.db.rowLockWaiting(ctx, suffix)
|
|
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))
|
|
}
|
|
})
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestIntegrationDelegationZoneLock(t *testing.T) {
|
|
for _, operation := range []string{opDelegationGrant, opDelegationRevoke} {
|
|
t.Run(operation, func(t *testing.T) {
|
|
it := newITZoneAPI(t)
|
|
it.server.store = newSQLWebStore(it.server.db, it.server.tables)
|
|
it.call(t, it.admin, "zone_create", "", "", zoneAPITestCreate, 201)
|
|
if operation == opDelegationRevoke {
|
|
it.grant(t, zoneAPITestName)
|
|
}
|
|
c := it.request(it.admin, operation, "", "", "")
|
|
c.Vars["username"] = it.user.Username
|
|
result := make(chan error, 1)
|
|
err := runZoneTx(t.Context(), it.server.db, it.server.tables, zoneAPITestName, it.server.log, func(tx *sql.Tx) error {
|
|
go func() {
|
|
var err error
|
|
if operation == opDelegationGrant {
|
|
_, err = handleDelegationGrant(t.Context(), c)
|
|
} else {
|
|
_, err = handleDelegationRevoke(t.Context(), c)
|
|
}
|
|
result <- err
|
|
}()
|
|
select {
|
|
case err := <-result:
|
|
return fmt.Errorf("delegation did not wait for zone lock: %v", err)
|
|
case <-time.After(200 * time.Millisecond):
|
|
}
|
|
if _, err := newDelegationStore(tx, it.server.tables).DeleteZoneDelegations(t.Context(), zoneAPITestName); err != nil {
|
|
return err
|
|
}
|
|
_, err := newRecordStore(tx, it.server.tables).DeleteZoneRecords(t.Context(), zoneAPITestName)
|
|
return err
|
|
})
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
var apiErr *apiError
|
|
if err := <-result; !errors.As(err, &apiErr) || apiErr.Status != http.StatusNotFound {
|
|
t.Fatalf("delegation after delete: %v", err)
|
|
}
|
|
if exists, err := it.delegations.HasDelegation(t.Context(), zoneAPITestName, it.user.ID); err != nil || exists {
|
|
t.Fatalf("orphan delegation: %v, %v", exists, err)
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
func TestIntegrationConcurrentWritesInDistinctZones(t *testing.T) {
|
|
it := newITZoneAPI(t)
|
|
zones := []string{zoneAPITestName, "other.example."}
|
|
for _, zone := range zones {
|
|
body := strings.Replace(zoneAPITestCreate, "Example.ORG", strings.TrimSuffix(zone, "."), 1)
|
|
zoneAPITestStatus(t, t.Context(), zoneAPITestRequest(it.server, it.admin, "zone_create", "", "", "", body), 201)
|
|
}
|
|
ctx, cancel := context.WithTimeout(t.Context(), 10*time.Second)
|
|
defer cancel()
|
|
start := make(chan struct{})
|
|
results := make(chan itZoneResult, len(zones))
|
|
for _, zone := range zones {
|
|
request := zoneAPITestRequest(it.server, it.admin, "record_create", zone, "", "", zoneAPITestRecord)
|
|
go func() {
|
|
<-start
|
|
response, err := zoneAPITestCall(ctx, request)
|
|
results <- itZoneResult{response, err}
|
|
}()
|
|
}
|
|
close(start)
|
|
for range zones {
|
|
if result := <-results; result.err != nil || result.response.Status != 201 {
|
|
t.Fatalf("concurrent write failed: %+v", result)
|
|
}
|
|
}
|
|
it.audit(t, "record_create", len(zones))
|
|
for _, zone := range zones {
|
|
rows, err := it.records.ZoneRows(ctx, zone)
|
|
if err != nil || len(rows) != 4 {
|
|
t.Fatalf("zone %s: found %d rows, error %v", zone, len(rows), err)
|
|
}
|
|
}
|
|
}
|