Files
EasyDNS-Web/internal/server/server.go
T
Mateusz Gruszczyński de13d851a8
Go quality gates / test (push) Waiting to run
v0.1.1
2026-11-30 14:44:28 +01:00

370 lines
13 KiB
Go

package server
import (
"context"
"encoding/json"
"fmt"
"html/template"
"log/slog"
"net/http"
"net/url"
"strconv"
"strings"
"time"
"git.linuxiarz.pl/gru/EasyDNS-Web/internal/config"
"git.linuxiarz.pl/gru/EasyDNS-Web/internal/multiserver"
)
var Version = "dev"
func New(cfg config.Config) (*Server, error) {
a, err := newAuth(cfg)
if err != nil {
return nil, fmt.Errorf("panel auth: %w", err)
}
registry, err := multiserver.NewConfigured(cfg.MultiServer, cfg.MultiServerExplicit, cfg.AllowInsecureHTTP, cfg.NodesDir, cfg.APIURL, cfg.TokenFile, cfg.APISocket, cfg.APIToken)
if err != nil {
return nil, fmt.Errorf("multi-server registry: %w", err)
}
localName, localRole := cfg.LocalName, cfg.LocalRole
if localName == "" {
localName = "Local EasyDNS"
}
if localRole == "" {
localRole = "primary"
}
if err := registry.ApplyEnvironment(localName, localRole, cfg.Servers); err != nil {
return nil, fmt.Errorf("environment-managed servers: %w", err)
}
local, client, history := registry.Default()
ts, err := loadTemplates()
if err != nil {
return nil, err
}
return &Server{cfg: cfg, api: client, telemetry: history, auth: a, templates: ts, nodes: registry, selectedNode: local}, nil
}
func (s *Server) Run(ctx context.Context) error {
go s.nodes.Run(ctx)
httpServer := &http.Server{Addr: s.cfg.Listen, Handler: s.Handler(), ReadHeaderTimeout: 7 * time.Second, ReadTimeout: 20 * time.Second, WriteTimeout: 80 * time.Second, IdleTimeout: 90 * time.Second, MaxHeaderBytes: 1 << 20}
go func() {
<-ctx.Done()
down, cancel := context.WithTimeout(context.Background(), 8*time.Second)
defer cancel()
_ = httpServer.Shutdown(down)
}()
slog.Info("EasyDNS UI started", "listen", s.cfg.Listen, "api_mode", func() string {
if s.cfg.APISocket != "" {
return "unix"
}
return "tcp"
}())
err := httpServer.ListenAndServe()
if err == http.ErrServerClosed {
return nil
}
return err
}
func (s *Server) Handler() http.Handler {
mux := http.NewServeMux()
mux.Handle("GET /static/", http.StripPrefix("/static/", staticHandler()))
mux.HandleFunc("GET /login", s.loginPage)
mux.HandleFunc("POST /login", s.loginPost)
mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
_, _ = w.Write([]byte("easydns-ui: ok\n"))
})
mux.HandleFunc("/", s.authorized)
return secureHeaders(mux)
}
func (s *Server) authorized(w http.ResponseWriter, r *http.Request) {
sess, ok := s.auth.parseSession(r)
if !ok {
http.Redirect(w, r, "/login", http.StatusSeeOther)
return
}
w.Header().Set("Cache-Control", "no-store")
if r.Method == "POST" && !s.auth.checkCSRF(r, sess) {
http.Error(w, "Invalid CSRF token or Origin", http.StatusForbidden)
return
}
if r.Method != "GET" && r.Method != "HEAD" && r.Method != "POST" {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
csrf := s.auth.csrf(sess)
ctx := context.WithValue(r.Context(), csrfKey{}, csrf)
r = r.WithContext(ctx)
view := *s // Request-local API / telemetry selection: never mutate shared Server.
if s.nodes.Enabled() {
id := "local"
if c, err := r.Cookie(activeNodeCookie); err == nil {
id = c.Value
}
node, client, history, ok := s.nodes.Get(id)
if !ok {
// A deleted/invalid selection must never silently redirect DNS writes
// to the local server. This also makes a stale browser cookie visible.
clearNodeCookie(w, s.cfg.CookieSecure)
if r.Method == http.MethodPost && r.URL.Path != "/servers/select" && r.URL.Path != "/logout" && r.URL.Path != "/configuration/multi-server" {
http.Error(w, "Selected server no longer exists. No DNS operation was performed. Choose a server on the Servers page.", http.StatusConflict)
return
}
if r.Method == http.MethodGet || r.Method == http.MethodHead {
redirect(w, r, "/servers?notice=server-selection-expired")
return
}
node, client, history = s.nodes.Default()
}
view.selectedNode, view.api, view.telemetry = node, client, history
}
view.dispatch(w, r)
}
func (s *Server) dispatch(w http.ResponseWriter, r *http.Request) {
switch {
case r.URL.Path == "/logout" && r.Method == "POST":
s.auth.setCookie(w, "", -1)
clearNodeCookie(w, s.cfg.CookieSecure)
http.Redirect(w, r, "/login", http.StatusSeeOther)
case r.URL.Path == "/servers" && r.Method == "GET" && s.nodes.Enabled():
s.serversOverview(w, r)
case r.URL.Path == "/servers/new" && r.Method == "GET" && s.nodes.Enabled():
s.serverNewForm(w, r)
case r.URL.Path == "/servers" && r.Method == "POST" && s.nodes.Enabled():
s.serverCreate(w, r)
case r.URL.Path == "/servers/select" && r.Method == "POST" && s.nodes.Enabled():
s.serverSelect(w, r)
case r.URL.Path == "/servers/compare" && r.Method == "GET" && s.nodes.Enabled():
s.serverCompare(w, r)
case strings.HasPrefix(r.URL.Path, "/servers/") && s.nodes.Enabled():
s.serverAction(w, r)
case r.URL.Path == "/" && r.Method == "GET":
s.overview(w, r)
case r.URL.Path == "/ui/telemetry" && r.Method == "GET":
s.telemetryJSON(w, r)
case r.URL.Path == "/zones" && r.Method == "GET":
s.zones(w, r)
case r.URL.Path == "/zones/new" && r.Method == "GET":
s.zoneCreateForm(w, r, false)
case r.URL.Path == "/zones/import" && r.Method == "GET":
s.zoneCreateForm(w, r, true)
case r.URL.Path == "/zones" && r.Method == "POST":
s.zoneCreate(w, r)
case r.URL.Path == "/query" && r.Method == "GET":
s.query(w, r)
case r.URL.Path == "/upstreams" && r.Method == "GET":
s.upstreams(w, r)
case r.URL.Path == "/upstreams/new" && r.Method == "GET":
s.upstreamForm(w, r)
case r.URL.Path == "/upstreams" && r.Method == "POST":
s.upstreamCreate(w, r)
case r.URL.Path == "/policies" && r.Method == "GET":
s.policies(w, r)
case r.URL.Path == "/policies" && r.Method == "POST":
s.policiesSave(w, r)
case r.URL.Path == "/views" && r.Method == "GET":
s.policiesReadOnly(w, r, "views")
case r.URL.Path == "/acl" && r.Method == "GET":
s.policiesReadOnly(w, r, "acl")
case r.URL.Path == "/rate-limiting" && r.Method == "GET":
s.policiesReadOnly(w, r, "rate")
case r.URL.Path == "/blocklists" && r.Method == "GET":
s.blocklists(w, r)
case r.URL.Path == "/blocklists/new" && r.Method == "GET":
s.blockForm(w, r)
case r.URL.Path == "/blocklists" && r.Method == "POST":
s.blockCreate(w, r)
case r.URL.Path == "/cache" && r.Method == "GET":
s.cache(w, r)
case r.URL.Path == "/cache/flush" && r.Method == "POST":
s.cacheFlush(w, r)
case r.URL.Path == "/metrics" && r.Method == "GET":
s.metrics(w, r)
case r.URL.Path == "/audit" && r.Method == "GET":
s.audit(w, r)
case r.URL.Path == "/status" && r.Method == "GET":
s.status(w, r)
case r.URL.Path == "/configuration" && r.Method == "GET":
s.configuration(w, r)
case r.URL.Path == "/configuration/multi-server" && r.Method == "POST":
s.multiServerPreference(w, r)
case r.URL.Path == "/configuration/reload" && r.Method == "POST":
s.reload(w, r)
case strings.HasPrefix(r.URL.Path, "/zones/"):
s.zoneRouter(w, r)
default:
http.NotFound(w, r)
}
}
type csrfKey struct{}
func csrf(r *http.Request) string {
if v, ok := r.Context().Value(csrfKey{}).(string); ok {
return v
}
return ""
}
func (s *Server) render(w http.ResponseWriter, r *http.Request, page, title, subtitle, active, breadcrumb string, d PageData) {
t, ok := s.templates[page]
if !ok {
http.Error(w, "Missing template", http.StatusInternalServerError)
return
}
alert, kind := notice(r.URL.Query().Get("notice"))
if d.Success != "" {
alert = d.Success
kind = "ok"
}
if d.Error != "" {
alert = d.Error
kind = "danger"
}
v := PageView{Page: page, Title: title, Subtitle: subtitle, Active: active, Breadcrumb: breadcrumb, User: s.cfg.Username, CSRF: csrf(r), Message: alert, MessageType: kind, Data: d, BuildVersion: Version, MultiServer: s.nodes.Enabled(), CanEditMultiServer: !s.cfg.MultiServerExplicit, LocalRoleConfigured: s.cfg.LocalRoleExplicit, SelectedNode: s.selectedNode, CurrentPath: r.URL.RequestURI()}
if s.nodes.Enabled() {
v.Nodes = s.nodes.All()
}
w.Header().Set("Content-Type", "text/html; charset=utf-8")
if err := t.ExecuteTemplate(w, "base", v); err != nil {
slog.Error("render", "page", page, "err", err)
}
}
func notice(n string) (string, string) {
switch n {
case "zone-created":
return "Primary zone created successfully.", "ok"
case "zone-deleted":
return "API-managed zone deleted.", "ok"
case "zone-replaced":
return "Zone contents replaced; the zone serial was updated.", "ok"
case "record-added":
return "DNS record created.", "ok"
case "record-updated":
return "DNS record updated.", "ok"
case "record-deleted":
return "DNS record deleted.", "ok"
case "notified":
return "DNS NOTIFY accepted for configured targets. Delivery is not guaranteed.", "ok"
case "synced":
return "Secondary synchronization request completed.", "ok"
case "upstream-added":
return "Upstream added and configuration reloaded.", "ok"
case "policy-updated":
return "Supported policy settings saved.", "ok"
case "rule-added":
return "Block rule added.", "ok"
case "cache-flushed":
return "Cache invalidation completed.", "ok"
case "reloaded":
return "Configuration hot reload completed.", "ok"
case "server-added":
return "Remote EasyDNS server added. Its availability is checked live.", "ok"
case "server-removed":
return "Server connection removed from this panel. The DNS server was not changed.", "ok"
case "server-role":
return "Topology label updated. EasyDNS server configuration was not changed.", "ok"
case "server-selection-expired":
return "The previously selected server is no longer configured. Select a server before continuing.", "danger"
case "servers-enabled":
return "Multi-server management is enabled. Your local EasyDNS remains the default server.", "ok"
case "servers-disabled":
return "Multi-server management is disabled. Saved remote connections are retained but inactive.", "ok"
case "session-ended":
return "Signed out.", "ok"
default:
return "", ""
}
}
func redirect(w http.ResponseWriter, r *http.Request, target string) {
http.Redirect(w, r, target, http.StatusSeeOther)
}
func (s *Server) get(ctx context.Context, path string, out any) error {
_, err := s.api.Get(ctx, path, out)
return err
}
func (s *Server) telemetryJSON(w http.ResponseWriter, r *http.Request) {
mode := r.URL.Query().Get("mode")
if s.nodes.Enabled() && len(s.nodes.All()) > 1 && (mode == "aggregate" || mode == "split") {
s.fleetTelemetry(w, r, mode)
return
}
smp, errText, last := s.telemetry.Snapshot()
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.Header().Set("Cache-Control", "no-store")
_ = json.NewEncoder(w).Encode(map[string]any{"samples": smp, "error": errText, "lastPoll": last, "intervalSeconds": 15})
}
func (s *Server) loginPage(w http.ResponseWriter, r *http.Request) {
if _, ok := s.auth.parseSession(r); ok {
redirect(w, r, "/")
return
}
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.Header().Set("Cache-Control", "no-store")
_ = s.templates["login"].ExecuteTemplate(w, "login", map[string]any{"Error": "", "Username": s.cfg.Username})
}
func (s *Server) loginPost(w http.ResponseWriter, r *http.Request) {
if !sameOrigin(r) {
http.Error(w, "Origin denied", http.StatusForbidden)
return
}
r.Body = http.MaxBytesReader(w, r.Body, 8<<10)
if err := r.ParseForm(); err != nil {
http.Error(w, "Invalid form", http.StatusBadRequest)
return
}
ip := remoteIP(r)
pass := r.Form.Get("password")
u := r.Form.Get("username")
if !s.auth.allowedLogin(ip) {
w.WriteHeader(http.StatusTooManyRequests)
_ = s.templates["login"].ExecuteTemplate(w, "login", map[string]any{"Error": "Too many attempts. Try again later.", "Username": s.cfg.Username})
return
}
if !s.auth.verify(u, pass) {
s.auth.failLogin(ip)
w.WriteHeader(http.StatusUnauthorized)
_ = s.templates["login"].ExecuteTemplate(w, "login", map[string]any{"Error": "Invalid credentials.", "Username": s.cfg.Username})
return
}
s.auth.clearFailure(ip)
s.auth.setCookie(w, s.auth.makeSession(), int(sessionTTL.Seconds()))
redirect(w, r, "/")
}
func getInt(v string, def, min, max int) int {
n, err := strconv.Atoi(v)
if err != nil || n < min {
return def
}
if n > max {
return max
}
return n
}
func formValues(r *http.Request, keys ...string) map[string]string {
m := make(map[string]string, len(keys))
for _, k := range keys {
m[k] = r.FormValue(k)
}
return m
}
func failAPI(d *PageData, err error) {
if err != nil {
d.Error = err.Error()
}
}
func encQ(values url.Values) string {
if len(values) == 0 {
return ""
}
return "?" + values.Encode()
}
func callError(err error) string {
if err == nil {
return ""
}
return err.Error()
}
func stringTrim(v string) string { return strings.TrimSpace(v) }
var _ = template.HTML("")