feat(api): add zone and record handlers

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

No files matched your search

+83
View File
@@ -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
}