Files
EasyDNS-Web/internal/server/pages.go
T
Mateusz Gruszczyński 8c4d463f1e
Go quality gates / test (push) Waiting to run
first commit
2026-11-30 11:37:40 +01:00

474 lines
17 KiB
Go

package server
import (
"context"
"fmt"
"net/http"
"net/url"
"strconv"
"strings"
"git.linuxiarz.pl/gru/EasyDNS-Web/internal/easydns"
)
func (s *Server) overview(w http.ResponseWriter, r *http.Request) {
var d PageData
errs := []string{}
if e := s.get(r.Context(), "/api/v1/status", &d.Status); e != nil {
errs = append(errs, callError(e))
}
if e := s.get(r.Context(), "/api/v1/stats", &d.Stats); e != nil {
errs = append(errs, callError(e))
}
if e := s.get(r.Context(), "/api/v1/health", &d.Health); e != nil {
errs = append(errs, callError(e))
}
var audits struct {
Items []easydns.AuditItem `json:"items"`
}
if s.get(r.Context(), "/api/v1/audit?n=6", &audits) == nil {
d.Audit = audits.Items
}
smp, e, last := s.telemetry.Snapshot()
d.SamplingCount = len(smp)
d.SamplingTime = last
d.SamplingError = e
if len(errs) > 0 {
d.Error = strings.Join(errs, "; ")
}
s.render(w, r, "overview", "Overview", "DNS health, authority and resolver operations.", "overview", "DNS / OVERVIEW", d)
}
func (s *Server) zones(w http.ResponseWriter, r *http.Request) {
var d PageData
v := r.URL.Query()
d.Filter = map[string]string{"name": v.Get("name"), "kind": v.Get("kind")}
page := getInt(v.Get("page"), 1, 1, 100000)
query := url.Values{"page": {strconv.Itoa(page)}, "per_page": {"25"}}
for _, k := range []string{"name", "kind"} {
if t := strings.TrimSpace(d.Filter[k]); t != "" {
query.Set(k, t)
}
}
var result easydns.Page[easydns.Zone]
if err := s.get(r.Context(), "/api/v1/zones?"+query.Encode(), &result); err != nil {
d.Error = err.Error()
} else {
d.Zones = result.Items
d.Pagination = result.Pagination
}
s.render(w, r, "zones", "Zones", "Inspect authoritative and secondary zones and their state.", "zones", "DNS / ZONES", d)
}
func (s *Server) zoneCreateForm(w http.ResponseWriter, r *http.Request, fromFile bool) {
d := PageData{Form: map[string]string{}, Action: "new"}
if fromFile {
d.Action = "import"
}
s.render(w, r, "zone-form", "Create primary zone", "Define a new primary zone on EasyDNS.", "zones", "DNS / ZONES / CREATE", d)
}
func (s *Server) zoneCreate(w http.ResponseWriter, r *http.Request) {
r.Body = http.MaxBytesReader(w, r.Body, 2<<20)
if err := r.ParseForm(); err != nil {
http.Error(w, "Invalid form", 400)
return
}
d := PageData{Form: formValues(r, "name", "ns", "hostmaster", "transfer_acl", "notify", "zone_file", "mode")}
name := strings.TrimSpace(d.Form["name"])
isFile := d.Form["mode"] == "import"
d.Action = "new"
if isFile {
d.Action = "import"
}
if name == "" {
d.Error = "Zone name is required."
s.render(w, r, "zone-form", "Create primary zone", "Define a new primary zone.", "zones", "DNS / ZONES / CREATE", d)
return
}
payload := map[string]any{"name": name, "transfer_acl": splitLines(d.Form["transfer_acl"]), "notify": splitLines(d.Form["notify"])}
if isFile {
if strings.TrimSpace(d.Form["zone_file"]) == "" {
d.Error = "Full zone file text is required."
} else {
payload["zone_file"] = d.Form["zone_file"]
}
} else {
ns := splitLines(d.Form["ns"])
if len(ns) == 0 {
d.Error = "At least one nameserver is required."
} else {
payload["ns"] = ns
}
if strings.TrimSpace(d.Form["hostmaster"]) != "" {
payload["hostmaster"] = strings.TrimSpace(d.Form["hostmaster"])
}
}
if d.Error != "" {
s.render(w, r, "zone-form", "Create primary zone", "Define a new primary zone.", "zones", "DNS / ZONES / CREATE", d)
return
}
var res struct {
Name string `json:"name"`
}
if err := s.api.Write(r.Context(), "POST", "/api/v1/zones", payload, "", &res); err != nil {
d.Error = err.Error()
s.render(w, r, "zone-form", "Create primary zone", "Define a new primary zone.", "zones", "DNS / ZONES / CREATE", d)
return
}
if res.Name == "" {
res.Name = name
}
redirect(w, r, "/zones/"+easydns.Escape(res.Name)+"?notice=zone-created")
}
func splitLines(s string) []string {
f := strings.FieldsFunc(s, func(r rune) bool { return r == '\n' || r == '\r' || r == ',' })
a := []string{}
for _, x := range f {
if x = strings.TrimSpace(x); x != "" {
a = append(a, x)
}
}
return a
}
func (s *Server) zoneRouter(w http.ResponseWriter, r *http.Request) {
path := strings.TrimPrefix(r.URL.Path, "/zones/")
p := strings.Split(path, "/")
if len(p) == 0 || p[0] == "" {
http.NotFound(w, r)
return
}
zone, e := url.PathUnescape(p[0])
if e != nil || strings.ContainsAny(zone, "/\\\x00") || len(zone) > 255 {
http.Error(w, "Invalid zone name", 400)
return
}
rest := p[1:]
key := strings.Join(rest, "/")
switch {
case key == "" && r.Method == "GET":
s.zoneDetail(w, r, zone, "overview")
case key == "records" && r.Method == "GET":
s.zoneDetail(w, r, zone, "records")
case key == "records" && r.Method == "POST":
s.recordSave(w, r, zone, "")
case key == "records/new" && r.Method == "GET":
s.recordForm(w, r, zone, "")
case key == "transfers" && r.Method == "GET":
s.zoneDetail(w, r, zone, "transfers")
case key == "dnssec" && r.Method == "GET":
s.zoneDetail(w, r, zone, "dnssec")
case key == "operations" && r.Method == "GET":
s.zoneDetail(w, r, zone, "operations")
case key == "replace" && r.Method == "GET":
s.zoneReplaceForm(w, r, zone)
case key == "replace" && r.Method == "POST":
s.zoneReplace(w, r, zone)
case key == "delete" && r.Method == "GET":
s.zoneDeleteForm(w, r, zone)
case key == "delete" && r.Method == "POST":
s.zoneDelete(w, r, zone)
case key == "notify" && r.Method == "POST":
s.zoneAction(w, r, zone, "notify")
case key == "sync" && r.Method == "POST":
s.zoneAction(w, r, zone, "sync")
case len(rest) == 3 && rest[0] == "records" && rest[2] == "edit" && r.Method == "GET":
s.recordForm(w, r, zone, rest[1])
case len(rest) == 3 && rest[0] == "records" && rest[2] == "delete" && r.Method == "GET":
s.recordDeleteForm(w, r, zone, rest[1])
case len(rest) == 3 && rest[0] == "records" && rest[2] == "delete" && r.Method == "POST":
s.recordDelete(w, r, zone, rest[1])
case len(rest) == 2 && rest[0] == "records" && r.Method == "POST":
s.recordSave(w, r, zone, rest[1])
default:
http.NotFound(w, r)
}
}
func (s *Server) readZone(ctx context.Context, zone string) (easydns.Zone, string, error) {
var out easydns.Zone
etag, err := s.api.Get(ctx, "/api/v1/zones/"+easydns.Escape(zone), &out)
return out, etag, err
}
func (s *Server) zoneDetail(w http.ResponseWriter, r *http.Request, name, tab string) {
d := PageData{Tab: tab, ZoneURL: "/zones/" + easydns.Escape(name)}
zone, etag, err := s.readZone(r.Context(), name)
if err != nil {
d.Error = err.Error()
} else {
d.Zone = zone
d.ETag = etag
d.IsPrimary = zone.IsPrimary()
}
if tab == "records" {
v := r.URL.Query()
query := url.Values{"page": {strconv.Itoa(getInt(v.Get("page"), 1, 1, 100000))}, "per_page": {"50"}}
d.Filter = map[string]string{"name": v.Get("name"), "type": v.Get("type")}
for _, k := range []string{"name", "type"} {
if v := strings.TrimSpace(d.Filter[k]); v != "" {
query.Set(k, v)
}
}
var p easydns.Page[easydns.Record]
if e, er := s.api.Get(r.Context(), "/api/v1/zones/"+easydns.Escape(name)+"/records?"+query.Encode(), &p); er != nil {
if d.Error == "" {
d.Error = er.Error()
}
} else {
d.Records = p.Items
d.Pagination = p.Pagination
if e != "" {
d.ETag = e
}
}
}
if tab == "transfers" {
var a struct {
Items []easydns.Transfer `json:"items"`
}
if e := s.get(r.Context(), "/api/v1/zones/"+easydns.Escape(name)+"/transfers", &a); e != nil {
if d.Error == "" {
d.Error = e.Error()
}
} else {
d.Transfers = a.Items
}
}
s.render(w, r, "zone", "Zone · "+name, "Zone state, records, transfers and diagnostics.", "zones", "DNS / ZONES / "+name, d)
}
func (s *Server) findRecord(ctx context.Context, zone, id string, pageHint int) (easydns.Record, string, error) {
// There is no individual-record GET. Search the real paginated list by its stable ID.
page := pageHint
if page < 1 {
page = 1
}
for n := 0; n < 100; n++ {
var records easydns.Page[easydns.Record]
path := fmt.Sprintf("/api/v1/zones/%s/records?page=%d&per_page=1000", easydns.Escape(zone), page)
etag, err := s.api.Get(ctx, path, &records)
if err != nil {
return easydns.Record{}, "", err
}
for _, rec := range records.Items {
if rec.ID == id {
return rec, etag, nil
}
}
if page*1000 >= records.Pagination.Total {
break
}
page++
}
return easydns.Record{}, "", &easydns.Error{Status: 404, Message: "record not found in zone record listing"}
}
func (s *Server) recordForm(w http.ResponseWriter, r *http.Request, zone, id string) {
d := PageData{ZoneURL: "/zones/" + easydns.Escape(zone), Form: map[string]string{"ttl": "3600"}, Action: "new"}
z, _, err := s.readZone(r.Context(), zone)
if err != nil {
d.Error = err.Error()
} else {
d.Zone = z
d.IsPrimary = z.IsPrimary()
}
if id != "" {
d.Action = "edit"
rec, etag, err := s.findRecord(r.Context(), zone, id, getInt(r.URL.Query().Get("page"), 1, 1, 100000))
if err != nil {
d.Error = err.Error()
} else {
d.Record = rec
d.ETag = etag
d.Form = map[string]string{"name": rec.Name, "type": rec.Type, "ttl": strconv.FormatUint(uint64(rec.TTL), 10), "data": rec.Data}
}
} else {
var p easydns.Page[easydns.Record]
etag, err := s.api.Get(r.Context(), "/api/v1/zones/"+easydns.Escape(zone)+"/records?per_page=1", &p)
if err != nil {
d.Error = err.Error()
} else {
d.ETag = etag
}
}
s.render(w, r, "record-form", map[bool]string{true: "Edit DNS record", false: "Add DNS record"}[id != ""], "Modify an authoritative zone with serial conflict protection.", "zones", "DNS / ZONES / "+zone+" / RECORDS", d)
}
func (s *Server) recordSave(w http.ResponseWriter, r *http.Request, zone, id string) {
r.Body = http.MaxBytesReader(w, r.Body, 16<<10)
if e := r.ParseForm(); e != nil {
http.Error(w, "Invalid form", 400)
return
}
d := PageData{ZoneURL: "/zones/" + easydns.Escape(zone), Action: "new", Form: formValues(r, "name", "type", "ttl", "data"), ETag: r.FormValue("etag")}
if id != "" {
d.Action = "edit"
d.Record.ID = id
}
z, _, e := s.readZone(r.Context(), zone)
if e != nil {
d.Error = e.Error()
} else {
d.Zone = z
d.IsPrimary = z.IsPrimary()
}
if e == nil && !z.IsPrimary() {
d.Error = "Records may only be changed on primary zones."
}
ttl, parseErr := strconv.ParseUint(strings.TrimSpace(d.Form["ttl"]), 10, 32)
if parseErr != nil || d.Form["name"] == "" || d.Form["type"] == "" || strings.TrimSpace(d.Form["data"]) == "" {
d.Error = "Name, type and data are required; TTL must be an integer between 0 and 4294967295."
}
if strings.EqualFold(d.Form["type"], "SOA") {
d.Error = "SOA is managed by zone replacement, not record CRUD."
}
if d.ETag == "" {
d.Error = "No current ETag. Reload the record form to prevent overwriting concurrent changes."
}
if d.Error != "" {
s.render(w, r, "record-form", "DNS record", "Modify an authoritative zone.", "zones", "DNS / ZONES / RECORDS", d)
return
}
payload := map[string]any{"name": strings.TrimSpace(d.Form["name"]), "type": strings.ToUpper(d.Form["type"]), "ttl": ttl, "data": strings.TrimSpace(d.Form["data"])}
method, path, notice := "POST", "/api/v1/zones/"+easydns.Escape(zone)+"/records", "record-added"
if id != "" {
method = "PUT"
path += "/" + easydns.Escape(id)
notice = "record-updated"
}
var out any
e = s.api.Write(r.Context(), method, path, payload, d.ETag, &out)
if e != nil {
if ae, ok := e.(*easydns.Error); ok && ae.Status == 412 {
s.conflict(w, r, zone, e.Error())
return
}
d.Error = e.Error()
s.render(w, r, "record-form", "DNS record", "Modify an authoritative zone.", "zones", "DNS / ZONES / RECORDS", d)
return
}
redirect(w, r, "/zones/"+easydns.Escape(zone)+"/records?notice="+notice)
}
func (s *Server) conflict(w http.ResponseWriter, r *http.Request, zone, msg string) {
d := PageData{ZoneURL: "/zones/" + easydns.Escape(zone), Error: msg}
s.render(w, r, "conflict", "Zone changed", "Another modification changed the zone serial. Reload records before editing again.", "zones", "DNS / ZONES / CONFLICT", d)
}
func (s *Server) recordDeleteForm(w http.ResponseWriter, r *http.Request, zone, id string) {
d := PageData{ZoneURL: "/zones/" + easydns.Escape(zone), Action: "record"}
rec, etag, e := s.findRecord(r.Context(), zone, id, getInt(r.URL.Query().Get("page"), 1, 1, 100000))
if e != nil {
d.Error = e.Error()
} else {
d.Record = rec
d.ETag = etag
if strings.EqualFold(rec.Type, "SOA") {
d.Error = "SOA cannot be deleted using the record API."
}
}
s.render(w, r, "delete-confirm", "Delete DNS record", "Confirm permanent removal of a DNS record.", "zones", "DNS / ZONES / RECORDS / DELETE", d)
}
func (s *Server) recordDelete(w http.ResponseWriter, r *http.Request, zone, id string) {
if r.FormValue("confirm") != "DELETE" {
http.Error(w, "Type DELETE to confirm", 400)
return
}
etag := r.FormValue("etag")
if etag == "" {
http.Error(w, "Missing zone serial. Reload.", 409)
return
}
if e := s.api.Write(r.Context(), "DELETE", "/api/v1/zones/"+easydns.Escape(zone)+"/records/"+easydns.Escape(id), nil, etag, nil); e != nil {
if ae, ok := e.(*easydns.Error); ok && ae.Status == 412 {
s.conflict(w, r, zone, e.Error())
return
}
d := PageData{Error: e.Error(), Action: "record", Record: easydns.Record{ID: id}, ZoneURL: "/zones/" + easydns.Escape(zone), ETag: etag}
s.render(w, r, "delete-confirm", "Delete DNS record", "Delete operation failed.", "zones", "DNS / ZONES / DELETE", d)
return
}
redirect(w, r, "/zones/"+easydns.Escape(zone)+"/records?notice=record-deleted")
}
func (s *Server) zoneReplaceForm(w http.ResponseWriter, r *http.Request, zone string) {
d := PageData{ZoneURL: "/zones/" + easydns.Escape(zone), Form: map[string]string{}}
z, etag, e := s.readZone(r.Context(), zone)
if e != nil {
d.Error = e.Error()
} else {
d.Zone = z
d.ETag = etag
d.IsPrimary = z.IsPrimary()
}
s.render(w, r, "replace-zone", "Replace zone file", "Submit a complete zone file. The original text cannot be retrieved from the API.", "zones", "DNS / ZONES / REPLACE", d)
}
func (s *Server) zoneReplace(w http.ResponseWriter, r *http.Request, zone string) {
r.Body = http.MaxBytesReader(w, r.Body, 2<<20)
if e := r.ParseForm(); e != nil {
http.Error(w, "Invalid form", 400)
return
}
d := PageData{ZoneURL: "/zones/" + easydns.Escape(zone), ETag: r.FormValue("etag"), Form: formValues(r, "zone_file")}
if d.ETag == "" || d.Form["zone_file"] == "" || r.FormValue("confirm") != "REPLACE" {
d.Error = "Full zone file, current ETag and the word REPLACE are required."
} else {
e := s.api.Write(r.Context(), "PUT", "/api/v1/zones/"+easydns.Escape(zone), map[string]string{"zone_file": d.Form["zone_file"]}, d.ETag, nil)
if e == nil {
redirect(w, r, d.ZoneURL+"?notice=zone-replaced")
return
}
if ae, ok := e.(*easydns.Error); ok && ae.Status == 412 {
s.conflict(w, r, zone, e.Error())
return
}
d.Error = e.Error()
}
s.render(w, r, "replace-zone", "Replace zone file", "Submit a complete zone file.", "zones", "DNS / ZONES / REPLACE", d)
}
func (s *Server) zoneDeleteForm(w http.ResponseWriter, r *http.Request, zone string) {
d := PageData{ZoneURL: "/zones/" + easydns.Escape(zone), Action: "zone"}
z, _, e := s.readZone(r.Context(), zone)
if e != nil {
d.Error = e.Error()
} else {
d.Zone = z
}
s.render(w, r, "delete-confirm", "Delete zone", "Only API-created zones can be deleted. File-configured zones return HTTP 409.", "zones", "DNS / ZONES / DELETE", d)
}
func (s *Server) zoneDelete(w http.ResponseWriter, r *http.Request, zone string) {
if r.FormValue("confirm") != zone {
d := PageData{Error: "Type the full zone name exactly to confirm.", ZoneURL: "/zones/" + easydns.Escape(zone), Zone: easydns.Zone{Name: zone}, Action: "zone"}
s.render(w, r, "delete-confirm", "Delete zone", "Confirm deletion.", "zones", "DNS / ZONES / DELETE", d)
return
}
e := s.api.Write(r.Context(), "DELETE", "/api/v1/zones/"+easydns.Escape(zone), nil, "", nil)
if e != nil {
d := PageData{Error: e.Error(), ZoneURL: "/zones/" + easydns.Escape(zone), Zone: easydns.Zone{Name: zone}, Action: "zone"}
s.render(w, r, "delete-confirm", "Delete zone", "Delete failed.", "zones", "DNS / ZONES / DELETE", d)
return
}
redirect(w, r, "/zones?notice=zone-deleted")
}
func (s *Server) zoneAction(w http.ResponseWriter, r *http.Request, zone, action string) {
d := PageData{ZoneURL: "/zones/" + easydns.Escape(zone), Tab: "operations"}
z, _, e := s.readZone(r.Context(), zone)
if e != nil {
d.Error = e.Error()
} else {
d.Zone = z
d.IsPrimary = z.IsPrimary()
}
if e == nil && action == "sync" && !z.IsSecondary() {
d.Error = "Sync is only valid for a secondary zone."
}
if e == nil && action == "notify" && len(z.Config.Notify) == 0 {
d.Error = "No NOTIFY targets configured for this zone."
}
if d.Error == "" {
if r.FormValue("confirm") != "yes" {
d.Error = "Confirm the requested zone operation."
} else {
var result any
err := s.api.Write(r.Context(), "POST", "/api/v1/zones/"+easydns.Escape(zone)+"/"+action, nil, "", &result)
if err != nil {
d.Error = err.Error()
} else {
redirect(w, r, d.ZoneURL+"/operations?notice="+map[string]string{"sync": "synced", "notify": "notified"}[action])
return
}
}
}
s.render(w, r, "zone", "Zone · "+zone, "Zone operations.", "zones", "DNS / ZONES / "+zone, d)
}