- refactor(api): use audit operation constants and the shared zone not found error in zone handlers - fix(api): return the stored content of rows with check errors - fix(api): return warnings from record deletes, zone creation and import apply - fix(api): allow repairing rows stored with a non canonical zone and invalid SOA sets - fix(check): accept JSON column formatting and an absent SOA serial as canonical content - fix(ui): match audit diff items by identity instead of array index - fix(ui): count the SOA change once, report import warnings and check the request size - fix(ui): edit the selected SOA row, keep the server order, show error rows raw and report write warnings - test(check): cover triggering and clean pairs with exact codes and record ids - test(records): cover SRV port, SOA timer and CAA value boundaries - test(cli): check the exact check output and the exit code of warning-only zones - refactor(import): order current rows with cmp.Compare - test(check): cover malformed stored content and a mailbox stored as an address - test(api): cover zone write failure paths, ambiguous SOA updates and unchanged record detection
588 lines
23 KiB
Go
588 lines
23 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"
|
|
"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)
|
|
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)
|
|
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, "", 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)
|
|
}
|
|
soa := zoneAPIFindSOA(it.rows(t))
|
|
if !strings.Contains(soa.Content.String, `"retry": 600, "expire"`) {
|
|
t.Fatalf("MySQL did not reformat the SOA content: %s", soa.Content.String)
|
|
}
|
|
}
|
|
|
|
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 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))
|
|
}
|
|
})
|
|
}
|
|
}
|
|
}
|
|
|
|
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 := withZoneLock(t.Context(), it.server.db, it.server.tables, zoneAPITestName, it.server.log, func(conn *sql.Conn) 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):
|
|
}
|
|
return runInTx(t.Context(), conn, func(tx *sql.Tx) error {
|
|
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)
|
|
}
|
|
})
|
|
}
|
|
}
|