Files
coredns-web-ui/handlers_api.go
T
bryanpedini 9251c85fd8 test: require review fix assertions
- test: require review fix assertions
- test: cover zone repair and imported dns records
- test: wait for dns and tighten assertions
- fix(api): drop the record id of a rolled back record creation
- test(audit): run every api route through the real handlers in an audit matrix
- test(api): run the authorization matrix through the real zone handlers
- test: repair duplicate apex soa through ui
2026-11-19 15:46:12 +01:00

1925 lines
55 KiB
Go

// 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"
"net/url"
"slices"
"strconv"
"strings"
"time"
)
const (
msgOwnAccount = "use the account page to change your own account"
msgLastActiveAdmin = "the last active admin cannot be demoted or deleted"
msgUsernameTaken = "username already used"
msgDelegationAbsent = "delegation not found"
msgWrongPassword = "current password is wrong"
msgConfirmMismatch = "confirmation does not match"
msgPasswordChanged = "the password was changed by another request"
)
func frameworkAPIHandlers(s *WebServer) map[string]apiHandler {
return map[string]apiHandler{
opAccountRead: handleAccountRead,
opPasswordChange: handlePasswordChange,
opDelegationList: handleDelegationList,
opDelegationGrant: handleDelegationGrant,
opDelegationRevoke: handleDelegationRevoke,
opUserList: handleUserList,
opUserCreate: handleUserCreate,
opUserRead: handleUserRead,
opUserRole: handleUserRole,
opUserPassword: handleUserPassword,
opUserDelete: handleUserDelete,
opAuditRead: handleAuditRead,
}
}
func apiTime(t time.Time) string {
return t.UTC().Format(time.RFC3339Nano)
}
func apiNullTime(t sql.NullTime) *string {
if !t.Valid {
return nil
}
s := apiTime(t.Time)
return &s
}
func noContent() apiResponse {
return apiResponse{Status: http.StatusNoContent}
}
func okJSON(body any) apiResponse {
return apiResponse{Status: http.StatusOK, Body: body}
}
func badParameter(name string) *apiError {
return &apiError{Status: http.StatusBadRequest, Message: "invalid parameter " + name}
}
func ownAccountError() *apiError {
return &apiError{Status: http.StatusForbidden, Message: msgOwnAccount}
}
func lastAdminError() *apiError {
return &apiError{Status: http.StatusConflict, Message: msgLastActiveAdmin}
}
func passwordFieldError(field string, err error) *apiError {
return fieldError(field, err.Error())
}
func (c *apiContext) setTargetUser(u userRow) {
c.Entry.TargetUserID = sql.NullInt64{Int64: u.ID, Valid: true}
}
func (c *apiContext) pathUsername() (string, error) {
username := c.Vars["username"]
if !validUsernameSyntax(username) {
return "", errUserNotFound()
}
return username, nil
}
func (c *apiContext) lookupUser(ctx context.Context) (userRow, error) {
username, err := c.pathUsername()
if err != nil {
return userRow{}, err
}
u, err := c.Server.store.UserByUsername(ctx, username)
if errors.Is(err, errRowNotFound) {
return userRow{}, errUserNotFound()
}
if err != nil {
return userRow{}, err
}
c.setTargetUser(u)
return u, nil
}
func activeTargetForUpdate(ctx context.Context, c *apiContext, tx webTx, username string) (userRow, error) {
u, err := tx.UserByUsernameForUpdate(ctx, username)
if errors.Is(err, errRowNotFound) {
return userRow{}, errUserNotFound()
}
if err != nil {
return userRow{}, err
}
c.setTargetUser(u)
if u.DeletedAt.Valid {
return userRow{}, errUserNotFound()
}
return u, nil
}
func lockActingAdmin(ctx context.Context, c *apiContext, tx webTx) ([]userRow, error) {
admins, err := tx.LockActiveAdmins(ctx)
if err != nil {
return nil, err
}
if !slices.ContainsFunc(admins, func(u userRow) bool { return u.ID == c.Principal.User.ID }) {
c.Server.log.WarnContext(ctx, "actor is no longer an active admin", "operation", c.Entry.Operation, "user", c.Principal.User.Username)
return nil, &apiError{Status: http.StatusForbidden, Message: msgAdminRequired}
}
return admins, nil
}
func (c *apiContext) recordChange(before, after []byte) {
c.Entry.Before, c.Entry.After = before, after
}
func (c *apiContext) commitChange(ctx context.Context, tx webTx, status int) error {
return c.writeChangeAuditWith(ctx, tx, status)
}
type accountResponse struct {
Username string `json:"username"`
Role string `json:"role"`
Zones []string `json:"zones"`
}
func handleAccountRead(ctx context.Context, c *apiContext) (apiResponse, error) {
u := c.Principal.User
resp := accountResponse{Username: u.Username, Role: u.Role, Zones: []string{}}
if !c.Principal.isAdmin() {
zones, err := c.Server.store.UserZones(ctx, u.ID)
if err != nil {
return apiResponse{}, err
}
for _, z := range zones {
if z.ZoneExists {
resp.Zones = append(resp.Zones, z.Zone)
}
}
}
return okJSON(resp), nil
}
type passwordChangeRequest struct {
Current string `json:"current"`
Password string `json:"password"`
}
func handlePasswordChange(ctx context.Context, c *apiContext) (apiResponse, error) {
var req passwordChangeRequest
if err := c.decodeJSON(&req); err != nil {
return apiResponse{}, err
}
s := c.Server
fields := map[string]string{}
if !s.verifyPassword(req.Current, c.Principal.User.PasswordHash) {
fields["current"] = msgWrongPassword
}
if err := checkPasswordRules(req.Password); err != nil {
fields["password"] = err.Error()
}
if len(fields) > 0 {
return apiResponse{}, &apiError{Status: http.StatusUnprocessableEntity, Message: "invalid password change", Fields: fields}
}
hash, err := s.hashPassword(req.Password)
if err != nil {
return apiResponse{}, err
}
c.setTargetUser(c.Principal.User)
err = s.store.InTx(ctx, func(tx webTx) error {
u, err := tx.UserByIDForUpdate(ctx, c.Principal.User.ID)
if errors.Is(err, errRowNotFound) || (err == nil && u.DeletedAt.Valid) {
return &apiError{Status: http.StatusUnauthorized, Message: msgAuthRequired}
}
if err != nil {
return err
}
if u.PasswordHash != c.Principal.User.PasswordHash {
return &apiError{Status: http.StatusConflict, Message: msgPasswordChanged}
}
if err := tx.SetPassword(ctx, u.ID, hash, c.Now); err != nil {
return err
}
if _, err := tx.DeleteUserSessionsExcept(ctx, u.ID, c.Principal.TokenHash); err != nil {
return err
}
snapshot := auditUserJSON(u)
c.recordChange(snapshot, snapshot)
return c.commitChange(ctx, tx, http.StatusNoContent)
})
if err != nil {
return apiResponse{}, err
}
return noContent(), nil
}
type delegatedUser struct {
Username string `json:"username"`
Role string `json:"role"`
}
func requireZone(ctx context.Context, exists func(context.Context, string) (bool, error), zone string) error {
ok, err := exists(ctx, zone)
if err != nil {
return err
}
if !ok {
return errZoneNotFound()
}
return nil
}
func handleDelegationList(ctx context.Context, c *apiContext) (apiResponse, error) {
store := c.Server.store
if err := requireZone(ctx, store.ZoneExists, c.Zone); err != nil {
return apiResponse{}, err
}
users, err := store.ZoneUsers(ctx, c.Zone)
if err != nil {
return apiResponse{}, err
}
out := make([]delegatedUser, 0, len(users))
for _, u := range users {
out = append(out, delegatedUser{Username: u.Username, Role: u.Role})
}
return okJSON(map[string]any{"users": out}), nil
}
func handleDelegationGrant(ctx context.Context, c *apiContext) (apiResponse, error) {
username, err := c.pathUsername()
if err != nil {
return apiResponse{}, err
}
err = c.Server.store.InZoneTx(ctx, c.Zone, c.Server.log, func(tx webTx) error {
if _, err := lockActingAdmin(ctx, c, tx); err != nil {
return err
}
if err := requireZone(ctx, tx.ZoneExists, c.Zone); err != nil {
return err
}
u, err := tx.UserByUsernameForUpdate(ctx, username)
if errors.Is(err, errRowNotFound) {
return errUserNotFound()
}
if err != nil {
return err
}
c.setTargetUser(u)
if aerr := delegationTargetError(u); aerr != nil {
return aerr
}
created, err := tx.GrantDelegation(ctx, c.Zone, u.ID, c.Principal.User.ID, c.Now)
if err != nil || !created {
return err
}
c.recordChange(nil, auditDelegationJSON(c.Zone, u.Username))
return c.commitChange(ctx, tx, http.StatusNoContent)
})
if err != nil {
return apiResponse{}, err
}
return noContent(), nil
}
func handleDelegationRevoke(ctx context.Context, c *apiContext) (apiResponse, error) {
username, err := c.pathUsername()
if err != nil {
return apiResponse{}, err
}
err = c.Server.store.InZoneTx(ctx, c.Zone, c.Server.log, func(tx webTx) error {
if _, err := lockActingAdmin(ctx, c, tx); err != nil {
return err
}
u, err := activeTargetForUpdate(ctx, c, tx, username)
if err != nil {
return err
}
revoked, err := tx.RevokeDelegation(ctx, c.Zone, u.ID)
if err != nil {
return err
}
if !revoked {
return &apiError{Status: http.StatusNotFound, Message: msgDelegationAbsent}
}
c.recordChange(auditDelegationJSON(c.Zone, u.Username), nil)
return c.commitChange(ctx, tx, http.StatusNoContent)
})
if err != nil {
return apiResponse{}, err
}
return noContent(), nil
}
type userListItem struct {
Username string `json:"username"`
Role string `json:"role"`
ZoneCount int64 `json:"zone_count"`
CreatedAt string `json:"created_at"`
LastLoginAt *string `json:"last_login_at"`
DeletedAt *string `json:"deleted_at"`
}
func userListItemOf(u userRow, zones int64) userListItem {
return userListItem{
Username: u.Username,
Role: u.Role,
ZoneCount: zones,
CreatedAt: apiTime(u.CreatedAt),
LastLoginAt: apiNullTime(u.LastLoginAt),
DeletedAt: apiNullTime(u.DeletedAt),
}
}
func queryFlag(q url.Values, name string) (bool, error) {
if !q.Has(name) {
return false, nil
}
switch q.Get(name) {
case "true":
return true, nil
case "false", "":
return false, nil
}
return false, badParameter(name)
}
func handleUserList(ctx context.Context, c *apiContext) (apiResponse, error) {
deleted, err := queryFlag(c.Request.URL.Query(), "deleted")
if err != nil {
return apiResponse{}, err
}
users, err := c.Server.store.ListUsers(ctx, deleted)
if err != nil {
return apiResponse{}, err
}
out := make([]userListItem, 0, len(users))
for _, u := range users {
out = append(out, userListItemOf(u.userRow, u.Zones))
}
return okJSON(map[string]any{"users": out}), nil
}
type userCreateRequest struct {
Username string `json:"username"`
Role string `json:"role"`
Password string `json:"password"`
}
func roleFieldMessage() string {
return "must be admin or user"
}
func handleUserCreate(ctx context.Context, c *apiContext) (apiResponse, error) {
var req userCreateRequest
if err := c.decodeJSON(&req); err != nil {
return apiResponse{}, err
}
fields := map[string]string{}
if err := checkUsername(req.Username); err != nil {
fields["username"] = err.Error()
}
if !validRole(req.Role) {
fields["role"] = roleFieldMessage()
}
if err := checkPasswordRules(req.Password); err != nil {
fields["password"] = err.Error()
}
if len(fields) > 0 {
return apiResponse{}, &apiError{Status: http.StatusUnprocessableEntity, Message: "invalid user", Fields: fields}
}
s := c.Server
hash, err := s.hashPassword(req.Password)
if err != nil {
return apiResponse{}, err
}
var created userRow
err = s.store.InTx(ctx, func(tx webTx) error {
if _, err := lockActingAdmin(ctx, c, tx); err != nil {
return err
}
u, err := tx.CreateUser(ctx, req.Username, req.Role, hash, c.Now)
if errors.Is(err, errUsernameTaken) {
return &apiError{Status: http.StatusConflict, Message: msgUsernameTaken}
}
if err != nil {
return err
}
created = u
c.setTargetUser(u)
c.recordChange(nil, auditUserJSON(u))
return c.commitChange(ctx, tx, http.StatusCreated)
})
if err != nil {
c.Entry.TargetUserID = sql.NullInt64{}
return apiResponse{}, err
}
return apiResponse{Status: http.StatusCreated, Body: userListItemOf(created, 0)}, nil
}
type userZoneItem struct {
Zone string `json:"zone"`
Exists bool `json:"exists"`
}
type userDetail struct {
Username string `json:"username"`
Role string `json:"role"`
CreatedAt string `json:"created_at"`
LastLoginAt *string `json:"last_login_at"`
DeletedAt *string `json:"deleted_at"`
Zones []userZoneItem `json:"zones"`
}
func handleUserRead(ctx context.Context, c *apiContext) (apiResponse, error) {
u, err := c.lookupUser(ctx)
if err != nil {
return apiResponse{}, err
}
zones, err := c.Server.store.UserZones(ctx, u.ID)
if err != nil {
return apiResponse{}, err
}
out := userDetail{
Username: u.Username,
Role: u.Role,
CreatedAt: apiTime(u.CreatedAt),
LastLoginAt: apiNullTime(u.LastLoginAt),
DeletedAt: apiNullTime(u.DeletedAt),
Zones: make([]userZoneItem, 0, len(zones)),
}
for _, z := range zones {
out.Zones = append(out.Zones, userZoneItem{Zone: z.Zone, Exists: z.ZoneExists})
}
return okJSON(out), nil
}
func (c *apiContext) foreignUsername() (string, error) {
username, err := c.pathUsername()
if err != nil {
return "", err
}
if isOwnAccount(c.Principal, username) {
c.setTargetUser(c.Principal.User)
return "", ownAccountError()
}
return username, nil
}
type userRoleRequest struct {
Role string `json:"role"`
}
func lockAdminsAndTarget(ctx context.Context, c *apiContext, tx webTx, username string) (userRow, []userRow, error) {
admins, err := lockActingAdmin(ctx, c, tx)
if err != nil {
return userRow{}, nil, err
}
u, err := activeTargetForUpdate(ctx, c, tx, username)
return u, admins, err
}
func handleUserRole(ctx context.Context, c *apiContext) (apiResponse, error) {
username, err := c.foreignUsername()
if err != nil {
return apiResponse{}, err
}
var req userRoleRequest
if err := c.decodeJSON(&req); err != nil {
return apiResponse{}, err
}
if !validRole(req.Role) {
return apiResponse{}, fieldError("role", roleFieldMessage())
}
err = c.Server.store.InTx(ctx, func(tx webTx) error {
u, admins, err := lockAdminsAndTarget(ctx, c, tx, username)
if err != nil {
return err
}
if u.Role == req.Role {
return nil
}
if leavesNoActiveAdmin(u, admins) {
return lastAdminError()
}
if err := tx.SetRole(ctx, u.ID, req.Role, c.Now); err != nil {
return err
}
after := u
after.Role = req.Role
c.recordChange(auditUserJSON(u), auditUserJSON(after))
return c.commitChange(ctx, tx, http.StatusNoContent)
})
if err != nil {
return apiResponse{}, err
}
return noContent(), nil
}
type userPasswordRequest struct {
Password string `json:"password"`
}
func handleUserPassword(ctx context.Context, c *apiContext) (apiResponse, error) {
username, err := c.foreignUsername()
if err != nil {
return apiResponse{}, err
}
var req userPasswordRequest
if err := c.decodeJSON(&req); err != nil {
return apiResponse{}, err
}
if err := checkPasswordRules(req.Password); err != nil {
return apiResponse{}, passwordFieldError("password", err)
}
s := c.Server
hash, err := s.hashPassword(req.Password)
if err != nil {
return apiResponse{}, err
}
err = s.store.InTx(ctx, func(tx webTx) error {
if _, err := lockActingAdmin(ctx, c, tx); err != nil {
return err
}
u, err := activeTargetForUpdate(ctx, c, tx, username)
if err != nil {
return err
}
if err := tx.SetPassword(ctx, u.ID, hash, c.Now); err != nil {
return err
}
if _, err := tx.DeleteUserSessions(ctx, u.ID); err != nil {
return err
}
snapshot := auditUserJSON(u)
c.recordChange(snapshot, snapshot)
return c.commitChange(ctx, tx, http.StatusNoContent)
})
if err != nil {
return apiResponse{}, err
}
return noContent(), nil
}
type confirmRequest struct {
Confirm string `json:"confirm"`
}
func handleUserDelete(ctx context.Context, c *apiContext) (apiResponse, error) {
username, err := c.foreignUsername()
if err != nil {
return apiResponse{}, err
}
var req confirmRequest
if err := c.decodeJSON(&req); err != nil {
return apiResponse{}, err
}
if req.Confirm != username {
return apiResponse{}, fieldError("confirm", msgConfirmMismatch)
}
err = c.Server.store.InTx(ctx, func(tx webTx) error {
u, admins, err := lockAdminsAndTarget(ctx, c, tx, username)
if err != nil {
return err
}
if leavesNoActiveAdmin(u, admins) {
return lastAdminError()
}
if err := tx.MarkDeleted(ctx, u.ID, c.Now); err != nil {
return err
}
if _, err := tx.DeleteUserSessions(ctx, u.ID); err != nil {
return err
}
after := u
after.DeletedAt = sql.NullTime{Time: dbTime(c.Now), Valid: true}
c.recordChange(auditUserJSON(u), auditUserJSON(after))
return c.commitChange(ctx, tx, http.StatusNoContent)
})
if err != nil {
return apiResponse{}, err
}
return noContent(), nil
}
type auditItem struct {
ID int64 `json:"id"`
Time string `json:"time"`
Actor string `json:"actor"`
Origin string `json:"origin"`
Operation string `json:"operation"`
Status *int64 `json:"status"`
Error *string `json:"error"`
Zone *string `json:"zone"`
RecordID *int64 `json:"record_id"`
TargetUser *string `json:"target_user"`
Before json.RawMessage `json:"before"`
After json.RawMessage `json:"after"`
}
type auditResponse struct {
Entries []auditItem `json:"entries"`
NextBeforeID *int64 `json:"next_before_id"`
}
func nullInt(v sql.NullInt64) *int64 {
if !v.Valid {
return nil
}
return &v.Int64
}
func nullString(v sql.NullString) *string {
if !v.Valid {
return nil
}
return &v.String
}
func rawJSON(b []byte) json.RawMessage {
if len(b) == 0 || !json.Valid(b) {
return json.RawMessage("null")
}
return json.RawMessage(b)
}
func auditItemOf(r auditRow) auditItem {
return auditItem{
ID: r.ID,
Time: apiTime(r.Time),
Actor: r.Actor,
Origin: r.Origin,
Operation: r.Operation,
Status: nullInt(r.Status),
Error: nullString(r.Error),
Zone: nullString(r.Zone),
RecordID: nullInt(r.RecordID),
TargetUser: nullString(r.TargetUsername),
Before: rawJSON(r.Before),
After: rawJSON(r.After),
}
}
func auditItemFor(p principal, r auditRow) auditItem {
item := auditItemOf(r)
refused := !r.Status.Valid || r.Status.Int64 >= 400
if !p.isAdmin() && r.TargetUserID.Valid && r.TargetUserID.Int64 != p.User.ID && refused {
item.TargetUser = nil
}
return item
}
func parseAuditFilter(q url.Values) (auditFilter, error) {
f := auditFilter{Limit: auditDefaultLimit}
if v := q.Get("zone"); v != "" {
zone, err := normalizeZone(v)
if err != nil {
return auditFilter{}, badParameter("zone")
}
f.Zone = zone
}
if v := q.Get("actor"); v != "" {
if len([]rune(v)) > auditMaxActorRunes {
return auditFilter{}, badParameter("actor")
}
f.Actor = v
}
if v := q.Get("operation"); v != "" {
if !knownOperation(v) {
return auditFilter{}, badParameter("operation")
}
f.Operation = v
}
switch v := q.Get("kind"); v {
case "", auditKindRead, auditKindChange:
f.Kind = v
default:
return auditFilter{}, badParameter("kind")
}
switch v := q.Get("outcome"); v {
case "", auditOutcomeSuccess, auditOutcomeError:
f.Outcome = v
default:
return auditFilter{}, badParameter("outcome")
}
if v := q.Get("before_id"); v != "" {
n, err := parsePositive(v, auditMaxBeforeID)
if err != nil {
return auditFilter{}, badParameter("before_id")
}
f.BeforeID = n
}
if v := q.Get("limit"); v != "" {
n, err := parsePositive(v, auditMaxLimit)
if err != nil {
return auditFilter{}, badParameter("limit")
}
f.Limit = int(n)
}
return f, nil
}
func parsePositive(s string, max int64) (int64, error) {
if s == "" || len(s) > 19 {
return 0, strconv.ErrSyntax
}
for _, r := range s {
if r < '0' || r > '9' {
return 0, strconv.ErrSyntax
}
}
n, err := strconv.ParseInt(s, 10, 64)
if err != nil || n < 1 || n > max {
return 0, strconv.ErrRange
}
return n, nil
}
func handleAuditRead(ctx context.Context, c *apiContext) (apiResponse, error) {
f, err := parseAuditFilter(c.Request.URL.Query())
if err != nil {
return apiResponse{}, err
}
if !c.Principal.isAdmin() {
f.RestrictToUserID = sql.NullInt64{Int64: c.Principal.User.ID, Valid: true}
}
delegated := map[string]bool{}
if !c.Principal.isAdmin() {
zones, err := c.Server.store.UserZones(ctx, c.Principal.User.ID)
if err != nil {
return apiResponse{}, err
}
for _, z := range zones {
delegated[z.Zone] = true
}
}
limit := f.Limit
f.Limit = limit + 1
rows, err := c.Server.store.ListAudit(ctx, f)
if err != nil {
return apiResponse{}, err
}
rows = slices.DeleteFunc(rows, func(r auditRow) bool { return !auditVisibleTo(c.Principal, r.auditEntry, delegated) })
resp := auditResponse{Entries: make([]auditItem, 0, min(len(rows), limit))}
for i, r := range rows {
if i == limit {
next := rows[limit-1].ID
resp.NextBeforeID = &next
break
}
resp.Entries = append(resp.Entries, auditItemFor(c.Principal, r))
}
return okJSON(resp), nil
}
func zoneAPIHandlers(s *WebServer) map[string]apiHandler {
h := zoneHandlers{s}
return map[string]apiHandler{
opZoneList: h.listZones,
opZoneCreate: h.createZone,
opZoneRead: h.readZone,
opZoneDelete: h.deleteZone,
opRecordList: h.listRecords,
opRecordCreate: h.createRecord,
opRecordUpdate: h.updateRecord,
opRecordDelete: h.deleteRecord,
opRecordBulkDelete: h.bulkDelete,
opSOAUpdate: h.updateSOA,
opZoneCheck: h.checkZone,
opCheckAll: h.checkAll,
opZoneExport: h.exportZone,
opZoneImportPreview: h.previewImport,
opZoneImport: h.applyImport,
}
}
type zoneHandlers struct {
server *WebServer
}
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, errZoneNotFound()
}
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 errZoneNotFound()
}
if actor.Role == "user" {
allowed, err := w.delegations.HasDelegationForShare(ctx, c.Zone, actor.ID)
if err != nil {
return err
}
if !allowed {
return errZoneNotFound()
}
}
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 errZoneNotFound()
}
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"`
}
type zoneAPICreated struct {
zoneAPIView
Warnings []zoneAPIProblem `json:"warnings"`
}
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 zoneAPISelectSOA(rows []recordRow, etag string) recordRow {
for _, row := range rows {
if row.RecordType == "SOA" && recordETag(row) == etag {
return row
}
}
return zoneAPIFindSOA(rows)
}
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)
}
problems, warnings := validateZoneChanges(zone, nil, zoneChanges{Creates: rows})
if err := zoneAPIRuleError(problems, "name"); err != nil {
return apiResponse{}, err
}
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, zoneAPIAuditRows(nil, deleted), zoneAPIAuditRows(rows, nil), true); err != nil {
return apiResponse{}, err
}
response := zoneAPISummary(zone, rows, c.Now, http.StatusCreated)
response.Body = zoneAPICreated{response.Body.(zoneAPIView), zoneAPIProblems(warnings)}
return response, 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)
parsed := err == nil && len(decoded.fields) == 0 && decoded.decodeErr == nil
if parsed {
data = decoded.data
}
if !parsed || slices.ContainsFunc(problems, func(p zoneProblem) bool { return p.Severity == "error" }) {
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)
response, err := 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
})
if err != nil {
c.Entry.RecordID = sql.NullInt64{}
}
return response, err
}
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, warnings := 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.StatusOK, Body: map[string]any{"warnings": zoneAPIProblems(warnings)}}, 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, warnings := 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]any{"deleted": len(changes.Deletes), "warnings": zoneAPIProblems(warnings)}}, 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 := zoneAPISelectSOA(w.rows, c.Request.Header.Get("If-Match"))
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
}
row := zoneAPIUpdatedRow(after, current)
soa := zoneAPISOA(row, c.Now)
return apiResponse{
Status: http.StatusOK, Header: zoneAPIETag(recordETag(row)),
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)),
}
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})
}
result.Warnings = zoneAPIImportWarnings(diff, lines)
return result
}
func zoneAPIImportWarnings(diff zoneImportDiff, lines []int) []zoneAPIImportMessage {
warnings := make([]zoneAPIImportMessage, 0, len(diff.Warnings))
for i, problem := range diff.Warnings {
message := zoneAPIImportMessage{Message: problem.Message}
if i < len(lines) {
message.Line = lines[i]
}
warnings = append(warnings, message)
}
return warnings
}
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, lines, 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]any{
"added": len(diff.Changes.Creates), "updated": len(diff.Updated), "deleted": len(diff.Deleted),
"warnings": zoneAPIImportWarnings(diff, lines),
}}, nil
})
}