diff --git a/handlers_api.go b/handlers_api.go new file mode 100644 index 0000000..b9baee9 --- /dev/null +++ b/handlers_api.go @@ -0,0 +1,1134 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright (C) 2026 Bryan Joshua Pedini + +package main + +import ( + "bytes" + "context" + "database/sql" + "encoding/json" + "errors" + "maps" + "net/http" + "slices" + "strconv" + "strings" + "time" +) + +func zoneAPIHandlers(s *WebServer) map[string]apiHandler { + h := zoneHandlers{s} + return map[string]apiHandler{ + "zone_list": h.listZones, + "zone_create": h.createZone, + "zone_read": h.readZone, + "zone_delete": h.deleteZone, + "record_list": h.listRecords, + "record_create": h.createRecord, + "record_update": h.updateRecord, + "record_delete": h.deleteRecord, + "record_bulk_delete": h.bulkDelete, + "soa_update": h.updateSOA, + "zone_check": h.checkZone, + "check_all": h.checkAll, + "zone_export": h.exportZone, + "zone_import_preview": h.previewImport, + "zone_import": h.applyImport, + } +} + +type zoneHandlers struct { + server *WebServer +} + +func zoneAPINotFound() *apiError { + return &apiError{Status: http.StatusNotFound, Message: "zone not found"} +} + +func zoneAPIFields(fields map[string]string) *apiError { + return &apiError{Status: http.StatusUnprocessableEntity, Message: "validation failed", Fields: fields} +} + +func zoneAPIRecordNotFound() *apiError { + return &apiError{Status: http.StatusNotFound, Message: "record not found"} +} + +func zoneAPIPrecondition() *apiError { + return &apiError{Status: http.StatusPreconditionFailed, Message: "record changed"} +} + +func zoneAPIAdmin(c *apiContext) error { + if !c.Principal.isAdmin() { + return &apiError{Status: http.StatusForbidden, Message: "forbidden"} + } + return nil +} + +func (h zoneHandlers) visibleZones(ctx context.Context, c *apiContext) ([]zoneSummary, error) { + store := newRecordStore(h.server.db, h.server.tables) + if c.Principal.isAdmin() { + return store.ListZones(ctx) + } + return store.ListZonesOfUser(ctx, c.Principal.User.ID) +} + +func (h zoneHandlers) readRows(ctx context.Context, zone string) ([]recordRow, error) { + rows, err := newRecordStore(h.server.db, h.server.tables).ZoneRows(ctx, zone) + if err == nil && len(rows) == 0 { + return nil, zoneAPINotFound() + } + return rows, err +} + +type zoneAPIWrite struct { + ctx context.Context + api *apiContext + records recordStore + delegations delegationStore + rows []recordRow +} + +func (h zoneHandlers) writeZone(ctx context.Context, c *apiContext, creating bool, change func(zoneAPIWrite) (apiResponse, error)) (apiResponse, error) { + var response apiResponse + var committed bool + err := withZoneLock(ctx, h.server.db, h.server.tables, c.Zone, h.server.log, func(conn *sql.Conn) error { + err := runInTx(ctx, conn, func(tx *sql.Tx) error { + w := zoneAPIWrite{ctx: ctx, api: c, records: newRecordStore(tx, h.server.tables), delegations: newDelegationStore(tx, h.server.tables)} + actor, err := newUserStore(tx, h.server.tables).UserByIDForShare(ctx, c.Principal.User.ID) + if err != nil && !errors.Is(err, errRowNotFound) { + return err + } + if err != nil || actor.DeletedAt.Valid || actor.Role != c.Principal.User.Role { + return zoneAPINotFound() + } + if actor.Role == "user" { + allowed, err := w.delegations.HasDelegationForShare(ctx, c.Zone, actor.ID) + if err != nil { + return err + } + if !allowed { + return zoneAPINotFound() + } + } + w.rows, err = w.records.ZoneRowsForUpdate(ctx, c.Zone) + if err != nil { + return err + } + if creating && len(w.rows) != 0 { + return &apiError{Status: http.StatusConflict, Message: "zone already exists"} + } + if !creating && len(w.rows) == 0 { + return zoneAPINotFound() + } + response, err = change(w) + if err != nil { + return err + } + if c.Entry.Before != nil || c.Entry.After != nil { + return c.writeChangeAudit(ctx, tx, response.Status) + } + return nil + }) + committed = err == nil + return err + }) + if !committed { + c.auditDone = false + c.Entry.Before, c.Entry.After = nil, nil + if errors.Is(err, errLockTimeout) { + return apiResponse{}, &apiError{Status: http.StatusServiceUnavailable, Message: "zone busy"} + } + return apiResponse{}, err + } + return response, nil +} + +type zoneAPIAuditRecord struct { + ID int64 `json:"id"` + Zone string `json:"zone"` + Name string `json:"name"` + TTL *int64 `json:"ttl"` + Type string `json:"record_type"` + Content *string `json:"content"` +} + +type zoneAPIAuditDelegation struct { + Zone string `json:"zone"` + Username string `json:"username"` +} + +func zoneAPINullable[T any](value T, valid bool) *T { + if !valid { + return nil + } + return &value +} + +func zoneAPIAuditRows(rows []recordRow, delegations []delegationRow) []any { + values := make([]any, 0, len(rows)+len(delegations)) + for _, row := range rows { + values = append(values, zoneAPIAuditRecord{ + row.ID, row.Zone, row.Name, zoneAPINullable(row.TTL.Int64, row.TTL.Valid), row.RecordType, + zoneAPINullable(row.Content.String, row.Content.Valid), + }) + } + for _, d := range delegations { + values = append(values, zoneAPIAuditDelegation{d.Zone, d.Username}) + } + return values +} + +func zoneAPIAuditChange(c *apiContext, before, after []any, multiple bool) error { + encode := func(values []any) ([]byte, error) { + switch { + case len(values) == 0: + return nil, nil + case !multiple && len(values) == 1: + return json.Marshal(values[0]) + default: + return json.Marshal(values) + } + } + var err error + c.Entry.Before, err = encode(before) + if err != nil { + return err + } + c.Entry.After, err = encode(after) + return err +} + +type zoneAPIListItem struct { + Name string `json:"name"` + Records int64 `json:"records"` + Serial *uint32 `json:"serial"` +} + +type zoneAPISOAFields struct { + NS string `json:"ns"` + MBox string `json:"mbox"` + TTL *int64 `json:"ttl"` + Refresh uint32 `json:"refresh"` + Retry uint32 `json:"retry"` + Expire uint32 `json:"expire"` + MinTTL uint32 `json:"minttl"` +} + +type zoneAPISOAView struct { + zoneAPISOAFields + ID int64 `json:"id"` + ETag string `json:"etag"` + Serial *uint32 `json:"serial"` +} + +type zoneAPIView struct { + zoneAPIListItem + SOA *zoneAPISOAView `json:"soa"` +} + +func zoneAPISerial(row recordRow) *uint32 { + serial, _ := storedSOASerial(row) + return zoneAPINullable(serial, serial != 0) +} + +func zoneAPIFindSOA(rows []recordRow) recordRow { + var first recordRow + for _, row := range rows { + if row.RecordType == "SOA" { + if row.Name == "" { + return row + } + if first.ID == 0 { + first = row + } + } + } + return first +} + +func zoneAPISOADetails(row recordRow, soa soaData) zoneAPISOAFields { + return zoneAPISOAFields{soa.NS, soa.MBox, zoneAPINullable(row.TTL.Int64, row.TTL.Valid), soa.Refresh, soa.Retry, soa.Expire, soa.MinTTL} +} + +func zoneAPISOA(row recordRow, now time.Time) *zoneAPISOAView { + if row.ID == 0 || row.Name != "" || recordHasCheckError(row, now) { + return nil + } + data, err := decodeRecord("SOA", row.Content.String) + if err != nil { + return nil + } + return &zoneAPISOAView{zoneAPISOADetails(row, data.(soaData)), row.ID, recordETag(row), zoneAPISerial(row)} +} + +func zoneAPIETag(etag string) http.Header { + return http.Header{"Etag": {etag}} +} + +func zoneAPISummary(zone string, rows []recordRow, now time.Time, status int) apiResponse { + row := zoneAPIFindSOA(rows) + view := zoneAPIView{zoneAPIListItem{zone, int64(len(rows)), zoneAPISerial(row)}, zoneAPISOA(row, now)} + response := apiResponse{Status: status, Body: view} + if view.SOA != nil { + response.Header = zoneAPIETag(view.SOA.ETag) + } + return response +} + +func (h zoneHandlers) listZones(ctx context.Context, c *apiContext) (apiResponse, error) { + rows, err := h.visibleZones(ctx, c) + if err != nil { + return apiResponse{}, err + } + zones := make([]zoneAPIListItem, 0, len(rows)) + for _, row := range rows { + zones = append(zones, zoneAPIListItem{row.Zone, row.RecordCount, zoneAPISerial(recordRow{Content: row.SOAContent})}) + } + return apiResponse{Status: http.StatusOK, Body: map[string]any{"zones": zones}}, nil +} + +func (h zoneHandlers) readZone(ctx context.Context, c *apiContext) (apiResponse, error) { + rows, err := h.readRows(ctx, c.Zone) + if err != nil { + return apiResponse{}, err + } + return zoneAPISummary(c.Zone, rows, c.Now, http.StatusOK), nil +} + +type zoneAPISOAInput struct { + NS string `json:"ns"` + MBox string `json:"mbox"` + TTL json.RawMessage `json:"ttl"` + Refresh json.RawMessage `json:"refresh"` + Retry json.RawMessage `json:"retry"` + Expire json.RawMessage `json:"expire"` + MinTTL json.RawMessage `json:"minttl"` +} + +func zoneAPISeconds(raw json.RawMessage, key string, fields map[string]string) int64 { + var value int64 + if string(raw) == "null" || json.Unmarshal(raw, &value) != nil || value < 0 || value > maxRecordSeconds { + fields[key] = "must be an integer from 0 to 2147483647" + return -1 + } + return value +} + +func (in zoneAPISOAInput) zoneSpec(zone string, fields map[string]string) newZoneSpec { + timer := func(raw json.RawMessage, key string) uint32 { return uint32(zoneAPISeconds(raw, key, fields)) } + return newZoneSpec{ + Zone: zone, PrimaryNS: in.NS, Mailbox: in.MBox, TTL: zoneAPISeconds(in.TTL, "ttl", fields), + Refresh: timer(in.Refresh, "refresh"), Retry: timer(in.Retry, "retry"), + Expire: timer(in.Expire, "expire"), MinTTL: timer(in.MinTTL, "minttl"), + } +} + +func (h zoneHandlers) createZone(ctx context.Context, c *apiContext) (apiResponse, error) { + if err := zoneAPIAdmin(c); err != nil { + return apiResponse{}, err + } + var in struct { + zoneAPISOAInput + Name string `json:"name"` + ExtraNS []string `json:"extra_ns"` + } + if err := c.decodeJSON(&in); err != nil { + return apiResponse{}, err + } + zone, err := normalizeZone(in.Name) + if err != nil { + return apiResponse{}, zoneAPIFields(map[string]string{"name": err.Error()}) + } + c.Zone = zone + c.Entry.Zone = sql.NullString{String: zone, Valid: true} + return h.writeZone(ctx, c, true, func(w zoneAPIWrite) (apiResponse, error) { + fields := make(map[string]string) + spec := in.zoneSpec(zone, fields) + if len(fields) != 0 { + return apiResponse{}, zoneAPIFields(fields) + } + spec.ExtraNS = in.ExtraNS + rows, fields := newZoneRows(spec, c.Now) + if len(fields) != 0 { + mapped := make(map[string]string) + for key, message := range fields { + switch { + case key == "MBox": + key = "mbox" + case strings.HasPrefix(key, "extra_ns."): + key = "extra_ns" + } + mapped[key] = message + } + return apiResponse{}, zoneAPIFields(mapped) + } + deleted, err := w.delegations.DeleteZoneDelegations(ctx, zone) + if err != nil { + return apiResponse{}, err + } + for i := range rows { + rows[i].ID, err = w.records.InsertRecord(ctx, rows[i]) + if err != nil { + return apiResponse{}, err + } + } + rows, err = w.writtenRows(rows) + if err != nil { + return apiResponse{}, err + } + if err := zoneAPIAuditChange(c, nil, zoneAPIAuditRows(rows, deleted), true); err != nil { + return apiResponse{}, err + } + return zoneAPISummary(zone, rows, c.Now, http.StatusCreated), nil + }) +} + +func (h zoneHandlers) deleteZone(ctx context.Context, c *apiContext) (apiResponse, error) { + if err := zoneAPIAdmin(c); err != nil { + return apiResponse{}, err + } + var in struct { + Confirm string `json:"confirm"` + } + decodeErr := c.decodeJSON(&in) + return h.writeZone(ctx, c, false, func(w zoneAPIWrite) (apiResponse, error) { + if decodeErr != nil { + return apiResponse{}, decodeErr + } + confirmation, err := normalizeZone(in.Confirm) + if err != nil || confirmation != c.Zone { + return apiResponse{}, zoneAPIFields(map[string]string{"confirm": "must match the zone name"}) + } + deleted, err := w.delegations.DeleteZoneDelegations(ctx, c.Zone) + if err != nil { + return apiResponse{}, err + } + if _, err := w.records.DeleteZoneRecords(ctx, c.Zone); err != nil { + return apiResponse{}, err + } + if err := zoneAPIAuditChange(c, zoneAPIAuditRows(w.rows, deleted), nil, len(w.rows)+len(deleted) > 1); err != nil { + return apiResponse{}, err + } + return apiResponse{Status: http.StatusNoContent}, nil + }) +} + +type zoneAPIProblem struct { + Code string `json:"code"` + Severity string `json:"severity"` + Message string `json:"message"` +} + +func zoneAPIProblems(problems []zoneProblem) []zoneAPIProblem { + result := make([]zoneAPIProblem, 0, len(problems)) + for _, p := range problems { + result = append(result, zoneAPIProblem{p.Code, p.Severity, p.Message}) + } + return result +} + +type zoneAPIRecord struct { + ID int64 `json:"id"` + Name string `json:"name"` + FQDN string `json:"fqdn"` + Type string `json:"type"` + TTL *int64 `json:"ttl"` + Data any `json:"data"` + Raw *string `json:"raw"` + ETag string `json:"etag"` + Problems []zoneAPIProblem `json:"problems"` +} + +func zoneAPIRecordView(row recordRow, problems []zoneProblem) zoneAPIRecord { + var data any + var raw *string + if row.Content.Valid { + decoded, err := inspectRecordContent(row.RecordType, row.Content.String) + if err == nil && len(decoded.fields) == 0 && decoded.decodeErr == nil { + data = decoded.data + } else { + raw = &row.Content.String + } + } + return zoneAPIRecord{ + row.ID, row.Name, recordFQDN(row), row.RecordType, zoneAPINullable(row.TTL.Int64, row.TTL.Valid), + data, raw, recordETag(row), zoneAPIProblems(problems), + } +} + +func (h zoneHandlers) listRecords(ctx context.Context, c *apiContext) (apiResponse, error) { + rows, err := h.readRows(ctx, c.Zone) + if err != nil { + return apiResponse{}, err + } + problemsByID := make(map[int64][]zoneProblem) + for _, p := range checkZone(c.Zone, rows, c.Now) { + problemsByID[p.RecordID] = append(problemsByID[p.RecordID], p) + } + sortZoneRecords(rows, c.Now) + records := make([]zoneAPIRecord, 0, len(rows)) + for _, row := range rows { + records = append(records, zoneAPIRecordView(row, problemsByID[row.ID])) + } + return apiResponse{Status: http.StatusOK, Body: map[string]any{"records": records}}, nil +} + +type zoneAPICheckProblem struct { + zoneAPIProblem + Zone string `json:"zone"` + ID *int64 `json:"id"` + Name *string `json:"name"` + Type *string `json:"type"` +} + +func zoneAPICheck(zone string, rows []recordRow, now time.Time, result []zoneAPICheckProblem) []zoneAPICheckProblem { + for _, p := range checkZone(zone, rows, now) { + rowProblem := p.RecordID != 0 + result = append(result, zoneAPICheckProblem{ + zoneAPIProblem{p.Code, p.Severity, p.Message}, zone, + zoneAPINullable(p.RecordID, rowProblem), zoneAPINullable(p.Name, rowProblem), zoneAPINullable(p.Type, rowProblem), + }) + } + return result +} + +func (h zoneHandlers) checkZone(ctx context.Context, c *apiContext) (apiResponse, error) { + rows, err := h.readRows(ctx, c.Zone) + if err != nil { + return apiResponse{}, err + } + problems := zoneAPICheck(c.Zone, rows, c.Now, []zoneAPICheckProblem{}) + return apiResponse{Status: http.StatusOK, Body: map[string]any{"problems": problems}}, nil +} + +func (h zoneHandlers) checkAll(ctx context.Context, c *apiContext) (apiResponse, error) { + problems := []zoneAPICheckProblem{} + err := runInTx(ctx, h.server.db, func(tx *sql.Tx) error { + store := newRecordStore(tx, h.server.tables) + var zones []zoneSummary + var err error + if c.Principal.isAdmin() { + zones, err = store.ListZones(ctx) + } else { + zones, err = store.ListZonesOfUser(ctx, c.Principal.User.ID) + } + if err != nil { + return err + } + for _, zone := range zones { + rows, err := store.ZoneRows(ctx, zone.Zone) + if err != nil { + return err + } + problems = zoneAPICheck(zone.Zone, rows, c.Now, problems) + } + return nil + }) + if err != nil { + return apiResponse{}, err + } + return apiResponse{Status: http.StatusOK, Body: map[string]any{"problems": problems}}, nil +} + +type zoneAPIRecordInput struct { + Name string `json:"name"` + Type string `json:"type"` + TTL json.RawMessage `json:"ttl"` + Data json.RawMessage `json:"data"` +} + +func (in zoneAPIRecordInput) record(c *apiContext) (recordRow, error) { + ttl := zoneAPISeconds(in.TTL, "ttl", make(map[string]string)) + row, fields := validateRecord(c.Zone, in.Name, in.Type, ttl, in.Data, c.Now) + if len(fields) != 0 { + mapped := make(map[string]string) + for key, message := range fields { + switch key { + case "content": + key = "data" + case "name", "type", "ttl": + default: + key = "data." + key + } + mapped[key] = message + } + return recordRow{}, zoneAPIFields(mapped) + } + if row.RecordType == "SOA" { + return withSOASerial(row, newSOASerial(c.Now), true) + } + return row, nil +} + +func zoneAPIRuleError(problems []zoneProblem, field string) error { + if len(problems) == 0 { + return nil + } + p := problems[0] + if field == "type" { + for _, problem := range problems { + if problem.Code == "soa_delete" || problem.Code == "ns_apex_missing" { + p = problem + break + } + } + if p.Code == "cname_conflict" || p.Code == "cname_apex" || p.Code == "duplicate" { + field = "name" + } + } + return zoneAPIFields(map[string]string{field: p.Message}) +} + +func (w zoneAPIWrite) persist(changes zoneChanges, multiple bool) ([]recordRow, error) { + if changes.empty() { + return nil, nil + } + serialRow, err := updateSOASerial(w.rows, changes, w.api.Now) + if err != nil { + return nil, zoneAPIFields(map[string]string{"type": "repair the SOA before changing other records"}) + } + updates := make(map[int64]recordRow, len(changes.Updates)+1) + for _, row := range changes.Updates { + updates[row.ID] = row + } + if changes.SOAUpdate != nil { + updates[changes.SOAUpdate.ID] = *changes.SOAUpdate + } + if serialRow != nil { + updates[serialRow.ID] = *serialRow + } + deletes := make(map[int64]bool, len(changes.Deletes)) + for _, id := range changes.Deletes { + deletes[id] = true + } + + var before, after []recordRow + for _, row := range w.rows { + switch { + case deletes[row.ID]: + if _, err := w.records.DeleteRecord(w.ctx, row.ID); err != nil { + return nil, err + } + before = append(before, row) + case updates[row.ID].ID != 0: + updated := updates[row.ID] + if err := w.records.UpdateRecord(w.ctx, updated); err != nil { + return nil, err + } + before = append(before, row) + after = append(after, updated) + } + } + for _, row := range changes.Creates { + row.ID, err = w.records.InsertRecord(w.ctx, row) + if err != nil { + return nil, err + } + after = append(after, row) + } + after, err = w.writtenRows(after) + if err != nil { + return nil, err + } + multiple = multiple || len(updates)+len(deletes)+len(changes.Creates) > 1 + err = zoneAPIAuditChange(w.api, zoneAPIAuditRows(before, nil), zoneAPIAuditRows(after, nil), multiple) + return after, err +} + +func (w zoneAPIWrite) writtenRows(written []recordRow) ([]recordRow, error) { + if len(written) == 0 { + return nil, nil + } + rows, err := w.records.ZoneRows(w.ctx, w.api.Zone) + if err != nil { + return nil, err + } + byID := zoneAPIRowsByID(rows) + for i := range written { + row, ok := byID[written[i].ID] + if !ok { + return nil, errors.New("written record not found in zone") + } + written[i] = row + } + return written, nil +} + +func zoneAPIRecordResponse(row recordRow, warnings []zoneProblem, now time.Time, status int) apiResponse { + view := zoneAPIRecordView(row, checkRecord(row, now)) + return apiResponse{ + Status: status, Header: zoneAPIETag(view.ETag), + Body: map[string]any{"record": view, "warnings": zoneAPIProblems(warnings)}, + } +} + +func (h zoneHandlers) createRecord(ctx context.Context, c *apiContext) (apiResponse, error) { + var in zoneAPIRecordInput + decodeErr := c.decodeJSON(&in) + return h.writeZone(ctx, c, false, func(w zoneAPIWrite) (apiResponse, error) { + if decodeErr != nil { + return apiResponse{}, decodeErr + } + row, err := in.record(c) + if err != nil { + return apiResponse{}, err + } + changes := zoneChanges{Creates: []recordRow{row}} + problems, warnings := validateZoneChanges(c.Zone, w.rows, changes) + if err := zoneAPIRuleError(problems, "type"); err != nil { + return apiResponse{}, err + } + after, err := w.persist(changes, false) + if err != nil { + return apiResponse{}, err + } + row = after[len(after)-1] + c.Entry.RecordID = sql.NullInt64{Int64: row.ID, Valid: true} + return zoneAPIRecordResponse(row, warnings, c.Now, http.StatusCreated), nil + }) +} + +func zoneAPIRequestedID(c *apiContext) (int64, error) { + id, err := strconv.ParseInt(c.Vars["id"], 10, 32) + if err != nil || id <= 0 { + return 0, &apiError{Status: http.StatusBadRequest, Message: "invalid record id"} + } + c.Entry.RecordID = sql.NullInt64{Int64: id, Valid: true} + return id, nil +} + +func (w zoneAPIWrite) findRecord(id int64, rowsByID map[int64]recordRow) (recordRow, error) { + if row, ok := rowsByID[id]; ok { + return row, nil + } + _, err := w.records.RecordByID(w.ctx, id) + switch { + case errors.Is(err, errRowNotFound): + return recordRow{}, nil + case err != nil: + return recordRow{}, err + default: + return recordRow{}, zoneAPIRecordNotFound() + } +} + +func zoneAPIRowsByID(rows []recordRow) map[int64]recordRow { + byID := make(map[int64]recordRow, len(rows)) + for _, row := range rows { + byID[row.ID] = row + } + return byID +} + +func zoneAPIMatch(row recordRow, etag string) error { + if etag == "" { + return &apiError{Status: http.StatusPreconditionRequired, Message: "If-Match is required"} + } + if row.ID == 0 || recordETag(row) != etag { + return zoneAPIPrecondition() + } + return nil +} + +func zoneAPIRecordUnchanged(current, proposed recordRow) bool { + if current == proposed { + return true + } + if !current.Content.Valid || !proposed.Content.Valid { + return false + } + var have, want map[string]json.RawMessage + if json.Unmarshal([]byte(current.Content.String), &have) != nil || + json.Unmarshal([]byte(proposed.Content.String), &want) != nil { + return false + } + current.Content = proposed.Content + return current == proposed && maps.EqualFunc(have, want, func(a, b json.RawMessage) bool { + return bytes.Equal(a, b) + }) +} + +func (h zoneHandlers) updateRecord(ctx context.Context, c *apiContext) (apiResponse, error) { + id, idErr := zoneAPIRequestedID(c) + var in zoneAPIRecordInput + decodeErr := c.decodeJSON(&in) + return h.writeZone(ctx, c, false, func(w zoneAPIWrite) (apiResponse, error) { + if idErr != nil { + return apiResponse{}, idErr + } + current, err := w.findRecord(id, zoneAPIRowsByID(w.rows)) + if err != nil { + return apiResponse{}, err + } + if err := zoneAPIMatch(current, c.Request.Header.Get("If-Match")); err != nil { + return apiResponse{}, err + } + if decodeErr != nil { + return apiResponse{}, decodeErr + } + proposed, err := in.record(c) + if err != nil { + return apiResponse{}, err + } + proposed.ID = current.ID + if current.RecordType == "SOA" && proposed.RecordType == "SOA" { + proposed, err = prepareSOAUpdate(current, proposed) + if err != nil { + return apiResponse{}, err + } + } + changes := zoneChanges{} + if !zoneAPIRecordUnchanged(current, proposed) { + changes.Updates = []recordRow{proposed} + } + problems, warnings := validateZoneChanges(c.Zone, w.rows, changes) + if err := zoneAPIRuleError(problems, "type"); err != nil { + return apiResponse{}, err + } + after, err := w.persist(changes, false) + if err != nil { + return apiResponse{}, err + } + return zoneAPIRecordResponse(zoneAPIUpdatedRow(after, current), warnings, c.Now, http.StatusOK), nil + }) +} + +func zoneAPIUpdatedRow(after []recordRow, original recordRow) recordRow { + for _, row := range after { + if row.ID == original.ID { + return row + } + } + return original +} + +func (h zoneHandlers) deleteRecord(ctx context.Context, c *apiContext) (apiResponse, error) { + id, idErr := zoneAPIRequestedID(c) + return h.writeZone(ctx, c, false, func(w zoneAPIWrite) (apiResponse, error) { + if idErr != nil { + return apiResponse{}, idErr + } + current, err := w.findRecord(id, zoneAPIRowsByID(w.rows)) + if err != nil { + return apiResponse{}, err + } + if err := zoneAPIMatch(current, c.Request.Header.Get("If-Match")); err != nil { + return apiResponse{}, err + } + changes := zoneChanges{Deletes: []int64{id}} + problems, _ := validateZoneChanges(c.Zone, w.rows, changes) + if err := zoneAPIRuleError(problems, "type"); err != nil { + return apiResponse{}, err + } + if _, err := w.persist(changes, false); err != nil { + return apiResponse{}, err + } + return apiResponse{Status: http.StatusNoContent}, nil + }) +} + +func (h zoneHandlers) bulkDelete(ctx context.Context, c *apiContext) (apiResponse, error) { + var in struct { + Records []struct { + ID json.RawMessage `json:"id"` + ETag string `json:"etag"` + } `json:"records"` + } + decodeErr := c.decodeJSON(&in) + return h.writeZone(ctx, c, false, func(w zoneAPIWrite) (apiResponse, error) { + if decodeErr != nil { + return apiResponse{}, decodeErr + } + if len(in.Records) == 0 { + return apiResponse{}, zoneAPIFields(map[string]string{"records": "select at least one record"}) + } + byID := zoneAPIRowsByID(w.rows) + seen := make(map[int64]bool, len(in.Records)) + changes := zoneChanges{Deletes: make([]int64, 0, len(in.Records))} + for _, item := range in.Records { + var id int64 + if json.Unmarshal(item.ID, &id) != nil || id <= 0 || seen[id] { + return apiResponse{}, zoneAPIFields(map[string]string{"records": "record ids must be distinct positive integers"}) + } + row, err := w.findRecord(id, byID) + if err != nil { + return apiResponse{}, err + } + if row.ID == 0 || item.ETag != recordETag(row) { + return apiResponse{}, zoneAPIPrecondition() + } + seen[id] = true + changes.Deletes = append(changes.Deletes, id) + } + problems, _ := validateZoneChanges(c.Zone, w.rows, changes) + if err := zoneAPIRuleError(problems, "records"); err != nil { + return apiResponse{}, err + } + if _, err := w.persist(changes, true); err != nil { + return apiResponse{}, err + } + return apiResponse{Status: http.StatusOK, Body: map[string]int{"deleted": len(changes.Deletes)}}, nil + }) +} + +func (h zoneHandlers) updateSOA(ctx context.Context, c *apiContext) (apiResponse, error) { + var in struct { + zoneAPISOAInput + ManagedSerial bool `json:"managed_serial"` + } + decodeErr := c.decodeJSON(&in) + return h.writeZone(ctx, c, false, func(w zoneAPIWrite) (apiResponse, error) { + current := zoneAPIFindSOA(w.rows) + if current.ID != 0 { + c.Entry.RecordID = sql.NullInt64{Int64: current.ID, Valid: true} + } + if err := zoneAPIMatch(current, c.Request.Header.Get("If-Match")); err != nil { + return apiResponse{}, err + } + if decodeErr != nil { + return apiResponse{}, decodeErr + } + fields := make(map[string]string) + spec := in.zoneSpec(c.Zone, fields) + if len(fields) != 0 { + return apiResponse{}, zoneAPIFields(fields) + } + content, _ := encodeRecord(soaData{ + NS: spec.PrimaryNS, MBox: spec.Mailbox, Refresh: spec.Refresh, + Retry: spec.Retry, Expire: spec.Expire, MinTTL: spec.MinTTL, + }) + proposed, fields := validateRecord(c.Zone, "", "SOA", spec.TTL, json.RawMessage(content), c.Now) + if len(fields) != 0 { + if message, ok := fields["MBox"]; ok { + delete(fields, "MBox") + fields["mbox"] = message + } + if message, ok := fields["name"]; ok { + delete(fields, "name") + fields["ns"] = message + } + return apiResponse{}, zoneAPIFields(fields) + } + proposed, err := prepareSOAUpdate(current, proposed) + if err != nil { + return apiResponse{}, err + } + serial, _ := storedSOASerial(current) + changes := zoneChanges{ManageSerial: in.ManagedSerial && serial == 0} + if !zoneAPIRecordUnchanged(current, proposed) { + changes.SOAUpdate = &proposed + } + problems, warnings := validateZoneChanges(c.Zone, w.rows, changes) + if err := zoneAPIRuleError(problems, "ns"); err != nil { + return apiResponse{}, err + } + after, err := w.persist(changes, false) + if err != nil { + return apiResponse{}, err + } + soa := zoneAPISOA(zoneAPIUpdatedRow(after, current), c.Now) + return apiResponse{ + Status: http.StatusOK, Header: zoneAPIETag(soa.ETag), + Body: map[string]any{"soa": soa, "warnings": zoneAPIProblems(warnings)}, + }, nil + }) +} + +func (h zoneHandlers) exportZone(ctx context.Context, c *apiContext) (apiResponse, error) { + rows, err := h.readRows(ctx, c.Zone) + if err != nil { + return apiResponse{}, err + } + file, err := exportZoneFile(c.Zone, rows, c.Now) + if err != nil { + return apiResponse{}, err + } + return apiResponse{ + Status: http.StatusOK, Raw: []byte(file), ContentType: "text/plain", + Header: http.Header{"Content-Disposition": {`attachment; filename="` + c.Zone + `zone"`}}, + }, nil +} + +type zoneAPIImportInput struct { + Mode string `json:"mode"` + Content *string `json:"content"` +} + +func (in zoneAPIImportInput) validate() error { + fields := make(map[string]string) + if in.Mode != "merge" && in.Mode != "replace" { + fields["mode"] = "must be merge or replace" + } + if in.Content == nil { + fields["content"] = "is required" + } + if len(fields) != 0 { + return zoneAPIFields(fields) + } + return nil +} + +type zoneAPIImportMessage struct { + Line int `json:"line,omitempty"` + Message string `json:"message"` +} + +func zoneAPIImportErrors(messages []zoneAPIImportMessage) error { + return &apiError{ + Status: http.StatusUnprocessableEntity, Message: "the file has errors", + Extra: map[string]any{"errors": messages}, + } +} + +func (in zoneAPIImportInput) diff(c *apiContext, rows []recordRow) (zoneImportDiff, []int, error) { + imported, err := parseZoneFile(c.Zone, strings.NewReader(*in.Content), c.Now) + if err != nil { + var invalid *zoneFileRecordError + var located *zoneFileLocatedError + switch { + case errors.Is(err, errZoneFileTooLarge): + return zoneImportDiff{}, nil, &apiError{Status: http.StatusRequestEntityTooLarge, Message: "request body too large"} + case errors.As(err, &invalid): + messages := make([]zoneAPIImportMessage, 0, len(invalid.Fields)) + for _, key := range slices.Sorted(maps.Keys(invalid.Fields)) { + messages = append(messages, zoneAPIImportMessage{invalid.Line, key + ": " + invalid.Fields[key]}) + } + return zoneImportDiff{}, nil, zoneAPIImportErrors(messages) + case errors.As(err, &located): + message, _, _ := strings.Cut(err.Error(), " at line: ") + return zoneImportDiff{}, nil, zoneAPIImportErrors([]zoneAPIImportMessage{{located.line, message}}) + default: + return zoneImportDiff{}, nil, err + } + } + diff, err := diffZoneImport(c.Zone, rows, imported, in.Mode, c.Now) + if err != nil { + return zoneImportDiff{}, nil, err + } + if len(diff.Problems) != 0 { + messages := make([]zoneAPIImportMessage, 0, len(diff.Problems)) + for _, problem := range diff.Problems { + messages = append(messages, zoneAPIImportMessage{Message: problem.Message}) + } + return zoneImportDiff{}, nil, zoneAPIImportErrors(messages) + } + return diff, imported.WarningLines, nil +} + +type zoneAPIImportRow struct { + Name string `json:"name"` + Type string `json:"type"` + TTL *int64 `json:"ttl"` + Value string `json:"value"` +} + +type zoneAPIImportUpdate struct { + zoneAPIImportRow + OldTTL *int64 `json:"old_ttl"` +} + +type zoneAPIImportSkip struct { + Line int `json:"line"` + Text string `json:"text"` + Reason string `json:"reason"` +} + +type zoneAPIImportPreview struct { + Fingerprint string `json:"fingerprint"` + Added []zoneAPIImportRow `json:"added"` + Updated []zoneAPIImportUpdate `json:"updated"` + Deleted []zoneAPIImportRow `json:"deleted"` + Unchanged int `json:"unchanged"` + Skipped []zoneAPIImportSkip `json:"skipped"` + SOA *zoneAPISOAFields `json:"soa"` + Warnings []zoneAPIImportMessage `json:"warnings"` +} + +func zoneAPIImportPreviewView(diff zoneImportDiff, lines []int, now time.Time) zoneAPIImportPreview { + result := zoneAPIImportPreview{ + Fingerprint: diff.Fingerprint, Unchanged: len(diff.Unchanged), + Added: make([]zoneAPIImportRow, 0, len(diff.Changes.Creates)), + Updated: make([]zoneAPIImportUpdate, 0, len(diff.Updated)), + Deleted: make([]zoneAPIImportRow, 0, len(diff.Deleted)), + Skipped: make([]zoneAPIImportSkip, 0, len(diff.Skipped)), + Warnings: make([]zoneAPIImportMessage, 0, len(diff.Warnings)), + } + view := func(row recordRow) zoneAPIImportRow { + return zoneAPIImportRow{row.Name, row.RecordType, zoneAPINullable(row.TTL.Int64, row.TTL.Valid), recordValue(row, now)} + } + for _, row := range diff.Changes.Creates { + result.Added = append(result.Added, view(row)) + } + for _, change := range diff.Updated { + result.Updated = append(result.Updated, zoneAPIImportUpdate{view(change.After), zoneAPINullable(change.Before.TTL.Int64, change.Before.TTL.Valid)}) + } + for _, row := range diff.Deleted { + result.Deleted = append(result.Deleted, view(row)) + } + if row := diff.Changes.SOAUpdate; row != nil { + if data, err := decodeRecord("SOA", row.Content.String); err == nil { + fields := zoneAPISOADetails(*row, data.(soaData)) + result.SOA = &fields + } + } + for _, item := range diff.Skipped { + result.Skipped = append(result.Skipped, zoneAPIImportSkip{item.Line, item.Text, item.Reason}) + } + for i, problem := range diff.Warnings { + message := zoneAPIImportMessage{Message: problem.Message} + if i < len(lines) { + message.Line = lines[i] + } + result.Warnings = append(result.Warnings, message) + } + return result +} + +func (h zoneHandlers) previewImport(ctx context.Context, c *apiContext) (apiResponse, error) { + rows, err := h.readRows(ctx, c.Zone) + if err != nil { + return apiResponse{}, err + } + var in zoneAPIImportInput + if err := c.decodeJSON(&in); err != nil { + return apiResponse{}, err + } + if err := in.validate(); err != nil { + return apiResponse{}, err + } + diff, lines, err := in.diff(c, rows) + if err != nil { + return apiResponse{}, err + } + return apiResponse{Status: http.StatusOK, Body: zoneAPIImportPreviewView(diff, lines, c.Now)}, nil +} + +func (h zoneHandlers) applyImport(ctx context.Context, c *apiContext) (apiResponse, error) { + var in struct { + zoneAPIImportInput + Fingerprint string `json:"fingerprint"` + } + decodeErr := c.decodeJSON(&in) + return h.writeZone(ctx, c, false, func(w zoneAPIWrite) (apiResponse, error) { + if decodeErr != nil { + return apiResponse{}, decodeErr + } + if err := in.validate(); err != nil { + return apiResponse{}, err + } + if in.Fingerprint != zoneFingerprint(w.rows) { + return apiResponse{}, &apiError{Status: http.StatusConflict, Message: "zone changed since preview"} + } + diff, _, err := in.diff(c, w.rows) + if err != nil { + return apiResponse{}, err + } + if _, err := w.persist(diff.Changes, true); err != nil { + return apiResponse{}, err + } + return apiResponse{Status: http.StatusOK, Body: map[string]int{ + "added": len(diff.Changes.Creates), "updated": len(diff.Updated), "deleted": len(diff.Deleted), + }}, nil + }) +} diff --git a/handlers_api_test.go b/handlers_api_test.go new file mode 100644 index 0000000..c1e9c71 --- /dev/null +++ b/handlers_api_test.go @@ -0,0 +1,679 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright (C) 2026 Bryan Joshua Pedini + +package main + +import ( + "context" + "database/sql" + "database/sql/driver" + "encoding/json" + "errors" + "net/http" + "net/http/httptest" + "slices" + "strconv" + "strings" + "testing" +) + +const zoneAPITestName = "example.org." +const zoneAPITestSOA = `{"ns":"ns.example.net","mbox":"hostmaster@example.org","ttl":3600,"refresh":3600,"retry":600,"expire":604800,"minttl":300}` + +var zoneAPITestCreate = `{"name":"Example.ORG","extra_ns":["backup.example.net"],` + zoneAPITestSOA[1:] + +const zoneAPITestRecord = `{"name":"new","type":"A","ttl":60,"data":{"ip":"192.0.2.10"}}` + +func zoneAPITestRequest(server *WebServer, actor userRow, operation, zone, id, etag, body string) *apiContext { + method := http.MethodGet + switch operation { + case "zone_create", "record_create", "record_bulk_delete", "zone_import_preview", "zone_import": + method = http.MethodPost + case "record_update", "soa_update": + method = http.MethodPut + case "zone_delete", "record_delete": + method = http.MethodDelete + } + req := httptest.NewRequest(method, "/api/v1/test", strings.NewReader(body)) + if body != "" { + req.Header.Set("Content-Type", "application/json") + } + if etag != "" { + req.Header.Set("If-Match", etag) + } + entry := &auditEntry{ + Time: modelNow, UserID: sql.NullInt64{Int64: actor.ID, Valid: true}, Actor: actor.Username, + Origin: "127.0.0.1", Operation: operation, Zone: sql.NullString{String: zone, Valid: zone != ""}, + } + return &apiContext{ + Request: req, Principal: principal{User: actor}, Zone: zone, Vars: map[string]string{"id": id}, + Now: modelNow, Entry: entry, Server: server, + } +} + +func zoneAPITestCall(ctx context.Context, c *apiContext) (apiResponse, error) { + return zoneAPIHandlers(c.Server)[c.Entry.Operation](ctx, c) +} + +func zoneAPITestStatus(t *testing.T, ctx context.Context, c *apiContext, status int) apiResponse { + t.Helper() + resp, err := zoneAPITestCall(ctx, c) + if status >= 400 { + var apiErr *apiError + if !errors.As(err, &apiErr) || apiErr.Status != status { + t.Fatalf("%s: got response %+v, error %v, want %d", c.Entry.Operation, resp, err, status) + } + return resp + } + if err != nil || resp.Status != status { + t.Fatalf("%s: got response %+v, error %v, want %d", c.Entry.Operation, resp, err, status) + } + return resp +} + +func zoneAPITestJSON(t *testing.T, value any) string { + t.Helper() + body, err := json.Marshal(value) + if err != nil { + t.Fatal(err) + } + return string(body) +} + +func zoneAPITestRows(t *testing.T) []recordRow { + t.Helper() + rows, fields := newZoneRows(newZoneSpec{ + Zone: zoneAPITestName, PrimaryNS: "ns.example.net", Mailbox: "hostmaster@example.org", + TTL: 3600, Refresh: 3600, Retry: 600, Expire: 604800, MinTTL: 300, + }, modelNow) + if len(fields) != 0 { + t.Fatal(fields) + } + for _, name := range []string{"first", "second"} { + row, fields := validateRecord(zoneAPITestName, name, "A", 60, []byte(`{"ip":"192.0.2.1"}`), modelNow) + if len(fields) != 0 { + t.Fatal(fields) + } + rows = append(rows, row) + } + for i := range rows { + rows[i].ID = int64(i + 1) + } + return rows +} + +type zoneAPITestDB struct { + t *testing.T + rows []recordRow + foreign recordRow + actor userRow + hasActor bool + delegated bool + stale bool + locked bool + auditError error + writeError error + lastID int64 +} + +func zoneAPITestDBFor(t *testing.T, rows []recordRow) *zoneAPITestDB { + t.Helper() + return &zoneAPITestDB{ + t: t, rows: slices.Clone(rows), actor: userRow{ID: 17, Username: "alice", Role: "admin"}, + hasActor: true, delegated: true, + } +} + +func zoneAPITestValues(row recordRow) []driver.Value { + ttl, _ := row.TTL.Value() + content, _ := row.Content.Value() + return []driver.Value{row.ID, row.Zone, row.Name, ttl, content, row.RecordType} +} + +func (f *zoneAPITestDB) server() (*WebServer, *fdbState) { + for _, row := range f.rows { + f.lastID = max(f.lastID, row.ID) + } + db, state := newFakeDB(f.t, f.query) + return &WebServer{db: db, tables: fdbTables(f.t), log: discardLogger()}, state +} + +func (f *zoneAPITestDB) query(query string, args []any) fdbResponse { + has := func(value string) bool { return strings.Contains(query, value) } + switch { + case has("GET_LOCK"): + if f.locked { + return fdbResponse{rows: fdbRow(int64(0))} + } + return fdbResponse{rows: fdbRow(int64(1))} + case has("RELEASE_LOCK"): + return fdbResponse{rows: fdbRow(int64(1))} + case has("SELECT u.") && has("FOR SHARE"): + if !f.hasActor { + return fdbResponse{} + } + deleted, _ := f.actor.DeletedAt.Value() + return fdbResponse{rows: fdbRow(f.actor.ID, f.actor.Username, f.actor.Role, "hash", modelNow, modelNow, nil, deleted)} + case has("SELECT 1 FROM") && has("zone_delegations") && has("FOR SHARE"): + if f.delegated { + return fdbResponse{rows: fdbRow(int64(1))} + } + return fdbResponse{} + case has("COUNT(*)") && has("GROUP BY"): + if len(f.rows) == 0 || has("WHERE r.") && !f.delegated { + return fdbResponse{} + } + var rows [][]driver.Value + soa := zoneAPIFindSOA(f.rows) + content, _ := soa.Content.Value() + rows = append(rows, []driver.Value{f.rows[0].Zone, int64(len(f.rows)), content}) + if !has("WHERE r.") && f.foreign.ID != 0 { + rows = append(rows, []driver.Value{f.foreign.Zone, int64(1), nil}) + } + return fdbResponse{rows: rows} + case has("SELECT d.") && has("FOR UPDATE OF d"): + if f.stale { + return fdbResponse{rows: fdbRow(args[0], int64(18), "bob", modelNow, f.actor.ID)} + } + return fdbResponse{} + case has("SELECT `id`") && has("WHERE `zone`"): + var rows [][]driver.Value + for _, row := range append(slices.Clone(f.rows), f.foreign) { + if row.Zone == args[0] { + rows = append(rows, zoneAPITestValues(row)) + } + } + return fdbResponse{rows: rows} + case has("SELECT `id`") && has("WHERE `id`"): + if f.foreign.ID == args[0] { + return fdbResponse{rows: fdbRow(zoneAPITestValues(f.foreign)...)} + } + return fdbResponse{} + case has("INSERT INTO `coredns_webui_audit`"): + return fdbResponse{lastInsertID: 1, err: f.auditError} + case has("INSERT INTO `coredns_records`"): + f.lastID++ + f.rows = append(f.rows, recordRow{ + ID: f.lastID, Zone: args[0].(string), Name: args[1].(string), TTL: sql.NullInt64{Int64: args[2].(int64), Valid: true}, + Content: sql.NullString{String: args[3].(string), Valid: true}, RecordType: args[4].(string), + }) + return fdbResponse{lastInsertID: f.lastID, err: f.writeError} + case has("UPDATE `coredns_records`"): + if i := slices.IndexFunc(f.rows, func(row recordRow) bool { return row.ID == args[5] }); i >= 0 { + f.rows[i] = recordRow{ + ID: args[5].(int64), Zone: args[0].(string), Name: args[1].(string), RecordType: args[4].(string), + TTL: sql.NullInt64{Int64: args[2].(int64), Valid: true}, Content: sql.NullString{String: args[3].(string), Valid: true}, + } + } + return fdbResponse{rowsAffected: 1, err: f.writeError} + case has("DELETE FROM `coredns_records`"): + f.rows = slices.DeleteFunc(f.rows, func(row recordRow) bool { + return row.ID == args[0] || row.Zone == args[0] + }) + return fdbResponse{rowsAffected: 1, err: f.writeError} + case has("DELETE FROM"): + return fdbResponse{rowsAffected: 1, err: f.writeError} + default: + f.t.Errorf("unexpected SQL: %s", query) + return fdbResponse{err: errors.New("unexpected SQL")} + } +} + +func zoneAPITestingSQL(state *fdbState, contains string) []fdbCall { + var result []fdbCall + for _, call := range state.Calls() { + if strings.Contains(call.query, contains) { + result = append(result, call) + } + } + return result +} + +func TestZoneAPIReadHandlers(t *testing.T) { + rows := zoneAPITestRows(t) + broken := recordRow{ID: 5, Zone: zoneAPITestName, Name: "bad", RecordType: "A", Content: sql.NullString{String: "{", Valid: true}} + f := zoneAPITestDBFor(t, append(rows, broken)) + f.foreign = recordRow{ID: 90, Zone: "private.example.", RecordType: "unknown"} + server, state := f.server() + for _, tc := range []struct { + operation string + fragment string + }{ + {"zone_list", `"records":5`}, + {"zone_read", `"mbox":"hostmaster.example.org."`}, + {"record_list", `"data":null,"raw":"{"`}, + {"zone_check", `"zone":"example.org.","id":5,"name":"bad","type":"A"`}, + {"check_all", `"zone":"private.example.","id":null,"name":null,"type":null`}, + {"zone_export", ""}, + } { + t.Run(tc.operation, func(t *testing.T) { + c := zoneAPITestRequest(server, f.actor, tc.operation, zoneAPITestName, "", "", "") + resp := zoneAPITestStatus(t, t.Context(), c, http.StatusOK) + if !strings.Contains(zoneAPITestJSON(t, resp.Body), tc.fragment) { + t.Fatalf("body = %s", zoneAPITestJSON(t, resp.Body)) + } + if tc.operation == "zone_read" && resp.Header.Get("ETag") != recordETag(rows[0]) { + t.Fatalf("ETag = %q", resp.Header.Get("ETag")) + } + if tc.operation == "zone_export" && (resp.ContentType != "text/plain" || + resp.Header.Get("Content-Disposition") != `attachment; filename="example.org.zone"` || + !strings.HasPrefix(string(resp.Raw), "$ORIGIN example.org.\n") || + !strings.Contains(string(resp.Raw), "; skipped id=5: ttl_null")) { + t.Fatalf("response = %+v, file %s", resp, resp.Raw) + } + if c.auditDone || c.Entry.Before != nil || c.Entry.After != nil { + t.Fatalf("read wrote change audit: %+v", c.Entry) + } + }) + } + if len(zoneAPITestingSQL(state, "INSERT INTO")) != 0 { + t.Fatal("read wrote to the database") + } + user := userRow{ID: 17, Role: "user", Username: "alice"} + for _, operation := range []string{"zone_list", "check_all"} { + c := zoneAPITestRequest(server, user, operation, "", "", "", "") + resp := zoneAPITestStatus(t, t.Context(), c, http.StatusOK) + if encoded := zoneAPITestJSON(t, resp.Body); strings.Contains(encoded, "private.example.") || !strings.Contains(encoded, zoneAPITestName) { + t.Fatalf("visibility: %s", encoded) + } + } + f.delegated = false + for _, operation := range []string{"zone_list", "check_all"} { + c := zoneAPITestRequest(server, user, operation, "", "", "", "") + resp := zoneAPITestStatus(t, t.Context(), c, http.StatusOK) + if encoded := zoneAPITestJSON(t, resp.Body); !strings.HasSuffix(encoded, "[]}") { + t.Fatalf("empty visibility: %s", encoded) + } + } + for _, zone := range []string{"missing.example.", zoneAPITestName} { + f.rows = nil + c := zoneAPITestRequest(server, f.actor, "zone_read", zone, "", "", "") + _, err := zoneAPITestCall(t.Context(), c) + if e, ok := err.(*apiError); !ok || e.Status != 404 || e.Message != "zone not found" { + t.Fatalf("absent zone: %v", err) + } + } +} + +func TestZoneAPIWriteHandlers(t *testing.T) { + rows := zoneAPITestRows(t) + bulk := zoneAPITestJSON(t, map[string]any{"records": []map[string]any{ + {"id": 3, "etag": recordETag(rows[2])}, {"id": 4, "etag": recordETag(rows[3])}, + }}) + for _, tc := range []struct { + operation string + id string + etag string + body string + status int + before, after []int64 + recordID int64 + serial bool + }{ + {"zone_create", "", "", zoneAPITestCreate, 201, nil, []int64{1, 2, 3}, 0, false}, + {"zone_delete", "", "", `{"confirm":"EXAMPLE.ORG"}`, 204, []int64{1, 2, 3, 4}, nil, 0, false}, + {"record_create", "", "", zoneAPITestRecord, 201, []int64{1}, []int64{1, 5}, 5, true}, + {"record_update", "3", recordETag(rows[2]), zoneAPITestRecord, 200, []int64{1, 3}, []int64{1, 3}, 3, true}, + {"record_delete", "3", recordETag(rows[2]), "", 204, []int64{1, 3}, []int64{1}, 3, true}, + {"record_bulk_delete", "", "", bulk, 200, []int64{1, 3, 4}, []int64{1}, 0, true}, + {"soa_update", "", recordETag(rows[0]), strings.Replace(zoneAPITestSOA, "3600", "1500", 1), 200, []int64{1}, []int64{1}, 1, true}, + } { + t.Run(tc.operation, func(t *testing.T) { + f := zoneAPITestDBFor(t, slices.Clone(rows)) + f.stale = tc.operation == "zone_create" || tc.operation == "zone_delete" + zone := zoneAPITestName + if tc.operation == "zone_create" { + f.rows, zone = nil, "" + } + server, state := f.server() + c := zoneAPITestRequest(server, f.actor, tc.operation, zone, tc.id, tc.etag, tc.body) + resp := zoneAPITestStatus(t, t.Context(), c, tc.status) + audits := zoneAPITestingSQL(state, "INSERT INTO `coredns_webui_audit`") + if len(audits) != 1 || state.commits != 1 || state.rollbacks != 0 || !c.auditDone || + c.Entry.RecordID.Int64 != tc.recordID || c.Entry.RecordID.Valid != (tc.recordID != 0) || + audits[0].args[5] != int64(tc.status) || audits[0].args[7] != zoneAPITestName { + t.Fatalf("change audit = %+v, record ID %+v, commits %d, rollbacks %d", audits, c.Entry.RecordID, state.commits, state.rollbacks) + } + zoneAPITestAuditIDs(t, c.Entry.Before, tc.before) + zoneAPITestAuditIDs(t, c.Entry.After, tc.after) + if f.stale && (!strings.Contains(string(c.Entry.Before)+string(c.Entry.After), `{"zone":"example.org.","username":"bob"}`) || + len(zoneAPITestingSQL(state, "DELETE FROM `coredns_webui_zone_delegations`")) != 1) { + t.Fatal("delegation cleanup is missing") + } + if tc.serial { + var serials []uint32 + for _, update := range zoneAPITestingSQL(state, "UPDATE `coredns_records`") { + if update.args[4] == "SOA" { + row := recordRow{Content: sql.NullString{String: update.args[3].(string), Valid: true}} + serial, _ := storedSOASerial(row) + serials = append(serials, serial) + } + } + if !slices.Equal(serials, []uint32{newSOASerial(modelNow) + 1}) { + t.Fatalf("serials = %v", serials) + } + } + if tc.status != 204 && tc.operation != "record_bulk_delete" && resp.Header.Get("ETag") == "" { + t.Fatal("missing response ETag") + } + calls := state.Queries() + if !strings.Contains(calls[0], "GET_LOCK") || !strings.HasSuffix(calls[1], "FOR SHARE") || + !strings.HasSuffix(calls[2], "FOR UPDATE") || !strings.Contains(calls[len(calls)-2], "INSERT INTO `coredns_webui_audit`") || + !strings.Contains(calls[len(calls)-1], "RELEASE_LOCK") { + t.Fatalf("write query order: %v", calls) + } + }) + } +} + +func zoneAPITestAuditIDs(t *testing.T, body []byte, want []int64) { + t.Helper() + if want == nil { + if body != nil { + t.Fatalf("audit = %s, want SQL NULL", body) + } + return + } + var objects []map[string]json.RawMessage + if len(body) > 0 && body[0] == '{' { + body = append(append([]byte{'['}, body...), ']') + } + if err := json.Unmarshal(body, &objects); err != nil { + t.Fatalf("audit %s: %v", body, err) + } + var ids []int64 + for _, object := range objects { + id, record := object["id"] + if !record { + continue + } + var idValue int64 + if err := json.Unmarshal(id, &idValue); err != nil { + t.Fatal(err) + } + if _, ok := object["record_type"]; !ok || len(object) != 6 || object["ttl"] == nil || object["content"] == nil || object["zone"] == nil || object["name"] == nil { + t.Fatalf("unexpected record audit fields: %v", object) + } + ids = append(ids, idValue) + } + if !slices.Equal(ids, want) { + t.Fatalf("audit ids = %v, want %v; values %s", ids, want, body) + } +} + +func TestZoneAPIWriteRefusals(t *testing.T) { + rows := zoneAPITestRows(t) + padded := `{"content":"` + strings.Repeat("x", zoneFileMaxBytes) + `","mode":"merge"}` + for _, tc := range []struct { + operation string + id string + etag string + body string + status int + field string + setup func(*zoneAPITestDB, *apiContext) + }{ + {operation: "zone_create", status: 409, body: zoneAPITestCreate}, + {operation: "zone_create", status: 403, body: zoneAPITestCreate, setup: func(_ *zoneAPITestDB, c *apiContext) { c.Principal.User.Role = "user" }}, + {operation: "zone_delete", status: 403, body: `{"confirm":"example.org"}`, setup: func(_ *zoneAPITestDB, c *apiContext) { c.Principal.User.Role = "user" }}, + {operation: "zone_create", status: 422, field: "name", body: `{"name":".."}`}, + {operation: "zone_create", status: 422, field: "extra_ns", body: strings.Replace(zoneAPITestCreate, "backup.example.net", "ns.example.net.", 1), setup: func(f *zoneAPITestDB, _ *apiContext) { f.rows = nil }}, + {operation: "zone_create", status: 422, field: "mbox", body: strings.Replace(zoneAPITestCreate, "hostmaster@example.org", "bad mailbox", 1), setup: func(f *zoneAPITestDB, _ *apiContext) { f.rows = nil }}, + {operation: "zone_create", status: 422, field: "ttl", body: strings.Replace(zoneAPITestCreate, `"ttl":3600`, `"ttl":"3600"`, 1), setup: func(f *zoneAPITestDB, _ *apiContext) { f.rows = nil }}, + {operation: "zone_delete", status: 422, field: "confirm", body: `{"confirm":"different.example"}`}, + {operation: "zone_delete", status: 404, body: `{"confirm":"example.org"}`, setup: func(f *zoneAPITestDB, _ *apiContext) { f.rows = nil }}, + {operation: "record_create", status: 422, field: "data.ip", body: `{"name":"new","type":"A","ttl":60,"data":{"ip":"::1"}}`}, + {operation: "record_create", status: 422, field: "name", body: `{"name":"elsewhere.example.","type":"A","ttl":60,"data":{"ip":"192.0.2.1"}}`}, + {operation: "record_create", status: 422, field: "type", body: `{"name":"new","type":"NONE","ttl":60,"data":{}}`}, + {operation: "record_create", status: 422, field: "name", body: `{"name":"first","type":"A","ttl":61,"data":{"ip":"192.0.2.1"}}`}, + {operation: "record_create", status: 422, field: "data.preference", body: `{"name":"new","type":"MX","ttl":60,"data":{"host":"mx.example","preference":"10"}}`}, + {operation: "record_create", status: 422, field: "ttl", body: `{"name":"new","type":"A","ttl":"60","data":{"ip":"192.0.2.1"}}`}, + {operation: "record_create", status: 400, body: `{"unknown":true}`}, + {operation: "record_create", status: 400, body: zoneAPITestRecord + "{}"}, + {operation: "record_create", status: 415, body: zoneAPITestRecord, setup: func(_ *zoneAPITestDB, c *apiContext) { c.Request.Header.Del("Content-Type") }}, + {operation: "record_create", status: 413, body: `{"data":"` + strings.Repeat("x", 64<<10) + `"}`}, + {operation: "record_create", status: 503, body: zoneAPITestRecord, setup: func(f *zoneAPITestDB, _ *apiContext) { f.locked = true }}, + {operation: "record_create", status: 404, body: zoneAPITestRecord, setup: func(f *zoneAPITestDB, c *apiContext) { + f.actor.Role, c.Principal.User.Role, f.delegated = "user", "user", false + }}, + {operation: "record_create", status: 404, body: zoneAPITestRecord, setup: func(f *zoneAPITestDB, _ *apiContext) { f.hasActor = false }}, + {operation: "record_create", status: 404, body: zoneAPITestRecord, setup: func(f *zoneAPITestDB, _ *apiContext) { f.actor.DeletedAt = sql.NullTime{Time: modelNow, Valid: true} }}, + {operation: "record_create", status: 404, body: zoneAPITestRecord, setup: func(f *zoneAPITestDB, _ *apiContext) { f.actor.Role = "user" }}, + {operation: "record_update", id: "3", status: 428, body: zoneAPITestRecord}, + {operation: "record_update", id: "3", status: 412, etag: `"old"`, body: zoneAPITestRecord}, + {operation: "record_update", id: "99", status: 412, etag: `"old"`, body: zoneAPITestRecord}, + {operation: "record_update", id: "wrong", status: 400, etag: `"old"`, body: zoneAPITestRecord}, + {operation: "record_update", id: "2147483648", status: 400, etag: `"old"`, body: zoneAPITestRecord}, + {operation: "record_update", id: "90", status: 404, etag: `"old"`, body: zoneAPITestRecord}, + {operation: "record_delete", id: "3", status: 428}, + {operation: "record_delete", id: "3", status: 412, etag: "*"}, + {operation: "record_delete", id: "90", status: 404, etag: `"old"`}, + {operation: "record_delete", id: "1", status: 422, field: "type", etag: recordETag(rows[0])}, + {operation: "record_delete", id: "2", status: 422, field: "type", etag: recordETag(rows[1])}, + {operation: "record_bulk_delete", status: 412, body: `{"records":[{"id":3,"etag":` + zoneAPITestJSON(t, recordETag(rows[2])) + `},{"id":4,"etag":"old"}]}`}, + {operation: "record_bulk_delete", status: 422, field: "records", body: `{"records":[]}`}, + {operation: "record_bulk_delete", status: 422, field: "records", body: `{"records":[{"id":"3","etag":"old"}]}`}, + {operation: "record_bulk_delete", status: 404, body: `{"records":[{"id":90,"etag":"old"}]}`}, + {operation: "soa_update", status: 428, body: zoneAPITestSOA}, + {operation: "soa_update", status: 412, etag: `"old"`, body: zoneAPITestSOA}, + {operation: "soa_update", status: 412, etag: recordETag(rows[0]), body: zoneAPITestSOA, setup: func(f *zoneAPITestDB, _ *apiContext) { f.rows = f.rows[1:] }}, + {operation: "soa_update", status: 422, field: "refresh", etag: recordETag(rows[0]), body: strings.Replace(zoneAPITestSOA, `"refresh":3600`, `"refresh":"3600"`, 1)}, + {operation: "soa_update", status: 422, field: "mbox", etag: recordETag(rows[0]), body: strings.Replace(zoneAPITestSOA, "hostmaster@example.org", "@example.org", 1)}, + {operation: "zone_import_preview", status: 413, body: padded}, + {operation: "zone_import", status: 413, body: padded}, + {operation: "zone_import", status: 409, body: `{"mode":"merge","content":"","fingerprint":"stale"}`}, + {operation: "zone_import_preview", status: 422, field: "mode", body: `{"mode":"invalid","content":""}`}, + } { + t.Run(tc.operation+"/"+strconv.Itoa(tc.status)+"/"+tc.field, func(t *testing.T) { + f := zoneAPITestDBFor(t, slices.Clone(rows)) + f.foreign = recordRow{ID: 90, Zone: "private.example.", RecordType: "TXT"} + server, state := f.server() + c := zoneAPITestRequest(server, f.actor, tc.operation, zoneAPITestName, tc.id, tc.etag, tc.body) + if tc.setup != nil { + tc.setup(f, c) + } + _, err := zoneAPITestCall(t.Context(), c) + var apiErr *apiError + if !errors.As(err, &apiErr) || apiErr.Status != tc.status || tc.field != "" && apiErr.Fields[tc.field] == "" { + t.Fatalf("error = %#v, want status %d, field %q", err, tc.status, tc.field) + } + if tc.status == 503 && apiErr.Message != "zone busy" { + t.Fatalf("busy error = %q", apiErr.Message) + } + if c.auditDone || c.Entry.Before != nil || c.Entry.After != nil || + len(zoneAPITestingSQL(state, "INSERT INTO"))+len(zoneAPITestingSQL(state, "UPDATE `"))+len(zoneAPITestingSQL(state, "DELETE FROM")) != 0 { + t.Fatalf("refusal wrote data: %+v, queries %v", c.Entry, state.Queries()) + } + }) + } +} + +func TestZoneAPIWarningsAndSerialModes(t *testing.T) { + rows := zoneAPITestRows(t) + var err error + rows[0], err = withSOASerial(rows[0], 0, false) + if err != nil { + t.Fatal(err) + } + f := zoneAPITestDBFor(t, rows) + f.actor.Role = "user" + server, state := f.server() + body := `{"name":"new","type":"MX","ttl":60,"data":{"host":"missing.example.org.","preference":10}}` + c := zoneAPITestRequest(server, f.actor, "record_create", zoneAPITestName, "", "", body) + resp := zoneAPITestStatus(t, t.Context(), c, 201) + if !strings.Contains(zoneAPITestJSON(t, resp.Body), "target_no_address") || + len(zoneAPITestingSQL(state, "UPDATE `coredns_records`")) != 0 || + len(zoneAPITestingSQL(state, "zone_delegations` WHERE `zone` = ? AND `user_id` = ? FOR SHARE")) != 1 { + t.Fatalf("response = %+v, SQL = %v", resp, state.Queries()) + } + c = zoneAPITestRequest(server, f.actor, "soa_update", zoneAPITestName, "", recordETag(rows[0]), zoneAPITestSOA) + resp = zoneAPITestStatus(t, t.Context(), c, 200) + if c.auditDone || c.Entry.Before != nil || c.Entry.After != nil || + resp.Header.Get("ETag") != recordETag(rows[0]) || !strings.Contains(zoneAPITestJSON(t, resp.Body), `"serial":null`) { + t.Fatalf("unexpected SOA no-op: %+v, %s", c.Entry, zoneAPITestJSON(t, resp.Body)) + } + c = zoneAPITestRequest(server, f.actor, "soa_update", zoneAPITestName, "", recordETag(rows[0]), `{"managed_serial":true,`+zoneAPITestSOA[1:]) + resp = zoneAPITestStatus(t, t.Context(), c, 200) + if !c.auditDone || !strings.Contains(zoneAPITestJSON(t, resp.Body), `"serial":`+strconv.FormatUint(uint64(newSOASerial(modelNow)), 10)) || + len(zoneAPITestingSQL(state, "UPDATE `coredns_records`")) != 1 { + t.Fatalf("SOA managed update: %+v, %s, SQL = %v", c.Entry, zoneAPITestJSON(t, resp.Body), state.Queries()) + } +} + +func TestZoneAPISOAFieldNames(t *testing.T) { + for _, field := range []string{"ns", "mbox", "ttl", "refresh", "retry", "expire", "minttl"} { + for _, operation := range []string{"zone_create", "soa_update"} { + t.Run(operation+"/"+field, func(t *testing.T) { + rows := zoneAPITestRows(t) + f := zoneAPITestDBFor(t, rows) + var body map[string]any + input, zone, etag := zoneAPITestSOA, zoneAPITestName, recordETag(rows[0]) + if operation == "zone_create" { + f.rows, input, zone, etag = nil, zoneAPITestCreate, "", "" + } + if err := json.Unmarshal([]byte(input), &body); err != nil { + t.Fatal(err) + } + body[field] = "invalid field" + server, state := f.server() + c := zoneAPITestRequest(server, f.actor, operation, zone, "", etag, zoneAPITestJSON(t, body)) + _, err := zoneAPITestCall(t.Context(), c) + var invalid *apiError + if !errors.As(err, &invalid) || invalid.Status != 422 || len(invalid.Fields) != 1 || invalid.Fields[field] == "" { + t.Fatalf("field %q: error %+v", field, err) + } + if c.auditDone || len(zoneAPITestingSQL(state, "INSERT INTO")) != 0 || len(zoneAPITestingSQL(state, "UPDATE `")) != 0 { + t.Fatalf("invalid field wrote data: %v", state.Queries()) + } + }) + } + } +} + +func TestZoneAPIRollback(t *testing.T) { + for _, failAt := range []string{"write", "audit", "commit"} { + t.Run(failAt, func(t *testing.T) { + f := zoneAPITestDBFor(t, zoneAPITestRows(t)) + failure := errors.New(failAt + " failed") + server, state := f.server() + switch failAt { + case "write": + f.writeError = failure + case "audit": + f.auditError = failure + case "commit": + state.commitErr = failure + } + c := zoneAPITestRequest(server, f.actor, "record_create", zoneAPITestName, "", "", zoneAPITestRecord) + resp, err := zoneAPITestCall(t.Context(), c) + if !errors.Is(err, failure) || resp.Status != 0 || c.auditDone || c.Entry.Before != nil || c.Entry.After != nil || + state.commits != 0 || (failAt != "commit" && state.rollbacks != 1) || + !strings.Contains(state.Queries()[len(state.Queries())-1], "RELEASE_LOCK") { + t.Fatalf("response %+v, err %v, audit %+v, SQL %v", resp, err, c.Entry, state.Queries()) + } + }) + } +} + +func TestZoneAPIImport(t *testing.T) { + rows := zoneAPITestRows(t) + f := zoneAPITestDBFor(t, rows) + server, state := f.server() + content := "$ORIGIN example.org.\nfirst 180 A 192.0.2.1\nlast TXT \"one\" \"two\"\nother PTR ptr.example.net.\n" + + "@ SOA ns.example.net. hostmaster.example.org. 99 3600 600 604800 600\n" + + "@ 3600 NS ns.example.net.\n" + makeBody := func(content string, apply bool) string { + body := map[string]any{"mode": "replace", "content": content} + if apply { + body["fingerprint"] = zoneFingerprint(f.rows) + } + return zoneAPITestJSON(t, body) + } + c := zoneAPITestRequest(server, f.actor, "zone_import_preview", zoneAPITestName, "", "", makeBody(content, false)) + resp := zoneAPITestStatus(t, t.Context(), c, 200) + for _, fragment := range []string{`"fingerprint":"` + zoneFingerprint(rows), `"old_ttl":60`, + `"name":"last","type":"TXT","ttl":3600,"value":"onetwo"`, `"minttl":600`, `"line":4,"text":`, `"line":3,"message":"TXT strings`} { + if encoded := zoneAPITestJSON(t, resp.Body); !strings.Contains(encoded, fragment) { + t.Fatalf("missing %q in %s", fragment, encoded) + } + } + c = zoneAPITestRequest(server, f.actor, "zone_import", zoneAPITestName, "", "", makeBody(content, true)) + resp = zoneAPITestStatus(t, t.Context(), c, 200) + if zoneAPITestJSON(t, resp.Body) != `{"added":1,"deleted":1,"updated":2}` { + t.Fatalf("apply response = %s", zoneAPITestJSON(t, resp.Body)) + } + zoneAPITestAuditIDs(t, c.Entry.Before, []int64{1, 3, 4}) + zoneAPITestAuditIDs(t, c.Entry.After, []int64{1, 3, 5}) + updates := zoneAPITestingSQL(state, "UPDATE `coredns_records`") + if len(updates) != 2 || updates[0].args[4] != "SOA" || !strings.Contains(updates[0].args[3].(string), strconv.FormatUint(uint64(newSOASerial(modelNow)+1), 10)) || + len(zoneAPITestingSQL(state, "INSERT INTO `coredns_webui_audit`")) != 1 { + t.Fatalf("incorrect import SQL: %v", state.Calls()) + } + for _, tc := range []struct { + content string + fragment string + }{ + {"\n; comment\nother.example. A 192.0.2.1\n", `"line":3,"message":"record has an owner outside the zone"`}, + {"\n; comment\nwww A not-an-address\n", `"line":3,"message":`}, + {"\n; comment\nwww AAAA ::ffff:192.0.2.1\n", `"line":3,"message":"ip:`}, + {"$INCLUDE ignored\n", `"line":1,"message":`}, + {"", "last apex NS"}, + } { + for _, operation := range []string{"zone_import_preview", "zone_import"} { + c := zoneAPITestRequest(server, f.actor, operation, zoneAPITestName, "", "", makeBody(tc.content, operation == "zone_import")) + _, err := zoneAPITestCall(t.Context(), c) + var apiErr *apiError + if !errors.As(err, &apiErr) || apiErr.Status != 422 || apiErr.Message != "the file has errors" || + !strings.Contains(zoneAPITestJSON(t, apiErr.Extra["errors"]), tc.fragment) { + t.Fatalf("%q yielded %#v, expected %q", tc.content, err, tc.fragment) + } + } + } +} + +func TestZoneAPIAbsence(t *testing.T) { + for _, operation := range []string{ + "zone_read", "zone_delete", "record_list", "record_create", "record_update", "record_delete", + "record_bulk_delete", "soa_update", "zone_check", "zone_export", "zone_import_preview", "zone_import", + } { + t.Run(operation, func(t *testing.T) { + f := zoneAPITestDBFor(t, nil) + server, _ := f.server() + c := zoneAPITestRequest(server, f.actor, operation, zoneAPITestName, "1", "", "") + _, err := zoneAPITestCall(t.Context(), c) + if e, ok := err.(*apiError); !ok || e.Status != 404 || e.Message != "zone not found" { + t.Fatalf("absent zone: %v", err) + } + }) + } +} + +func TestZoneAPIUnreadableSOA(t *testing.T) { + rows := zoneAPITestRows(t) + rows[0].Content = sql.NullString{String: "{", Valid: true} + f := zoneAPITestDBFor(t, rows) + server, _ := f.server() + c := zoneAPITestRequest(server, f.actor, "zone_read", zoneAPITestName, "", "", "") + resp := zoneAPITestStatus(t, t.Context(), c, 200) + if resp.Header.Get("ETag") != "" || !strings.Contains(zoneAPITestJSON(t, resp.Body), `"serial":null,"soa":null`) { + t.Fatalf("broken SOA summary = %+v", resp) + } + c = zoneAPITestRequest(server, f.actor, "soa_update", zoneAPITestName, "", recordETag(rows[0]), zoneAPITestSOA) + resp = zoneAPITestStatus(t, t.Context(), c, 200) + if resp.Header.Get("ETag") == "" || resp.Header.Get("ETag") == recordETag(rows[0]) || !c.auditDone { + t.Fatalf("SOA was not repaired: %+v", resp) + } +} + +func TestZoneAPIReadErrors(t *testing.T) { + failure := errors.New("database read failed") + db, _ := newFakeDB(t, func(string, []any) fdbResponse { return fdbResponse{err: failure} }) + server := &WebServer{db: db, tables: fdbTables(t), log: discardLogger()} + for _, operation := range []string{"zone_list", "zone_read", "record_list", "zone_check", "check_all", "zone_export", "zone_import_preview", "record_create"} { + c := zoneAPITestRequest(server, userRow{ID: 17, Role: "admin"}, operation, zoneAPITestName, "", "", "") + _, err := zoneAPITestCall(t.Context(), c) + if !errors.Is(err, failure) { + t.Errorf("%s = %v", operation, err) + } + } +} diff --git a/integration_zone_api_test.go b/integration_zone_api_test.go new file mode 100644 index 0000000..ab1b468 --- /dev/null +++ b/integration_zone_api_test.go @@ -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)) + } + }) + } + } +} diff --git a/scripts/integration.sh b/scripts/integration.sh index 0e9f781..33fdfd2 100755 --- a/scripts/integration.sh +++ b/scripts/integration.sh @@ -9,6 +9,7 @@ IT_NAME=${IT_NAME:-cdwu-it-${IT_ID}} MYSQL_IMAGE=${MYSQL_IMAGE:-mysql:8.4} network="${IT_NAME}" mysql="${IT_NAME}-mysql" +mysql_data="${IT_NAME}-data" tests="${IT_NAME}-tests" image="${IT_NAME}:integration" root_password=$(od -An -tx1 -N16 /dev/urandom | tr -d ' \n') @@ -17,7 +18,8 @@ cleanup() { if [ "$status" -ne 0 ]; then docker logs --tail 80 "$mysql" >&2 2>&1 || true fi - docker rm --force "$tests" "$mysql" >/dev/null 2>&1 || true + docker rm --force --volumes "$tests" "$mysql" >/dev/null 2>&1 || true + docker volume rm "$mysql_data" >/dev/null 2>&1 || true docker network rm "$network" >/dev/null 2>&1 || true docker image rm --force "$image" >/dev/null 2>&1 || true exit "$status" @@ -27,6 +29,7 @@ trap 'exit 130' INT TERM docker build --target integration --file dockerfile --tag "$image" . docker network create --internal "$network" >/dev/null docker run --detach --name "$mysql" --network "$network" --network-alias mysql \ + --volume "$mysql_data:/var/lib/mysql" \ --env MYSQL_ROOT_PASSWORD="$root_password" "$MYSQL_IMAGE" >/dev/null attempt=0 until docker exec --env MYSQL_PWD="$root_password" "$mysql" mysqladmin ping --host=127.0.0.1 --user=root --silent >/dev/null 2>&1; do diff --git a/stub_contracts.go b/stub_contracts.go index 997fbd1..7ebf6f1 100644 --- a/stub_contracts.go +++ b/stub_contracts.go @@ -4,8 +4,14 @@ package main import ( + "bytes" + "context" "database/sql" + "encoding/json" "errors" + "io" + "mime" + "net/http" "time" ) @@ -28,3 +34,80 @@ type auditEntry struct { func stubHashPassword(password string) (string, error) { return "", errors.New("password hashing is not available") } + +type principal struct { + User userRow + TokenHash []byte +} + +func (p principal) isAdmin() bool { return p.User.Role == "admin" } + +type apiContext struct { + Request *http.Request + Principal principal + Zone string + Vars map[string]string + Now time.Time + Entry *auditEntry + Server *WebServer + auditDone bool +} + +type apiResponse struct { + Status int + Body any + Raw []byte + ContentType string + Header http.Header +} + +type apiError struct { + Status int + Message string + Fields map[string]string + Extra map[string]any +} + +func (e *apiError) Error() string { return e.Message } + +type apiHandler func(ctx context.Context, c *apiContext) (apiResponse, error) + +func (c *apiContext) decodeJSON(dst any) error { + invalid := &apiError{Status: http.StatusBadRequest, Message: "invalid JSON"} + if c.Request.Body == nil || c.Request.Body == http.NoBody { + return invalid + } + limit := int64(64 << 10) + if c.Entry.Operation == "zone_import_preview" || c.Entry.Operation == "zone_import" { + limit = zoneFileMaxBytes + } + body, err := io.ReadAll(io.LimitReader(c.Request.Body, limit+1)) + if err != nil { + return invalid + } + if int64(len(body)) > limit { + return &apiError{Status: http.StatusRequestEntityTooLarge, Message: "request body too large"} + } + if len(body) == 0 { + return invalid + } + contentType, _, err := mime.ParseMediaType(c.Request.Header.Get("Content-Type")) + if err != nil || contentType != "application/json" { + return &apiError{Status: http.StatusUnsupportedMediaType, Message: "expected application/json"} + } + decoder := json.NewDecoder(bytes.NewReader(body)) + decoder.DisallowUnknownFields() + if bytes.Equal(bytes.TrimSpace(body), []byte("null")) || decoder.Decode(dst) != nil || decoder.Decode(new(any)) != io.EOF { + return invalid + } + return nil +} + +func (c *apiContext) writeChangeAudit(ctx context.Context, tx *sql.Tx, status int) error { + c.Entry.Status = sql.NullInt64{Int64: int64(status), Valid: true} + if _, err := newAuditStore(tx, c.Server.tables).InsertAudit(ctx, *c.Entry); err != nil { + return err + } + c.auditDone = true + return nil +} diff --git a/zonefile.go b/zonefile.go index 9356d8e..07b334d 100644 --- a/zonefile.go +++ b/zonefile.go @@ -4,6 +4,7 @@ package main import ( + "bufio" "bytes" "crypto/sha256" "errors" @@ -59,18 +60,22 @@ func exportZoneFile(zone string, rows []recordRow, now time.Time) (string, error } type zoneFileSkip struct { + Line int + Text string Name string `json:"name"` Type string `json:"type"` Reason string `json:"reason"` } type zoneFileRecords struct { - Rows []recordRow - Skipped []zoneFileSkip - Warnings []zoneProblem + Rows []recordRow + Skipped []zoneFileSkip + Warnings []zoneProblem + WarningLines []int } type zoneFileRecordError struct { + Line int Index int Name string Type string @@ -81,6 +86,32 @@ func (e *zoneFileRecordError) Error() string { return fmt.Sprintf("zone file record %d (%s %s) has invalid fields", e.Index, e.Name, e.Type) } +type zoneFileLocatedError struct { + line int + err error +} + +func (e *zoneFileLocatedError) Error() string { return e.err.Error() } + +func (e *zoneFileLocatedError) Unwrap() error { return e.err } + +type zoneFilePosition struct { + *bufio.Reader + line int + lastLine int +} + +func (p *zoneFilePosition) ReadByte() (byte, error) { + b, err := p.Reader.ReadByte() + if err == nil { + p.lastLine = p.line + if b == '\n' { + p.line++ + } + } + return b, err +} + func parseZoneFile(zone string, source io.Reader, now time.Time) (zoneFileRecords, error) { zone, err := normalizeZone(zone) if err != nil { @@ -93,7 +124,8 @@ func parseZoneFile(zone string, source io.Reader, now time.Time) (zoneFileRecord if len(content) > zoneFileMaxBytes { return zoneFileRecords{}, errZoneFileTooLarge } - parser := dns.NewZoneParser(zoneFileTTLSource(content), zone, "") + position := &zoneFilePosition{Reader: bufio.NewReader(zoneFileTTLSource(content))} + parser := dns.NewZoneParser(position, zone, "") parser.SetIncludeAllowed(false) var result zoneFileRecords @@ -102,37 +134,40 @@ func parseZoneFile(zone string, source io.Reader, now time.Time) (zoneFileRecord if !ok { break } + line := max(1, position.lastLine) + located := func(err error) error { return &zoneFileLocatedError{line, err} } if i > zoneFileMaxRecords { - return zoneFileRecords{}, errors.New("zone file exceeds 10000 records") + return zoneFileRecords{}, located(errors.New("zone file exceeds 10000 records")) } header := rr.Header() recordType := dns.Type(header.Rrtype).String() if header.Class != dns.ClassINET { - return zoneFileRecords{}, fmt.Errorf("zone file record %d must have class IN", i) + return zoneFileRecords{}, located(errors.New("record must have class IN")) } if !dns.IsSubDomain(zone, header.Name) { - return zoneFileRecords{}, fmt.Errorf("zone file record %d has an owner outside the zone", i) + return zoneFileRecords{}, located(errors.New("record has an owner outside the zone")) } if _, ok := recordRules[recordType]; !ok { - result.Skipped = append(result.Skipped, zoneFileSkip{header.Name, recordType, "record type is not supported"}) + result.Skipped = append(result.Skipped, zoneFileSkip{Line: line, Text: rr.String(), Name: header.Name, Type: recordType, Reason: "record type is not supported"}) continue } data, err := zoneFileRecordData(rr) if err != nil { - return zoneFileRecords{}, fmt.Errorf("zone file record %d: %w", i, err) + return zoneFileRecords{}, located(err) } encoded, _ := encodeRecord(data) row, fields := validateRecord(zone, header.Name, recordType, int64(header.Ttl), []byte(encoded), now) if len(fields) != 0 { - return zoneFileRecords{}, &zoneFileRecordError{i, header.Name, recordType, fields} + return zoneFileRecords{}, &zoneFileRecordError{line, i, header.Name, recordType, fields} } if txt, ok := rr.(*dns.TXT); ok && len(txt.Txt) > 1 { result.Warnings = append(result.Warnings, recordProblem(row, "warning", "txt_joined", "TXT strings were joined and the plugin will re-split them at 255 bytes")) + result.WarningLines = append(result.WarningLines, line) } result.Rows = append(result.Rows, row) } if err := parser.Err(); err != nil { - return zoneFileRecords{}, err + return zoneFileRecords{}, &zoneFileLocatedError{max(1, position.lastLine), err} } return result, nil }