299 lines
9.2 KiB
Go
299 lines
9.2 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/easydns"
|
|
"git.linuxiarz.pl/gru/EasyDNS-Web/internal/telemetry"
|
|
)
|
|
|
|
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)
|
|
}
|
|
client, err := easydns.New(cfg.APIURL, cfg.TokenFile, cfg.APISocket)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
ts, err := loadTemplates()
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return &Server{cfg: cfg, api: client, telemetry: telemetry.New(), auth: a, templates: ts}, nil
|
|
}
|
|
func (s *Server) Run(ctx context.Context) error {
|
|
go s.telemetry.Run(ctx, s.api)
|
|
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)
|
|
switch {
|
|
case r.URL.Path == "/logout" && r.Method == "POST":
|
|
s.auth.setCookie(w, "", -1)
|
|
http.Redirect(w, r, "/login", http.StatusSeeOther)
|
|
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/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}
|
|
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 "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, _ *http.Request) {
|
|
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("")
|