v0.1.1
Go quality gates / test (push) Waiting to run

This commit is contained in:
Mateusz Gruszczyński committed 2026-11-30 14:44:28 +01:00
1 parent 8c4d463f1e
commit de13d851a8
75 files changed
+4656 -442

No files matched your search

+169 -23
View File
@@ -3,20 +3,44 @@ package config
import (
"errors"
"fmt"
"net"
"net/url"
"os"
"strconv"
"strings"
)
// ServerSeed is a config-managed EasyDNS instance. Token contents are held
// only in process memory and never included in HTML, JSON or logs.
type ServerSeed struct {
Slot int
Name string
Role string
URL string
Token string
TokenFile string
}
type Config struct {
Listen string
APIURL string
APISocket string
TokenFile string
PasswordFile string
SessionKeyFile string
CookieSecure bool
Username string
Listen string
APIURL string
APISocket string
TokenFile string
APIToken string
PasswordFile string
Password string
SessionKeyFile string
SessionAuto bool
CookieSecure bool
Username string
MultiServer bool
MultiServerExplicit bool
LocalRoleExplicit bool
AllowInsecureHTTP bool
NodesDir string
LocalName string
LocalRole string
Servers []ServerSeed
}
func env(key, fallback string) string {
@@ -26,27 +50,149 @@ func env(key, fallback string) string {
return fallback
}
func parseBool(key string, fallback bool) (bool, error) {
v := strings.TrimSpace(os.Getenv(key))
if v == "" {
return fallback, nil
}
value, err := strconv.ParseBool(v)
if err != nil {
return false, fmt.Errorf("invalid %s: must be true or false", key)
}
return value, nil
}
// Load applies defaults, then the optional TOML file, then explicit environment
// variables. EASYDNS_UI_CONFIG_FILE selects a required file; otherwise Debian's
// /etc/easydns-ui/config.toml is used if present (Docker .env works without it).
// A specified multi-server enabled value in TOML or the environment is
// authoritative. The UI preference is available only when neither sets it.
func Load() (Config, error) {
c := Config{
Listen: env("EASYDNS_UI_LISTEN", "127.0.0.1:8088"),
APIURL: env("EASYDNS_API_URL", "http://127.0.0.1:9953"),
APISocket: os.Getenv("EASYDNS_API_SOCKET"),
TokenFile: env("EASYDNS_API_TOKEN_FILE", "/etc/easydns/data/control.token"),
PasswordFile: env("EASYDNS_UI_PASSWORD_FILE", "/etc/easydns-ui/panel.password"),
SessionKeyFile: env("EASYDNS_UI_SESSION_KEY_FILE", "/etc/easydns-ui/session.key"),
CookieSecure: env("EASYDNS_UI_COOKIE_SECURE", "false") == "true",
Username: env("EASYDNS_UI_USERNAME", "admin"),
Listen: "127.0.0.1:8088",
APIURL: "http://127.0.0.1:9953",
TokenFile: "/etc/easydns/data/control.token",
PasswordFile: "/etc/easydns-ui/panel.password",
SessionKeyFile: "/etc/easydns-ui/session.key",
Username: "admin",
NodesDir: "/var/lib/easydns-ui",
LocalName: "Local EasyDNS",
LocalRole: "primary",
}
if _, err := strconv.Atoi(strings.Split(c.Listen, ":")[len(strings.Split(c.Listen, ":"))-1]); err != nil {
return c, fmt.Errorf("invalid listen address: %w", err)
path, explicit := os.LookupEnv("EASYDNS_UI_CONFIG_FILE")
if !explicit {
path = "/etc/easydns-ui/config.toml"
}
if c.APISocket == "" && !strings.HasPrefix(c.APIURL, "http://127.0.0.1:") && !strings.HasPrefix(c.APIURL, "http://[::1]:") && !strings.HasPrefix(c.APIURL, "https://") {
return c, errors.New("API URL must be loopback HTTP or HTTPS")
if path == "" {
return c, errors.New("EASYDNS_UI_CONFIG_FILE must be an absolute file path")
}
for _, path := range []string{c.PasswordFile, c.SessionKeyFile} {
if _, err := os.Stat(path); err != nil {
return c, fmt.Errorf("required credential file %s: %w", path, err)
if !strings.HasPrefix(path, "/") {
return c, errors.New("EASYDNS_UI_CONFIG_FILE must be an absolute file path")
}
if err := readTOMLConfig(&c, path); err != nil {
if !errors.Is(err, os.ErrNotExist) || explicit {
return c, fmt.Errorf("load panel configuration %s: %w", path, err)
}
}
c.Listen = env("EASYDNS_UI_LISTEN", c.Listen)
c.APIURL = env("EASYDNS_API_URL", c.APIURL)
c.APISocket = env("EASYDNS_API_SOCKET", c.APISocket)
c.TokenFile = env("EASYDNS_API_TOKEN_FILE", c.TokenFile)
c.APIToken = env("EASYDNS_API_TOKEN", c.APIToken)
c.PasswordFile = env("EASYDNS_UI_PASSWORD_FILE", c.PasswordFile)
if p, ok := os.LookupEnv("EASYDNS_UI_PASSWORD"); ok && p != "" {
c.Password = p
}
c.SessionKeyFile = env("EASYDNS_UI_SESSION_KEY_FILE", c.SessionKeyFile)
c.Username = env("EASYDNS_UI_USERNAME", c.Username)
c.NodesDir = env("EASYDNS_UI_NODES_DIR", c.NodesDir)
c.LocalName = env("EASYDNS_UI_LOCAL_NAME", c.LocalName)
c.LocalRole = env("EASYDNS_UI_LOCAL_ROLE", c.LocalRole)
if value, ok := os.LookupEnv("EASYDNS_UI_LOCAL_ROLE"); ok && strings.TrimSpace(value) != "" {
c.LocalRoleExplicit = true
}
var err error
if c.CookieSecure, err = parseBool("EASYDNS_UI_COOKIE_SECURE", c.CookieSecure); err != nil {
return c, err
}
if c.SessionAuto, err = parseBool("EASYDNS_UI_SESSION_AUTO", c.SessionAuto); err != nil {
return c, err
}
if c.MultiServer, err = parseBool("EASYDNS_UI_MULTISERVER", c.MultiServer); err != nil {
return c, err
}
if _, ok := os.LookupEnv("EASYDNS_UI_MULTISERVER"); ok && strings.TrimSpace(os.Getenv("EASYDNS_UI_MULTISERVER")) != "" {
c.MultiServerExplicit = true
}
if c.AllowInsecureHTTP, err = parseBool("EASYDNS_UI_ALLOW_INSECURE_HTTP", c.AllowInsecureHTTP); err != nil {
return c, err
}
if _, portText, e := net.SplitHostPort(c.Listen); e != nil {
return c, fmt.Errorf("invalid listen address: %w", e)
} else {
port, pErr := strconv.Atoi(portText)
if pErr != nil || port < 1 || port > 65535 {
return c, errors.New("invalid listen port")
}
}
if c.APISocket == "" {
u, e := url.Parse(c.APIURL)
if e != nil || u == nil || u.Host == "" || u.User != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Path != "" || u.RawQuery != "" || u.Fragment != "" {
return c, errors.New("EasyDNS API URL must be an http(s) base URL without credentials or path")
}
if u.Scheme == "http" && !c.AllowInsecureHTTP {
h := u.Hostname()
ip := net.ParseIP(h)
if h != "localhost" && (ip == nil || !ip.IsLoopback()) {
return c, errors.New("EasyDNS API URL must use HTTPS or loopback HTTP (set EASYDNS_UI_ALLOW_INSECURE_HTTP=true only for trusted networks)")
}
}
}
if c.Password == "" {
if _, err := os.Stat(c.PasswordFile); err != nil {
return c, fmt.Errorf("required credential file %s (or panel.password / EASYDNS_UI_PASSWORD): %w", c.PasswordFile, err)
}
} else if len(c.Password) < 16 {
return c, errors.New("panel password must have at least 16 characters")
}
if !c.SessionAuto {
if _, err := os.Stat(c.SessionKeyFile); err != nil {
return c, fmt.Errorf("required session key file %s (or panel.session_auto / EASYDNS_UI_SESSION_AUTO=true): %w", c.SessionKeyFile, err)
}
}
// Environment-declared node slots override file-declared slots by slot ID;
// each environment slot must be fully defined (never mix token fragments).
bySlot := make(map[int]ServerSeed)
for _, seed := range c.Servers {
if seed.Slot < 1 || seed.Slot > 15 {
return c, errors.New("invalid config.toml server slot")
}
if _, ok := bySlot[seed.Slot]; ok {
return c, errors.New("duplicate config.toml server slot")
}
bySlot[seed.Slot] = seed
}
for i := 1; i <= 15; i++ {
prefix := fmt.Sprintf("EASYDNS_UI_SERVER_%d_", i)
seed := ServerSeed{Slot: i, Name: strings.TrimSpace(os.Getenv(prefix + "NAME")), URL: strings.TrimSpace(os.Getenv(prefix + "URL")), Role: env(prefix+"ROLE", "secondary"), Token: strings.TrimSpace(os.Getenv(prefix + "TOKEN")), TokenFile: strings.TrimSpace(os.Getenv(prefix + "TOKEN_FILE"))}
if seed.Name == "" && seed.URL == "" && seed.Token == "" && seed.TokenFile == "" {
continue
}
bySlot[i] = seed
}
c.Servers = nil
for i := 1; i <= 15; i++ {
seed, ok := bySlot[i]
if !ok {
continue
}
if seed.Name == "" || seed.URL == "" || (seed.Token == "" && seed.TokenFile == "") {
return c, fmt.Errorf("incomplete server slot %d: NAME, URL and TOKEN or TOKEN_FILE are required", i)
}
if seed.Token != "" && seed.TokenFile != "" {
return c, fmt.Errorf("server slot %d: use TOKEN or TOKEN_FILE, not both", i)
}
c.Servers = append(c.Servers, seed)
}
return c, nil
}
+46
View File
@@ -0,0 +1,46 @@
package config
import (
"path/filepath"
"strings"
"testing"
)
func TestDockerEnvironmentCredentialsAndServerSlots(t *testing.T) {
t.Setenv("EASYDNS_UI_PASSWORD", "a-strong-admin-password-123")
t.Setenv("EASYDNS_UI_SESSION_AUTO", "true")
t.Setenv("EASYDNS_UI_SESSION_KEY_FILE", filepath.Join(t.TempDir(), "session.key"))
t.Setenv("EASYDNS_API_URL", "https://primary.example.net:9953")
t.Setenv("EASYDNS_API_TOKEN", "primary-token-from-env")
t.Setenv("EASYDNS_UI_MULTISERVER", "true")
t.Setenv("EASYDNS_UI_ALLOW_INSECURE_HTTP", "true")
t.Setenv("EASYDNS_UI_SERVER_1_NAME", "Secondary One")
t.Setenv("EASYDNS_UI_SERVER_1_ROLE", "secondary")
t.Setenv("EASYDNS_UI_SERVER_1_URL", "http://dns-secondary:9953")
t.Setenv("EASYDNS_UI_SERVER_1_TOKEN", "secondary-token-from-env")
c, err := Load()
if err != nil {
t.Fatal(err)
}
if c.Password != "a-strong-admin-password-123" || c.APIToken != "primary-token-from-env" || !c.SessionAuto || !c.MultiServer || !c.MultiServerExplicit || !c.AllowInsecureHTTP {
t.Fatalf("environment not loaded correctly: %#v", c)
}
if len(c.Servers) != 1 || c.Servers[0].Token != "secondary-token-from-env" || c.Servers[0].Role != "secondary" {
t.Fatalf("remote slot not loaded: %#v", c.Servers)
}
}
func TestRejectShortPasswordAndIncompleteRemoteSlot(t *testing.T) {
t.Setenv("EASYDNS_UI_PASSWORD", "too-short")
t.Setenv("EASYDNS_UI_SESSION_AUTO", "true")
if _, err := Load(); err == nil || !strings.Contains(err.Error(), "at least 16") {
t.Fatalf("short password accepted: %v", err)
}
t.Setenv("EASYDNS_UI_PASSWORD", "long-enough-password-123")
t.Setenv("EASYDNS_UI_SERVER_1_NAME", "Secondary One")
t.Setenv("EASYDNS_UI_SERVER_1_URL", "https://dns-secondary.example.net:9953")
t.Setenv("EASYDNS_UI_SERVER_1_TOKEN", "")
if _, err := Load(); err == nil || !strings.Contains(err.Error(), "incomplete server slot") {
t.Fatalf("incomplete server accepted: %v", err)
}
}
+317
View File
@@ -0,0 +1,317 @@
package config
// This is a deliberately small, strict reader for the application's documented
// TOML settings: tables, arrays of server tables, basic/literal strings,
// booleans and integer server slots. Keeping it in the standard library means
// the offline Docker and Debian builds need no downloaded dependencies.
// Unsupported TOML constructs fail explicitly instead of being ignored.
import (
"bufio"
"fmt"
"os"
"strconv"
"strings"
)
// readTOMLConfig mutates only the supplied Config. No secrets are logged or
// included in parser errors. The caller decides whether a missing file is OK.
func readTOMLConfig(c *Config, filename string) error {
f, err := os.Open(filename)
if err != nil {
return err
}
defer f.Close()
scanner := bufio.NewScanner(f)
scanner.Buffer(make([]byte, 4096), 128*1024)
section := ""
serverIndex := -1
seen := make(map[string]bool)
slots := make(map[int]bool)
lineNumber := 0
for scanner.Scan() {
lineNumber++
line, e := stripTOMLComment(scanner.Text())
if e != nil {
return fmt.Errorf("config.toml line %d: %w", lineNumber, e)
}
line = strings.TrimSpace(line)
if line == "" {
continue
}
if strings.HasPrefix(line, "[[") && strings.HasSuffix(line, "]]") {
if strings.TrimSpace(line[2:len(line)-2]) != "servers" {
return fmt.Errorf("config.toml line %d: unsupported array of tables", lineNumber)
}
if len(c.Servers) >= 15 {
return fmt.Errorf("config.toml line %d: at most 15 remote servers are supported", lineNumber)
}
c.Servers = append(c.Servers, ServerSeed{Slot: len(c.Servers) + 1, Role: "secondary"})
serverIndex = len(c.Servers) - 1
section = "servers"
continue
}
if strings.HasPrefix(line, "[") && strings.HasSuffix(line, "]") {
table := strings.TrimSpace(line[1 : len(line)-1])
if table != "panel" && table != "api" && table != "multiserver" {
return fmt.Errorf("config.toml line %d: unsupported table", lineNumber)
}
section = table
serverIndex = -1
continue
}
key, raw, found := strings.Cut(line, "=")
key = strings.TrimSpace(key)
if !found || key == "" || strings.TrimSpace(raw) == "" || section == "" {
return fmt.Errorf("config.toml line %d: expected key = value inside a table", lineNumber)
}
keyID := section + "." + key
if section == "servers" {
keyID = fmt.Sprintf("servers[%d].%s", serverIndex, key)
}
if seen[keyID] {
return fmt.Errorf("config.toml line %d: duplicate key %s", lineNumber, keyID)
}
seen[keyID] = true
value, kind, e := parseTOMLValue(strings.TrimSpace(raw))
if e != nil {
return fmt.Errorf("config.toml line %d (%s): %w", lineNumber, keyID, e)
}
if e = assignTOML(c, section, serverIndex, key, value, kind); e != nil {
return fmt.Errorf("config.toml line %d (%s): %w", lineNumber, keyID, e)
}
}
if err := scanner.Err(); err != nil {
return fmt.Errorf("read config.toml: %w", err)
}
for i := range c.Servers {
slot := c.Servers[i].Slot
if slot < 1 || slot > 15 || slots[slot] {
return fmt.Errorf("config.toml: duplicate or invalid server slot %d", slot)
}
slots[slot] = true
}
return nil
}
// A # inside a quoted token is not a comment. Only # outside quotes is.
func stripTOMLComment(line string) (string, error) {
quote := byte(0)
escaped := false
for i := 0; i < len(line); i++ {
ch := line[i]
if quote == '"' && escaped {
escaped = false
continue
}
if quote == '"' && ch == '\\' {
escaped = true
continue
}
if quote == 0 && (ch == '"' || ch == '\'') {
quote = ch
continue
}
if quote != 0 && ch == quote {
quote = 0
continue
}
if quote == 0 && ch == '#' {
return line[:i], nil
}
}
if quote != 0 || escaped {
return "", fmt.Errorf("unterminated string")
}
return line, nil
}
func parseTOMLValue(raw string) (value, kind string, err error) {
if len(raw) == 0 {
return "", "", fmt.Errorf("empty value")
}
if raw[0] == '"' {
if len(raw) < 2 || raw[len(raw)-1] != '"' {
return "", "", fmt.Errorf("expected quoted string")
}
for i := 1; i < len(raw)-1; i++ {
if raw[i] != '\\' {
continue
}
i++
if i >= len(raw)-1 || !strings.ContainsRune("\\\"bfnrtuU", rune(raw[i])) {
return "", "", fmt.Errorf("unsupported string escape")
}
}
v, e := strconv.Unquote(raw)
if e != nil {
return "", "", fmt.Errorf("invalid quoted string")
}
return v, "string", nil
}
if raw[0] == '\'' {
if len(raw) < 2 || raw[len(raw)-1] != '\'' || strings.Contains(raw[1:len(raw)-1], "'") {
return "", "", fmt.Errorf("invalid literal string")
}
return raw[1 : len(raw)-1], "string", nil
}
if raw == "true" || raw == "false" {
return raw, "bool", nil
}
if _, e := strconv.Atoi(raw); e == nil {
return raw, "integer", nil
}
return "", "", fmt.Errorf("expected string, boolean, or integer")
}
func assignTOML(c *Config, section string, index int, key, value, kind string) error {
require := func(expected string) error {
if kind != expected {
return fmt.Errorf("expected %s value", expected)
}
return nil
}
switch section {
case "panel":
switch key {
case "listen":
if err := require("string"); err != nil {
return err
}
c.Listen = value
case "username":
if err := require("string"); err != nil {
return err
}
c.Username = value
case "password":
if err := require("string"); err != nil {
return err
}
c.Password = value
case "password_file":
if err := require("string"); err != nil {
return err
}
c.PasswordFile = value
case "session_key_file":
if err := require("string"); err != nil {
return err
}
c.SessionKeyFile = value
case "nodes_dir":
if err := require("string"); err != nil {
return err
}
c.NodesDir = value
case "cookie_secure":
if err := require("bool"); err != nil {
return err
}
c.CookieSecure = value == "true"
case "session_auto":
if err := require("bool"); err != nil {
return err
}
c.SessionAuto = value == "true"
default:
return fmt.Errorf("unknown setting")
}
case "api":
switch key {
case "url":
if err := require("string"); err != nil {
return err
}
c.APIURL = value
case "socket":
if err := require("string"); err != nil {
return err
}
c.APISocket = value
case "token":
if err := require("string"); err != nil {
return err
}
c.APIToken = value
case "token_file":
if err := require("string"); err != nil {
return err
}
c.TokenFile = value
case "allow_insecure_http":
if err := require("bool"); err != nil {
return err
}
c.AllowInsecureHTTP = value == "true"
default:
return fmt.Errorf("unknown setting")
}
case "multiserver":
switch key {
case "enabled":
if err := require("bool"); err != nil {
return err
}
c.MultiServer = value == "true"
c.MultiServerExplicit = true
case "local_name":
if err := require("string"); err != nil {
return err
}
c.LocalName = value
case "local_role":
if err := require("string"); err != nil {
return err
}
c.LocalRole = value
c.LocalRoleExplicit = true
default:
return fmt.Errorf("unknown setting")
}
case "servers":
if index < 0 || index >= len(c.Servers) {
return fmt.Errorf("missing [[servers]] table")
}
s := &c.Servers[index]
switch key {
case "slot":
if err := require("integer"); err != nil {
return err
}
n, _ := strconv.Atoi(value)
s.Slot = n
case "name":
if err := require("string"); err != nil {
return err
}
s.Name = value
case "role":
if err := require("string"); err != nil {
return err
}
s.Role = value
case "url":
if err := require("string"); err != nil {
return err
}
s.URL = value
case "token":
if err := require("string"); err != nil {
return err
}
s.Token = value
case "token_file":
if err := require("string"); err != nil {
return err
}
s.TokenFile = value
default:
return fmt.Errorf("unknown setting")
}
default:
return fmt.Errorf("unknown table")
}
return nil
}
+152
View File
@@ -0,0 +1,152 @@
package config
import (
"os"
"path/filepath"
"strings"
"testing"
)
func configForTest(t *testing.T, contents string) string {
t.Helper()
file := filepath.Join(t.TempDir(), "config.toml")
if err := os.WriteFile(file, []byte(contents), 0600); err != nil {
t.Fatal(err)
}
t.Setenv("EASYDNS_UI_CONFIG_FILE", file)
t.Setenv("EASYDNS_UI_SESSION_AUTO", "true")
t.Setenv("EASYDNS_UI_SESSION_KEY_FILE", filepath.Join(t.TempDir(), "session.key"))
return file
}
func TestDebianConfigTOMLLoadsSecretsAndTwoRemotes(t *testing.T) {
configForTest(t, `# Server admin credentials and APIs
[panel]
listen = "127.0.0.1:18448"
username = "operator"
password = "long-secret#pass-word!"
cookie_secure = true
[api]
url = "https://primary.example.net:9953"
token = 'primary#token' # a literal string
[multiserver]
enabled = true
local_name = "Primary DNS"
local_role = "primary"
[[servers]]
slot = 1
name = "Secondary One"
role = "secondary"
url = "https://secondary-1.example.net:9953"
token = "remote#one" # not a comment in token
[[servers]]
slot = 2
name = "Secondary Two"
url = "https://secondary-2.example.net:9953"
token = "remote-two"
`)
c, err := Load()
if err != nil {
t.Fatal(err)
}
if c.Listen != "127.0.0.1:18448" || c.Username != "operator" || c.Password != "long-secret#pass-word!" || c.APIToken != "primary#token" || !c.MultiServer || !c.MultiServerExplicit || !c.LocalRoleExplicit || !c.CookieSecure {
t.Fatal("TOML settings not applied")
}
if len(c.Servers) != 2 || c.Servers[0].Slot != 1 || c.Servers[0].Token != "remote#one" || c.Servers[1].Slot != 2 || c.Servers[1].Role != "secondary" {
t.Fatalf("invalid TOML servers: %#v", c.Servers)
}
}
func TestConfigEnvOverridesTOMLAndServerSlot(t *testing.T) {
configForTest(t, `[panel]
password = "file-password-is-very-long"
username = "operator"
[api]
url = "https://source.example.org:9953"
token = "file-token"
[multiserver]
enabled = true
[[servers]]
slot = 2
name = "File Server"
role = "secondary"
url = "https://file.example.org:9953"
token = "file-remote-token"
`)
t.Setenv("EASYDNS_UI_USERNAME", "env-admin")
t.Setenv("EASYDNS_UI_PASSWORD", "env-password-is-long-and-strong")
t.Setenv("EASYDNS_API_TOKEN", "env-token")
t.Setenv("EASYDNS_UI_MULTISERVER", "false")
t.Setenv("EASYDNS_UI_SERVER_2_NAME", "Env Server")
t.Setenv("EASYDNS_UI_SERVER_2_URL", "https://env.example.org:9953")
t.Setenv("EASYDNS_UI_SERVER_2_TOKEN", "env-remote-token")
c, err := Load()
if err != nil {
t.Fatal(err)
}
if c.Username != "env-admin" || c.Password != "env-password-is-long-and-strong" || c.APIToken != "env-token" || c.MultiServer || !c.MultiServerExplicit {
t.Fatal("environment did not override TOML")
}
if len(c.Servers) != 1 || c.Servers[0].Name != "Env Server" || c.Servers[0].Token != "env-remote-token" {
t.Fatalf("environment slot not replaced: %#v", c.Servers)
}
}
func TestExampleConfigHasValidSyntax(t *testing.T) {
path := "../../packaging/easydns-ui.toml"
c := Config{}
if err := readTOMLConfig(&c, path); err != nil {
t.Fatalf("packaged sample invalid: %v", err)
}
if c.APIURL != "http://127.0.0.1:9953" || c.PasswordFile != "/etc/easydns-ui/panel.password" || c.MultiServer || len(c.Servers) != 0 {
t.Fatal("packaged defaults changed")
}
}
func TestConfigRejectsInvalidOrDuplicateKeysWithoutEchoingSecrets(t *testing.T) {
tests := []string{
`[panel]
password="secret-test-123456789"
passwrod="secret-test-123456789"
`,
`[panel]
password="secret-test-123456789"
password="secret-test-123456789"
`,
`[panel]
password = true
`,
`[panel]
password="secret-test-123456789"
[[servers]]
slot=1
[[servers]]
slot=1
`,
`[panel]
password="secret-test-123456789"
foo = [1,2]
`,
`[panel]
password="secret-test-123456789"
` + "[wrong]\nvalue = true\n",
}
for i, test := range tests {
p := filepath.Join(t.TempDir(), "config.toml")
if err := os.WriteFile(p, []byte(test), 0600); err != nil {
t.Fatal(err)
}
var c Config
err := readTOMLConfig(&c, p)
if err == nil || strings.Contains(err.Error(), "secret-test-123456789") {
t.Fatalf("case %d error=%v", i, err)
}
}
}
func TestConfigExplicitMissingFileReturnsError(t *testing.T) {
t.Setenv("EASYDNS_UI_CONFIG_FILE", filepath.Join(t.TempDir(), "missing.toml"))
if _, err := Load(); err == nil || !strings.Contains(err.Error(), "missing.toml") {
t.Fatal(err)
}
}
+15 -5
View File
@@ -20,11 +20,18 @@ const maxResponse = 16 << 20
type Client struct {
base string
tokenFile string
token string
useSocket bool
http *http.Client
}
func New(base, tokenFile, socket string) (*Client, error) {
return NewWithToken(base, tokenFile, socket, "")
}
// NewWithToken permits an explicitly configured in-memory token (e.g. from
// Compose .env) without writing the secret into the container filesystem.
func NewWithToken(base, tokenFile, socket, token string) (*Client, error) {
tr := &http.Transport{MaxIdleConnsPerHost: 8, IdleConnTimeout: 30 * time.Second, ResponseHeaderTimeout: 30 * time.Second}
if socket != "" {
tr.DialContext = func(ctx context.Context, _, _ string) (net.Conn, error) {
@@ -38,7 +45,7 @@ func New(base, tokenFile, socket string) (*Client, error) {
}
base = strings.TrimSuffix(base, "/")
}
return &Client{base: base, tokenFile: tokenFile, useSocket: socket != "", http: &http.Client{Transport: tr, Timeout: 65 * time.Second, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}}, nil
return &Client{base: base, tokenFile: tokenFile, token: token, useSocket: socket != "", http: &http.Client{Transport: tr, Timeout: 65 * time.Second, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}}, nil
}
type Error struct {
@@ -78,11 +85,14 @@ func (c *Client) Do(ctx context.Context, method, path string, body any, etag str
req.Header.Set("If-Match", etag)
}
if !c.useSocket && path != "/readyz" && path != "/healthz" && path != "/api/v1/health" {
secret, e := os.ReadFile(c.tokenFile)
if e != nil {
return "", &Error{Message: "Unable to read EasyDNS generated control token; check token file permissions or configure the Unix socket"}
token := c.token
if token == "" {
secret, e := os.ReadFile(c.tokenFile)
if e != nil {
return "", &Error{Message: "Unable to read EasyDNS generated control token; check token file permissions, EASYDNS_API_TOKEN, or configure the Unix socket"}
}
token = strings.TrimSpace(string(secret))
}
token := strings.TrimSpace(string(secret))
if token == "" {
return "", &Error{Message: "EasyDNS control token file is empty"}
}
+80
View File
@@ -0,0 +1,80 @@
package multiserver
import (
"context"
"git.linuxiarz.pl/gru/EasyDNS-Web/internal/config"
"io"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"testing"
)
func TestEnvironmentTokensInMemoryAndRestoreAfterToggle(t *testing.T) {
dir := t.TempDir()
var remoteToken string
remote := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
remoteToken = r.Header.Get("Authorization")
_, _ = io.WriteString(w, `{"zones":[]}`)
}))
defer remote.Close()
reg, err := NewConfigured(true, true, false, dir, "http://127.0.0.1:9953", "", "", "local-token")
if err != nil {
t.Fatal(err)
}
seeds := []config.ServerSeed{{Slot: 1, Name: "DNS Secondary", Role: RoleSecondary, URL: remote.URL, Token: "remote-env-token"}}
if err = reg.ApplyEnvironment("DNS Primary", RolePrimary, seeds); err != nil {
t.Fatal(err)
}
if got := reg.All(); len(got) != 2 || !got[1].Managed {
t.Fatalf("configured nodes=%v", got)
}
nodes, err := os.ReadFile(filepath.Join(dir, "nodes.json"))
if err != nil {
t.Fatal(err)
}
if strings.Contains(string(nodes), "remote-env-token") || strings.Contains(string(nodes), "DNS Secondary") {
t.Fatalf("env-defined node or secret persisted: %s", nodes)
}
files, _ := filepath.Glob(filepath.Join(dir, "tokens", "*.token"))
if len(files) != 0 {
t.Fatalf("environment tokens persisted: %v", files)
}
node, client, _, found := reg.Get(reg.All()[1].ID)
if !found || !node.Managed {
t.Fatal("remote env node unavailable")
}
_, err = client.Get(context.Background(), "/api/v1/zones", nil)
if err != nil {
t.Fatal(err)
}
if remoteToken != "Bearer remote-env-token" {
t.Fatalf("unexpected Authorization header %q", remoteToken)
}
if err = reg.SetEnabled(false); err != nil {
t.Fatal(err)
}
if err = reg.SetEnabled(true); err != nil {
t.Fatal(err)
}
if len(reg.All()) != 2 {
t.Fatalf("environment nodes lost on toggle: %v", reg.All())
}
if err = reg.Remove(reg.All()[1].ID); err == nil {
t.Fatal("environment-managed server was removable from the UI")
}
}
func TestTrustedHTTPRequiresExplicitOptIn(t *testing.T) {
if _, err := ValidateURL("http://dns-primary:9953"); err == nil {
t.Fatal("non-loopback HTTP accepted without opt-in")
}
if _, err := ValidateURLWithHTTP("http://dns-primary:9953", true); err != nil {
t.Fatal(err)
}
if _, err := ValidateURL("https://dns-primary.example.net:9953"); err != nil {
t.Fatal(err)
}
}
+797
View File
@@ -0,0 +1,797 @@
// Package multiserver manages optional connections to independent EasyDNS instances.
// It never creates or changes server-side DNS cluster configuration.
package multiserver
import (
"context"
"crypto/rand"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"net"
"net/url"
"os"
"path/filepath"
"strings"
"sync"
"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"
)
const maxRemote = 15
// Role is a user-assigned UI topology label, NOT a DNS configuration setting.
const (
RolePrimary = "primary"
RoleSecondary = "secondary"
RoleUnassigned = "unassigned"
)
type Node struct {
ID string `json:"id"`
Name string `json:"name"`
Role string `json:"role"`
URL string `json:"url"`
Local bool `json:"local,omitempty"`
Managed bool `json:"managed_by_environment,omitempty"`
}
type runtime struct {
node Node
api *easydns.Client
history *telemetry.History
cancel context.CancelFunc
}
type persisted struct {
LocalRole string `json:"local_role"`
Remote []Node `json:"remote"`
}
// panelSettings contains panel-only preferences. It does not affect DNS.
// A setting saved in the web UI overrides the optional environment bootstrap.
type panelSettings struct {
Enabled bool `json:"multi_server_enabled"`
}
type Registry struct {
mu sync.RWMutex
enabled bool
store string
settings string
tokenDir string
local *runtime
remote []*runtime
managed []*runtime // Environment-provided tokens are kept in memory only.
allowInsecureHTTP bool
envLocalRole string
started bool
runCtx context.Context
}
func ValidateURL(value string) (string, error) { return ValidateURLWithHTTP(value, false) }
// Insecure HTTP requires an explicit operator opt-in (isolated Docker/LAN only).
func ValidateURLWithHTTP(value string, allowInsecure bool) (string, error) {
raw := strings.TrimSpace(value)
u, err := url.Parse(raw)
if err != nil || u == nil || u.Host == "" || u.User != nil || u.RawQuery != "" || u.Fragment != "" || u.Path != "" || u.Opaque != "" {
return "", errors.New("enter a base URL without path, query, credentials, or fragment")
}
if u.Scheme != "https" && u.Scheme != "http" {
return "", errors.New("only HTTPS and loopback HTTP are supported")
}
if u.Scheme == "http" {
host := strings.Trim(u.Hostname(), "[]")
ip := net.ParseIP(host)
if !allowInsecure && host != "localhost" && (ip == nil || !ip.IsLoopback()) {
return "", errors.New("remote node URLs require HTTPS with a trusted certificate; HTTP is allowed only on loopback")
}
}
if u.Port() != "" {
if len(u.Port()) > 5 {
return "", errors.New("invalid port")
}
}
return strings.TrimSuffix(raw, "/"), nil
}
func validateRole(role string) bool {
return role == RolePrimary || role == RoleSecondary || role == RoleUnassigned
}
func ValidateName(name string) error {
if len(name) < 2 || len(name) > 64 || strings.TrimSpace(name) != name || strings.ContainsAny(name, "\r\n\x00") {
return errors.New("node name must be 2–64 characters without leading/trailing whitespace")
}
return nil
}
func ValidateToken(t string) error {
if len(t) == 0 || len(t) > 4096 || strings.ContainsAny(t, "\x00\r\n") || strings.TrimSpace(t) != t {
return errors.New("provide a valid EasyDNS control token (up to 4096 characters, no whitespace at the ends)")
}
return nil
}
func New(enabled bool, stateDir string, localURL, localTokenFile, localSocket string) (*Registry, error) {
return NewWithToken(enabled, stateDir, localURL, localTokenFile, localSocket, "")
}
func NewWithToken(enabled bool, stateDir string, localURL, localTokenFile, localSocket, localToken string) (*Registry, error) {
return NewConfigured(enabled, false, false, stateDir, localURL, localTokenFile, localSocket, localToken)
}
// NewConfigured optionally makes the explicit environment flag authoritative.
func NewConfigured(enabled, environmentOverride, allowInsecureHTTP bool, stateDir, localURL, localTokenFile, localSocket, localToken string) (*Registry, error) {
client, err := easydns.NewWithToken(localURL, localTokenFile, localSocket, localToken)
if err != nil {
return nil, err
}
local := &runtime{node: Node{ID: "local", Name: "Local EasyDNS", Role: RolePrimary, URL: localURL, Local: true}, api: client, history: telemetry.New()}
reg := &Registry{enabled: enabled, store: filepath.Join(stateDir, "nodes.json"), settings: filepath.Join(stateDir, "settings.json"), tokenDir: filepath.Join(stateDir, "tokens"), local: local, allowInsecureHTTP: allowInsecureHTTP, envLocalRole: RolePrimary}
// A mode explicitly configured in TOML or environment takes precedence over
// old UI preferences, including a stale or damaged settings.json. UI
// preferences are consulted only when neither configuration source sets it.
if !environmentOverride {
settingsRaw, err := os.ReadFile(reg.settings)
if err == nil {
var pref panelSettings
if err := json.Unmarshal(settingsRaw, &pref); err != nil {
return nil, fmt.Errorf("decode panel preferences: %w", err)
}
reg.enabled = pref.Enabled
} else if !errors.Is(err, os.ErrNotExist) {
return nil, fmt.Errorf("read panel preferences: %w", err)
}
}
// Leave the default single-server panel independent of optional fleet data.
// An invalid saved node list must not block an explicitly disabled feature.
if reg.enabled {
localRole, remote, err := reg.loadNodes()
if err != nil {
return nil, err
}
reg.local.node.Role = localRole
reg.remote = remote
}
return reg, nil
}
// loadNodes validates stored metadata without mutating the active registry.
// Caller holds the write lock when loading at runtime.
func (r *Registry) loadNodes() (string, []*runtime, error) {
localRole := RolePrimary
raw, err := os.ReadFile(r.store)
if errors.Is(err, os.ErrNotExist) {
return localRole, nil, nil
}
if err != nil {
return "", nil, fmt.Errorf("read server registry: %w", err)
}
var saved persisted
if err := json.Unmarshal(raw, &saved); err != nil {
return "", nil, fmt.Errorf("decode server registry: %w", err)
}
if saved.LocalRole != "" {
if !validateRole(saved.LocalRole) {
return "", nil, errors.New("invalid local node role in registry")
}
localRole = saved.LocalRole
}
if len(saved.Remote) > maxRemote {
return "", nil, errors.New("node registry exceeds maximum servers")
}
primaryCount := 0
if localRole == RolePrimary {
primaryCount++
}
ids := map[string]bool{"local": true}
names := map[string]bool{strings.ToLower(r.local.node.Name): true}
remote := make([]*runtime, 0, len(saved.Remote))
for _, n := range saved.Remote {
// Migrate old builds: environment-managed entries are rebuilt from .env.
if n.Managed {
continue
}
if ids[n.ID] || !validNodeID(n.ID) || !validateRole(n.Role) || ValidateName(n.Name) != nil || names[strings.ToLower(n.Name)] {
return "", nil, errors.New("invalid or duplicate node entry in registry")
}
ids[n.ID] = true
names[strings.ToLower(n.Name)] = true
if n.Role == RolePrimary {
primaryCount++
}
u, e := ValidateURLWithHTTP(n.URL, r.allowInsecureHTTP)
if e != nil {
return "", nil, fmt.Errorf("invalid configured URL for %s: %w", n.ID, e)
}
n.URL = u
n.Local = false
api, e := easydns.New(n.URL, filepath.Join(r.tokenDir, n.ID+".token"), "")
if e != nil {
return "", nil, e
}
remote = append(remote, &runtime{node: n, api: api, history: telemetry.New()})
}
if primaryCount > 1 {
return "", nil, errors.New("only one node may have the Primary topology label")
}
return localRole, remote, nil
}
func validNodeID(s string) bool {
if len(s) != 24 {
return false
}
_, e := hex.DecodeString(s)
return e == nil
}
// ApplyEnvironment configures the optional remote nodes declared in .env.
// Slots are stable identifiers across restarts: editing a URL or token updates
// the existing node instead of adding another. UI-managed nodes are preserved;
// removing an environment slot removes only its environment-managed node.
// No EasyDNS configuration is modified.
func (r *Registry) ApplyEnvironment(localName, localRole string, seeds []config.ServerSeed) error {
r.mu.Lock()
defer r.mu.Unlock()
if r.started {
return errors.New("environment configuration can be applied only at startup")
}
if err := ValidateName(localName); err != nil {
return fmt.Errorf("local server name: %w", err)
}
if !validateRole(localRole) {
return errors.New("invalid local server topology label")
}
// Load saved nodes even while single-server mode is disabled only when
// environment-managed slots exist. A broken optional fleet file must not
// prevent the default local-only service from starting.
r.local.node.Name = localName
r.local.node.Role = localRole
r.envLocalRole = localRole
if len(seeds) == 0 && !r.enabled {
return nil
}
savedRole, existing, err := r.loadNodes()
if err != nil {
return err
}
_ = savedRole
existingByID := make(map[string]*runtime, len(existing))
for _, n := range existing {
existingByID[n.node.ID] = n
}
next := make([]*runtime, 0, len(existing)+len(seeds))
for _, n := range existing {
if !n.node.Managed {
next = append(next, n)
}
}
// Validate all remote entries before writing tokens or changing registry.
type candidate struct {
node Node
token string
}
var configured []candidate
seen := map[string]bool{strings.ToLower(localName): true}
primaryCount := 0
if localRole == RolePrimary {
primaryCount++
}
for _, n := range next {
if seen[strings.ToLower(n.node.Name)] {
return errors.New("duplicate name between local and saved remote server")
}
seen[strings.ToLower(n.node.Name)] = true
if n.node.Role == RolePrimary {
primaryCount++
}
}
for _, seed := range seeds {
if seed.Slot < 1 || seed.Slot > maxRemote {
return errors.New("environment server slot out of range")
}
if err := ValidateName(seed.Name); err != nil {
return fmt.Errorf("server slot %d name: %w", seed.Slot, err)
}
if !validateRole(seed.Role) {
return fmt.Errorf("server slot %d: invalid topology label", seed.Slot)
}
u, err := ValidateURLWithHTTP(seed.URL, r.allowInsecureHTTP)
if err != nil {
return fmt.Errorf("server slot %d URL: %w", seed.Slot, err)
}
secret := seed.Token
if seed.TokenFile != "" {
bytes, e := os.ReadFile(seed.TokenFile)
if e != nil {
return fmt.Errorf("server slot %d: cannot read token file: %w", seed.Slot, e)
}
secret = strings.TrimSpace(string(bytes))
}
if err := ValidateToken(secret); err != nil {
return fmt.Errorf("server slot %d token: %w", seed.Slot, err)
}
if seen[strings.ToLower(seed.Name)] {
return fmt.Errorf("server slot %d: duplicate node name", seed.Slot)
}
seen[strings.ToLower(seed.Name)] = true
if seed.Role == RolePrimary {
primaryCount++
}
hash := sha256.Sum256([]byte(fmt.Sprintf("EasyDNS-Web/env-slot/%d", seed.Slot)))
id := hex.EncodeToString(hash[:12])
if old, ok := existingByID[id]; ok && !old.node.Managed {
return fmt.Errorf("server slot %d: reserved ID collision", seed.Slot)
}
configured = append(configured, candidate{node: Node{ID: id, Name: seed.Name, Role: seed.Role, URL: u, Managed: true}, token: secret})
}
if primaryCount > 1 {
return errors.New("only one server may have the Primary topology label")
}
if len(next)+len(configured) > maxRemote {
return errors.New("too many remote servers (maximum 15)")
}
var managed []*runtime
for _, c := range configured {
// .env secrets are used directly; do not copy them to the state volume.
api, err := easydns.NewWithToken(c.node.URL, "", "", c.token)
if err != nil {
return err
}
old := existingByID[c.node.ID]
history := telemetry.New()
if old != nil && old.node.URL == c.node.URL {
history = old.history
}
node := &runtime{node: c.node, api: api, history: history}
next = append(next, node)
managed = append(managed, node)
}
if err := r.saveLocked(localRole, next); err != nil {
return fmt.Errorf("save server registry: %w", err)
}
// Remove files left by older releases; configured env tokens now remain
// in memory, even when a new token is set for the same numbered slot.
for _, c := range configured {
_ = os.Remove(filepath.Join(r.tokenDir, c.node.ID+".token"))
}
for _, n := range existing {
if !n.node.Managed {
continue
}
stillConfigured := false
for _, c := range configured {
if c.node.ID == n.node.ID {
stillConfigured = true
break
}
}
if !stillConfigured {
_ = os.Remove(filepath.Join(r.tokenDir, n.node.ID+".token"))
}
}
r.local.node.Name = localName
r.local.node.Role = localRole
r.managed = managed
if r.enabled {
r.remote = next
}
return nil
}
func (r *Registry) Enabled() bool {
r.mu.RLock()
defer r.mu.RUnlock()
return r.enabled
}
// SetEnabled switches the optional fleet UI on or off immediately. Remote
// definitions and per-server bearer tokens are retained when disabled.
func (r *Registry) SetEnabled(enabled bool) error {
r.mu.Lock()
defer r.mu.Unlock()
var remote []*runtime
if enabled && !r.enabled {
var err error
_, remote, err = r.loadNodes()
if err != nil {
return err
}
}
data, err := json.MarshalIndent(panelSettings{Enabled: enabled}, "", " ")
if err != nil {
return err
}
if err = writePrivateFile(r.settings, append(data, '\n')); err != nil {
return fmt.Errorf("save multi-server preference: %w", err)
}
if r.enabled == enabled {
return nil
}
r.enabled = enabled
if enabled {
r.local.node.Role = r.envLocalRole
r.remote = append(remote, r.managed...)
}
for _, n := range r.remote {
if enabled {
r.startNodeLocked(n)
} else if n.cancel != nil {
n.cancel()
n.cancel = nil
}
}
return nil
}
func (r *Registry) All() []Node {
r.mu.RLock()
defer r.mu.RUnlock()
res := []Node{r.local.node}
for _, n := range r.remote {
res = append(res, n.node)
}
return res
}
func (r *Registry) client(id string) *runtime {
if id == "local" || id == "" {
return r.local
}
for _, v := range r.remote {
if v.node.ID == id {
return v
}
}
return nil
}
func (r *Registry) Get(id string) (Node, *easydns.Client, *telemetry.History, bool) {
r.mu.RLock()
defer r.mu.RUnlock()
n := r.client(id)
if n == nil {
return Node{}, nil, nil, false
}
return n.node, n.api, n.history, true
}
func (r *Registry) Default() (Node, *easydns.Client, *telemetry.History) {
r.mu.RLock()
defer r.mu.RUnlock()
return r.local.node, r.local.api, r.local.history
}
func (r *Registry) saveLocked(localRole string, remote []*runtime) error {
saved := persisted{LocalRole: localRole}
for _, n := range remote {
if n.node.Managed {
continue
}
saved.Remote = append(saved.Remote, n.node)
}
data, e := json.MarshalIndent(saved, "", " ")
if e != nil {
return e
}
return writePrivateFile(r.store, append(data, '\n'))
}
func writePrivateFile(path string, data []byte) error {
dir := filepath.Dir(path)
if e := os.MkdirAll(dir, 0700); e != nil {
return e
}
f, e := os.CreateTemp(dir, ".nodes-*")
if e != nil {
return e
}
name := f.Name()
defer os.Remove(name)
if e = f.Chmod(0600); e != nil {
f.Close()
return e
}
if _, e = f.Write(data); e != nil {
f.Close()
return e
}
if e = f.Sync(); e != nil {
f.Close()
return e
}
if e = f.Close(); e != nil {
return e
}
return os.Rename(name, path)
}
func (r *Registry) Add(name, role, baseURL, secret string) (Node, error) {
if !r.Enabled() {
return Node{}, errors.New("multi-server mode is disabled")
}
if err := ValidateName(name); err != nil {
return Node{}, err
}
if !validateRole(role) {
return Node{}, errors.New("invalid topology label")
}
baseURL, err := ValidateURLWithHTTP(baseURL, r.allowInsecureHTTP)
if err != nil {
return Node{}, err
}
if err = ValidateToken(secret); err != nil {
return Node{}, err
}
r.mu.Lock()
defer r.mu.Unlock()
if !r.enabled {
return Node{}, errors.New("multi-server mode is disabled")
}
if len(r.remote) >= maxRemote {
return Node{}, errors.New("maximum remote server count reached")
}
if role == RolePrimary && r.hasPrimaryLocked("") {
return Node{}, errors.New("a Primary node already exists; change its label before adding another")
}
if strings.EqualFold(r.local.node.Name, name) {
return Node{}, errors.New("node name already exists")
}
for _, v := range r.remote {
if strings.EqualFold(v.node.Name, name) {
return Node{}, errors.New("node name already exists")
}
}
raw := make([]byte, 12)
if _, err = rand.Read(raw); err != nil {
return Node{}, err
}
n := Node{ID: hex.EncodeToString(raw), Name: name, Role: role, URL: baseURL}
api, err := easydns.New(n.URL, filepath.Join(r.tokenDir, n.ID+".token"), "")
if err != nil {
return Node{}, err
}
if err = os.MkdirAll(r.tokenDir, 0700); err != nil {
return Node{}, err
}
secretPath := filepath.Join(r.tokenDir, n.ID+".token")
// A secret is written only by the panel service account, never to HTML or logs.
f, err := os.OpenFile(secretPath, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0600)
if err != nil {
return Node{}, err
}
if _, err = f.WriteString(secret + "\n"); err != nil {
f.Close()
os.Remove(secretPath)
return Node{}, err
}
if err = f.Close(); err != nil {
os.Remove(secretPath)
return Node{}, err
}
nr := &runtime{node: n, api: api, history: telemetry.New()}
newer := append(append([]*runtime{}, r.remote...), nr)
if err = r.saveLocked(r.local.node.Role, newer); err != nil {
os.Remove(secretPath)
return Node{}, err
}
r.remote = newer
if r.started {
r.startNodeLocked(nr)
}
return n, nil
}
func (r *Registry) hasPrimaryLocked(except string) bool {
if r.local.node.ID != except && r.local.node.Role == RolePrimary {
return true
}
for _, v := range r.remote {
if v.node.ID != except && v.node.Role == RolePrimary {
return true
}
}
return false
}
func (r *Registry) SetRole(id, role string) error {
if !validateRole(role) {
return errors.New("invalid topology label")
}
r.mu.Lock()
defer r.mu.Unlock()
if !r.enabled {
return errors.New("multi-server mode is disabled")
}
n := r.client(id)
if n == nil {
return errors.New("server not found")
}
if n.node.Managed {
return errors.New("this server is managed by environment variables; change .env and restart the panel")
}
if role == RolePrimary && r.hasPrimaryLocked(id) {
return errors.New("a Primary node already exists; change that node to Unassigned first")
}
old := n.node.Role
n.node.Role = role
if err := r.saveLocked(r.local.node.Role, r.remote); err != nil {
n.node.Role = old
return err
}
return nil
}
func (r *Registry) Remove(id string) error {
if id == "local" {
return errors.New("the local EasyDNS server cannot be removed")
}
r.mu.Lock()
defer r.mu.Unlock()
if !r.enabled {
return errors.New("multi-server mode is disabled")
}
newer := make([]*runtime, 0, len(r.remote))
var removed *runtime
for _, n := range r.remote {
if n.node.ID == id {
removed = n
} else {
newer = append(newer, n)
}
}
if removed == nil {
return errors.New("server not found")
}
if removed.node.Managed {
return errors.New("this server is managed by environment variables; change .env and restart the panel")
}
if err := r.saveLocked(r.local.node.Role, newer); err != nil {
return err
}
r.remote = newer
if removed.cancel != nil {
removed.cancel()
}
// Remove the secret only after the registry no longer references it.
if err := os.Remove(filepath.Join(r.tokenDir, id+".token")); err != nil && !errors.Is(err, os.ErrNotExist) {
return fmt.Errorf("node removed but token file cleanup failed: %w", err)
}
return nil
}
func (r *Registry) startNodeLocked(n *runtime) {
if !r.started || r.runCtx == nil {
return
}
ctx, cancel := context.WithCancel(r.runCtx)
n.cancel = cancel
go n.history.Run(ctx, n.api)
}
func (r *Registry) Run(ctx context.Context) {
r.mu.Lock()
r.started = true
r.runCtx = ctx
r.startNodeLocked(r.local)
if r.enabled {
for _, n := range r.remote {
r.startNodeLocked(n)
}
}
r.mu.Unlock()
<-ctx.Done()
r.mu.Lock()
r.started = false
r.runCtx = nil
r.mu.Unlock()
}
type Probe struct {
Node Node
Health easydns.Health
Status easydns.Status
State string // healthy, degraded, offline
Error string
CheckedAt time.Time
}
func (r *Registry) ProbeAll(ctx context.Context) []Probe {
ids := r.All()
result := make([]Probe, len(ids))
var wg sync.WaitGroup
for i, node := range ids {
wg.Add(1)
go func(i int, n Node) {
defer wg.Done()
p := Probe{Node: n, State: "offline", CheckedAt: time.Now()}
_, api, _, ok := r.Get(n.ID)
if !ok {
p.Error = "Server removed"
result[i] = p
return
}
localCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
defer cancel()
_, hErr := api.Get(localCtx, "/api/v1/health", &p.Health)
_, sErr := api.Get(localCtx, "/api/v1/status", &p.Status)
if hErr != nil || sErr != nil {
if sErr != nil {
p.Error = sErr.Error()
} else {
p.Error = hErr.Error()
}
} else if strings.EqualFold(p.Health.Status, "ok") {
p.State = "healthy"
} else {
p.State = "degraded"
}
result[i] = p
}(i, node)
}
wg.Wait()
return result
}
type Comparison struct {
Node Node
Zone easydns.Zone
Present bool
Error string
Serial string
MatchesPrimary bool
}
func ValidateZone(zone string) error {
if len(zone) < 1 || len(zone) > 253 || strings.Trim(zone, ". ") == "" {
return errors.New("enter a valid zone name")
}
for _, ch := range zone {
if !(ch >= 'a' && ch <= 'z' || ch >= 'A' && ch <= 'Z' || ch >= '0' && ch <= '9' || ch == '.' || ch == '-' || ch == '_') {
return errors.New("invalid characters in zone name")
}
}
return nil
}
func (r *Registry) Compare(ctx context.Context, zone string) ([]Comparison, error) {
if err := ValidateZone(zone); err != nil {
return nil, err
}
ns := r.All()
result := make([]Comparison, len(ns))
var wg sync.WaitGroup
for i, n := range ns {
wg.Add(1)
go func(i int, n Node) {
defer wg.Done()
v := Comparison{Node: n, Serial: "—"}
_, api, _, ok := r.Get(n.ID)
if !ok {
v.Error = "Server removed"
result[i] = v
return
}
localCtx, cancel := context.WithTimeout(ctx, 7*time.Second)
defer cancel()
_, err := api.Get(localCtx, "/api/v1/zones/"+easydns.Escape(zone), &v.Zone)
if err != nil {
var ae *easydns.Error
if errors.As(err, &ae) && ae.Status == 404 {
v.Error = "Zone not found"
} else {
v.Error = err.Error()
}
} else {
v.Present = true
v.Serial = v.Zone.SerialText()
}
result[i] = v
}(i, n)
}
wg.Wait()
primarySerial := ""
for _, c := range result {
if c.Node.Role == RolePrimary && c.Present && c.Zone.Serial != nil {
primarySerial = c.Serial
break
}
}
if primarySerial != "" {
for i := range result {
result[i].MatchesPrimary = result[i].Present && result[i].Serial == primarySerial
}
}
return result, nil
}
+168
View File
@@ -0,0 +1,168 @@
package multiserver
import (
"context"
"fmt"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"testing"
)
func fakeEasyDNS(t *testing.T, secret string, serial uint32) *httptest.Server {
t.Helper()
return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/api/v1/health" && r.Header.Get("Authorization") != "Bearer "+secret {
http.Error(w, `{"error":{"status":401,"message":"unauthorized"}}`, http.StatusUnauthorized)
return
}
w.Header().Set("Content-Type", "application/json")
switch r.URL.Path {
case "/api/v1/health":
fmt.Fprint(w, `{"status":"ok","expired_zones":[]}`)
case "/api/v1/status":
fmt.Fprint(w, `{"version":"0.1.4","mode":"hybrid","roles":{"primary":1,"secondary":2},"uptime_seconds":10}`)
case "/api/v1/zones/example.com.":
fmt.Fprintf(w, `{"name":"example.com.","kind":"primary","serial":%d,"loaded":true,"records":2}`, serial)
default:
http.NotFound(w, r)
}
}))
}
func TestOptionalRegistryAndPersistence(t *testing.T) {
local := fakeEasyDNS(t, "local-secret", 25)
remote := fakeEasyDNS(t, "remote-secret", 24)
defer local.Close()
defer remote.Close()
dir := t.TempDir()
tokenPath := filepath.Join(dir, "control.token")
if err := os.WriteFile(tokenPath, []byte("local-secret\n"), 0600); err != nil {
t.Fatal(err)
}
reg, err := New(false, dir, local.URL, tokenPath, "")
if err != nil {
t.Fatal(err)
}
if reg.Enabled() {
t.Fatal("default must be single-server")
}
if _, err := reg.Add("node-two", RoleSecondary, remote.URL, "remote-secret"); err == nil {
t.Fatal("add permitted while disabled")
}
if err := reg.SetEnabled(true); err != nil {
t.Fatal(err)
}
if !reg.Enabled() {
t.Fatal("setting did not enable fleet")
}
node, err := reg.Add("node-two", RoleSecondary, remote.URL, "remote-secret")
if err != nil {
t.Fatal(err)
}
if node.Local || node.ID == "local" {
t.Fatal("invalid remote node")
}
probes := reg.ProbeAll(context.Background())
if len(probes) != 2 || probes[0].State != "healthy" || probes[1].State != "healthy" {
t.Fatalf("unexpected probes: %+v", probes)
}
compared, err := reg.Compare(context.Background(), "example.com.")
if err != nil {
t.Fatal(err)
}
if len(compared) != 2 || !compared[0].MatchesPrimary || compared[1].MatchesPrimary || compared[1].Serial != "24" {
t.Fatalf("unexpected zone comparison: %+v", compared)
}
if err := reg.SetRole(node.ID, RolePrimary); err == nil {
t.Fatal("multiple Primary labels allowed")
}
if err := reg.SetEnabled(false); err != nil {
t.Fatal(err)
}
if reg.Enabled() {
t.Fatal("setting not disabled")
}
if _, err := os.Stat(filepath.Join(dir, "tokens", node.ID+".token")); err != nil {
t.Fatalf("disabled mode should retain tokens: %v", err)
}
// Explicit saved UI setting overrides the environment's bootstrap default.
reloaded, err := New(true, dir, local.URL, tokenPath, "")
if err != nil {
t.Fatal(err)
}
if reloaded.Enabled() || len(reloaded.All()) != 1 {
t.Fatalf("disabled mode should not load remote nodes: enabled=%v, nodes=%v", reloaded.Enabled(), reloaded.All())
}
if err := reloaded.SetEnabled(true); err != nil {
t.Fatal(err)
}
if len(reloaded.All()) != 2 {
t.Fatalf("connections were not restored on re-enable: %+v", reloaded.All())
}
if err := reloaded.SetRole("local", RoleUnassigned); err != nil {
t.Fatal(err)
}
if err := reloaded.SetRole(node.ID, RolePrimary); err != nil {
t.Fatal(err)
}
if err := reloaded.Remove("local"); err == nil {
t.Fatal("local node removal allowed")
}
if err := reloaded.Remove(node.ID); err != nil {
t.Fatal(err)
}
if _, err := os.Stat(filepath.Join(dir, "tokens", node.ID+".token")); !os.IsNotExist(err) {
t.Fatalf("remote token retained after removing connection: %v", err)
}
}
func TestRemoteURLValidation(t *testing.T) {
rejected := []string{"http://192.0.2.8:9953", "https://user:pass@dns.example:9953", "https://dns.example/path", "file:///etc/passwd", "http://dns.example", "https://dns.example?secret=1"}
for _, value := range rejected {
if _, err := ValidateURL(value); err == nil {
t.Fatalf("unsafe URL accepted: %s", value)
}
}
for _, value := range []string{"http://127.0.0.1:9953", "http://[::1]:9953", "https://dns.example:9953"} {
if _, err := ValidateURL(value); err != nil {
t.Fatalf("valid URL rejected: %s: %v", value, err)
}
}
if ValidateToken("token\r\n") == nil || ValidateToken("") == nil || ValidateName(" bad ") == nil || ValidateZone("foo/bar") == nil {
t.Fatal("invalid values accepted")
}
if _, err := ValidateURL("https://" + strings.Repeat("a", 255) + ":9953"); err == nil {
// There is no DNS lookup here; a syntactically long hostname may still parse.
t.Log("long hostname URL validation is syntax-only")
}
}
// A damaged optional nodes.json must not prevent default single-server startup.
func TestDisabledModeIgnoresInvalidOptionalRegistry(t *testing.T) {
local := fakeEasyDNS(t, "local-secret", 25)
defer local.Close()
dir := t.TempDir()
path := filepath.Join(dir, "control.token")
if err := os.WriteFile(path, []byte("local-secret\n"), 0600); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(dir, "nodes.json"), []byte("not json"), 0600); err != nil {
t.Fatal(err)
}
reg, err := New(false, dir, local.URL, path, "")
if err != nil {
t.Fatalf("disabled panel was blocked by optional fleet registry: %v", err)
}
if len(reg.All()) != 1 {
t.Fatalf("wanted local-only mode, got: %+v", reg.All())
}
if err := reg.SetEnabled(true); err == nil {
t.Fatal("invalid registry unexpectedly enabled")
}
if reg.Enabled() {
t.Fatal("enable failure must preserve disabled setting")
}
}
+48 -5
View File
@@ -12,6 +12,7 @@ import (
"net/http"
"net/url"
"os"
"path/filepath"
"strings"
"sync"
"time"
@@ -32,14 +33,22 @@ type auth struct {
}
func newAuth(cfg config.Config) (*auth, error) {
p, err := os.ReadFile(cfg.PasswordFile)
if err != nil {
return nil, err
secret := cfg.Password
if secret == "" {
p, err := os.ReadFile(cfg.PasswordFile)
if err != nil {
return nil, err
}
secret = strings.TrimSpace(string(p))
}
secret := strings.TrimSpace(string(p))
if len(secret) < 16 {
return nil, errors.New("panel password must have at least 16 characters")
}
if cfg.SessionAuto {
if err := ensureSessionKey(cfg.SessionKeyFile); err != nil {
return nil, err
}
}
k, err := os.ReadFile(cfg.SessionKeyFile)
if err != nil {
return nil, err
@@ -51,7 +60,41 @@ func newAuth(cfg config.Config) (*auth, error) {
if len(k) < 32 {
return nil, errors.New("session key must contain at least 32 bytes")
}
return &auth{key: k, password: []byte(secret), username: cfg.Username, secure: cfg.CookieSecure, fail: make(map[string][]time.Time)}, nil
// Derive the signing key from the persisted session secret and current
// login credentials. Password/username changes invalidate old sessions.
mac := hmac.New(sha256.New, k)
mac.Write([]byte("easydns-ui-session-v1:" + cfg.Username + ":" + secret))
return &auth{key: mac.Sum(nil), password: []byte(secret), username: cfg.Username, secure: cfg.CookieSecure, fail: make(map[string][]time.Time)}, nil
}
// Creates the session secret only when explicitly enabled (Docker mode).
// The same secret is reused across container recreations through a volume.
func ensureSessionKey(path string) error {
if _, err := os.Stat(path); err == nil {
return nil
} else if !errors.Is(err, os.ErrNotExist) {
return err
}
if err := os.MkdirAll(filepath.Dir(path), 0700); err != nil {
return err
}
key := make([]byte, 32)
if _, err := rand.Read(key); err != nil {
return err
}
f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0600)
if errors.Is(err, os.ErrExist) {
return nil
}
if err != nil {
return err
}
if _, err = f.WriteString(hex.EncodeToString(key) + "\n"); err != nil {
f.Close()
os.Remove(path)
return err
}
return f.Close()
}
func bytesTrimSpace(v []byte) []byte { return []byte(strings.TrimSpace(string(v))) }
func (a *auth) sign(v string) string {
+155
View File
@@ -0,0 +1,155 @@
package server
import (
"context"
"encoding/json"
"math"
"net/http"
"sync"
"time"
"git.linuxiarz.pl/gru/EasyDNS-Web/internal/easydns"
"git.linuxiarz.pl/gru/EasyDNS-Web/internal/multiserver"
"git.linuxiarz.pl/gru/EasyDNS-Web/internal/telemetry"
)
const metricsModeCookie = "easydns_ui_metrics_mode"
// The mode is a presentation setting, not a DNS configuration operation.
// With Multi-server disabled the legacy single-node view is unchanged.
func (s *Server) metricsMode(w http.ResponseWriter, r *http.Request) string {
if !s.nodes.Enabled() || len(s.nodes.All()) < 2 {
return "single"
}
if _, explicit := r.URL.Query()["mode"]; explicit {
v := r.URL.Query().Get("mode")
if validMetricsMode(v) {
http.SetCookie(w, &http.Cookie{
Name: metricsModeCookie, Value: v, Path: "/metrics", HttpOnly: true,
Secure: s.cfg.CookieSecure, SameSite: http.SameSiteLaxMode,
MaxAge: 365 * 24 * 60 * 60,
})
return v
}
}
if c, err := r.Cookie(metricsModeCookie); err == nil && validMetricsMode(c.Value) {
return c.Value
}
return "aggregate"
}
func validMetricsMode(s string) bool {
return s == "single" || s == "split" || s == "aggregate"
}
type FleetMetricsNode struct {
Node multiserver.Node
Stats easydns.Stats
Available bool
Error string
Samples int
LastPoll time.Time
LastError string
}
// fetchFleetMetrics reads the *existing* EasyDNS /api/v1/stats endpoint on
// each node concurrently, never writes to DNS. Incomplete fleet totals are
// explicitly marked as partial in the UI; nonadditive latency is not summed.
func (s *Server) fetchFleetMetrics(ctx context.Context) ([]FleetMetricsNode, easydns.Stats, int, bool) {
all := s.nodes.All()
result := make([]FleetMetricsNode, len(all))
var wg sync.WaitGroup
for i, n := range all {
wg.Add(1)
go func(i int, node multiserver.Node) {
defer wg.Done()
item := FleetMetricsNode{Node: node}
_, api, history, ok := s.nodes.Get(node.ID)
if !ok {
item.Error = "Server connection was removed"
result[i] = item
return
}
current, sampleError, last := history.Snapshot()
item.LastPoll, item.LastError = last, sampleError
item.Samples = len(current)
reqCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
defer cancel()
if _, err := api.Get(reqCtx, "/api/v1/stats", &item.Stats); err != nil {
item.Error = "Stats request failed: " + err.Error()
} else {
item.Available = true
}
result[i] = item
}(i, n)
}
wg.Wait()
total := easydns.Stats{Responses: map[string]uint64{}, Sources: map[string]uint64{}}
online := 0
for _, n := range result {
if !n.Available {
continue
}
online++
st := n.Stats
total.QueriesTotal = saturatingAdd(total.QueriesTotal, st.QueriesTotal)
total.Blocked = saturatingAdd(total.Blocked, st.Blocked)
total.RateLimited = saturatingAdd(total.RateLimited, st.RateLimited)
for k, v := range st.Responses {
total.Responses[k] = saturatingAdd(total.Responses[k], v)
}
for k, v := range st.Sources {
total.Sources[k] = saturatingAdd(total.Sources[k], v)
}
total.Cache.Entries = saturatingAdd(total.Cache.Entries, st.Cache.Entries)
total.Cache.Hits = saturatingAdd(total.Cache.Hits, st.Cache.Hits)
total.Cache.Misses = saturatingAdd(total.Cache.Misses, st.Cache.Misses)
total.Cache.Evictions = saturatingAdd(total.Cache.Evictions, st.Cache.Evictions)
}
var cacheRateAvailable bool
if total.Cache.Hits > 0 || total.Cache.Misses > 0 {
total.CacheHitRate = float64(total.Cache.Hits) / (float64(total.Cache.Hits) + float64(total.Cache.Misses))
cacheRateAvailable = true
}
return result, total, online, cacheRateAvailable
}
func saturatingAdd(a, b uint64) uint64 {
if math.MaxUint64-a < b {
return math.MaxUint64
}
return a + b
}
// fleetTelemetry is a panel-internal authenticated JSON endpoint. It never
// calls a non-existent EasyDNS endpoint; all data comes from sampled /stats.
func (s *Server) fleetTelemetry(w http.ResponseWriter, _ *http.Request, mode string) {
all := s.nodes.All()
nodes := make([]telemetry.FleetNode, 0, len(all))
for _, n := range all {
_, _, history, ok := s.nodes.Get(n.ID)
if !ok {
// Preserve the node as a missing contributor when it is removed
// concurrently with this request. Never display a partial total.
nodes = append(nodes, telemetry.FleetNode{ID: n.ID, Name: n.Name, Role: n.Role, Error: "Server connection no longer available"})
continue
}
samples, errText, last := history.Snapshot()
nodes = append(nodes, telemetry.FleetNode{
ID: n.ID, Name: n.Name, Role: n.Role,
Samples: samples, Error: errText, LastPoll: last,
})
}
response := map[string]any{
"mode": mode, "nodes": nodes, "total": len(all),
"intervalSeconds": 15,
}
if mode == "aggregate" {
response["samples"] = telemetry.AggregateFleet(nodes)
response["aggregation"] = "strict-complete: rates sum only when every server has a fresh sample; cache ratio weighted by cache lookups; latency per node"
}
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.Header().Set("Cache-Control", "no-store")
_ = json.NewEncoder(w).Encode(response)
}
+160
View File
@@ -0,0 +1,160 @@
package server
import (
"encoding/json"
"fmt"
"math"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"testing"
"time"
"git.linuxiarz.pl/gru/EasyDNS-Web/internal/easydns"
)
func TestFleetModesUseAllServerStatsAndSelectedSingleMode(t *testing.T) {
newBackend := func(queries, hits, misses, blocked uint64) *httptest.Server {
return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
if r.URL.Path == "/api/v1/stats" {
fmt.Fprintf(w, `{"queries_total":%d,"cache":{"hits":%d,"misses":%d},"cache_hit_rate":0.5,"blocked":%d,"rate_limited":3,"responses":{"noerror":%d},"sources":{"recursive":%d},"latency_p95_s":0.012}`, queries, hits, misses, blocked, queries, queries)
return
}
fmt.Fprint(w, `{}`)
}))
}
local := newBackend(100, 90, 10, 2)
defer local.Close()
remote := newBackend(300, 10, 90, 5)
defer remote.Close()
s := panelWithNodes(t, local.URL, t.TempDir())
w := panelRequest(t, s, "GET", "/metrics?mode=aggregate", nil, nil)
if w.Code != 200 || strings.Contains(w.Body.String(), "METRICS SCOPE") || !strings.Contains(w.Body.String(), `data-metrics-mode="single"`) {
t.Fatalf("multi-server disabled must remain single-node: %d", w.Code)
}
if err := s.nodes.SetEnabled(true); err != nil {
t.Fatal(err)
}
node, err := s.nodes.Add("secondary-east", "secondary", remote.URL, "secret-remote")
if err != nil {
t.Fatal(err)
}
w = panelRequest(t, s, "GET", "/metrics?mode=aggregate", nil, nil)
if w.Code != 200 {
t.Fatalf("aggregate: %d %s", w.Code, w.Body.String())
}
body := w.Body.String()
for _, want := range []string{`data-metrics-mode="aggregate"`, "2 / 2 responding", "400", "50.0%", "Per server", "Aggregate", "Split", "Single", "All configured servers"} {
if !strings.Contains(body, want) {
t.Errorf("aggregate missing %q", want)
}
}
if strings.Contains(body, "secret-remote") || strings.Contains(body, "Switch</button>") {
t.Fatal("auth token or redundant Switch button in HTML")
}
w = panelRequest(t, s, "GET", "/metrics?mode=split", nil, nil)
if w.Code != 200 || !strings.Contains(w.Body.String(), `data-metrics-mode="split"`) || !strings.Contains(w.Body.String(), "secondary-east") || !strings.Contains(w.Body.String(), "NOERROR by server") {
t.Fatalf("split page missing server breakdown: %d", w.Code)
}
// Switch active server, then choose Single: only selected remote counters appear.
w = panelRequest(t, s, "POST", "/servers/select", url.Values{"server_id": {node.ID}, "next": {"/metrics"}}, nil)
var active *http.Cookie
for _, c := range w.Result().Cookies() {
if c.Name == activeNodeCookie {
active = c
}
}
if active == nil {
t.Fatal("node selection cookie missing")
}
w = panelRequest(t, s, "GET", "/metrics?mode=single", nil, active)
if w.Code != 200 || !strings.Contains(w.Body.String(), `data-metrics-mode="single"`) || !strings.Contains(w.Body.String(), "300") || strings.Contains(w.Body.String(), "2 / 2 responding") {
t.Fatalf("single mode not scoped to remote: %d", w.Code)
}
// Query parameter preference should survive a refresh through an HTTP-only cookie.
w = panelRequest(t, s, "GET", "/metrics?mode=split", nil, nil)
var pref *http.Cookie
for _, c := range w.Result().Cookies() {
if c.Name == metricsModeCookie {
pref = c
}
}
if pref == nil || !pref.HttpOnly || pref.Value != "split" {
t.Fatal("fleet preference cookie missing or insecure")
}
w = panelRequest(t, s, "GET", "/metrics", nil, pref)
if w.Code != 200 || !strings.Contains(w.Body.String(), `data-metrics-mode="split"`) {
t.Fatal("mode preference not restored")
}
}
func TestFleetTelemetryAggregatesAndSplitWithoutSecrets(t *testing.T) {
stub := func(q uint64) *httptest.Server {
return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, `{}`) }))
}
local := stub(10)
defer local.Close()
remote := stub(20)
defer remote.Close()
s := panelWithNodes(t, local.URL, t.TempDir())
if err := s.nodes.SetEnabled(true); err != nil {
t.Fatal(err)
}
node, err := s.nodes.Add("remote-node", "secondary", remote.URL, "private-remote-token")
if err != nil {
t.Fatal(err)
}
_, _, hLocal := s.nodes.Default()
_, _, hRemote, _ := s.nodes.Get(node.ID)
t0 := time.Now().UTC().Truncate(15 * time.Second).Add(time.Second)
mk := func(q, h, m uint64) easydns.Stats {
return easydns.Stats{QueriesTotal: q, Responses: map[string]uint64{"noerror": q}, Cache: easydns.Cache{Hits: h, Misses: m}}
}
hLocal.Record(t0, mk(100, 10, 10))
hLocal.Record(t0.Add(15*time.Second), mk(130, 30, 10))
hRemote.Record(t0.Add(2*time.Second), mk(200, 0, 0))
hRemote.Record(t0.Add(17*time.Second), mk(260, 0, 60))
w := panelRequest(t, s, "GET", "/ui/telemetry?mode=aggregate", nil, nil)
if w.Code != 200 {
t.Fatalf("aggregate endpoint %d", w.Code)
}
var agg struct {
Mode string `json:"mode"`
Nodes []struct {
Name string `json:"name"`
} `json:"nodes"`
Samples []struct {
Rate *float64 `json:"queryRate"`
Cache *float64 `json:"cacheHitRate"`
Contributors int `json:"contributors"`
} `json:"samples"`
}
if err := json.Unmarshal(w.Body.Bytes(), &agg); err != nil {
t.Fatal(err)
}
if agg.Mode != "aggregate" || len(agg.Nodes) != 2 || len(agg.Samples) == 0 {
t.Fatalf("aggregate shape: %+v", agg)
}
last := agg.Samples[len(agg.Samples)-1]
if last.Rate == nil || math.Abs(*last.Rate-6) > 0.00001 || last.Cache == nil || math.Abs(*last.Cache-25) > 0.00001 || last.Contributors != 2 {
t.Fatalf("bad weighted fleet aggregation: rate=%.8f cache=%.8f contributors=%d", *last.Rate, *last.Cache, last.Contributors)
}
if strings.Contains(w.Body.String(), "private-remote-token") {
t.Fatal("token leaked to metrics JSON")
}
w = panelRequest(t, s, "GET", "/ui/telemetry?mode=split", nil, nil)
if w.Code != 200 || !strings.Contains(w.Body.String(), `"mode":"split"`) || !strings.Contains(w.Body.String(), "remote-node") {
t.Fatalf("split telemetry missing: %d", w.Code)
}
w = panelRequest(t, s, "GET", "/ui/telemetry", nil, nil)
if w.Code != 200 || strings.Contains(w.Body.String(), "remote-node") || !strings.Contains(w.Body.String(), `"samples"`) {
t.Fatal("single telemetry was not preserved")
}
}
+13 -4
View File
@@ -190,15 +190,24 @@ func (s *Server) cacheFlush(w http.ResponseWriter, r *http.Request) {
s.render(w, r, "cache", "Cache", "Resolver cache counters and invalidation.", "cache", "MONITORING / CACHE", d)
}
func (s *Server) metrics(w http.ResponseWriter, r *http.Request) {
d := PageData{}
if e := s.get(r.Context(), "/api/v1/stats", &d.Stats); e != nil {
d.Error = e.Error()
d := PageData{MetricsMode: s.metricsMode(w, r)}
if d.MetricsMode == "single" {
if e := s.get(r.Context(), "/api/v1/stats", &d.Stats); e != nil {
d.Error = e.Error()
}
} else {
d.MetricNodes, d.MetricTotals, d.MetricOnline, d.MetricHasCache = s.fetchFleetMetrics(r.Context())
d.MetricTotal = len(d.MetricNodes)
}
sm, e, last := s.telemetry.Snapshot()
d.SamplingCount = len(sm)
d.SamplingTime = last
d.SamplingError = e
s.render(w, r, "metrics", "Metrics", "Real counters and live samples collected by this panel.", "metrics", "MONITORING / METRICS", d)
subtitle := "Real counters and live samples collected by this panel."
if d.MetricsMode != "single" {
subtitle = "Compare independent EasyDNS installations using actual per-node counters and samples."
}
s.render(w, r, "metrics", "Metrics", subtitle, "metrics", "MONITORING / METRICS", d)
}
func (s *Server) audit(w http.ResponseWriter, r *http.Request) {
d := PageData{}
+179
View File
@@ -0,0 +1,179 @@
package server
import (
"fmt"
"net/http"
"net/http/httptest"
"net/url"
"os"
"path/filepath"
"strings"
"testing"
"git.linuxiarz.pl/gru/EasyDNS-Web/internal/config"
)
func panelWithNodes(t *testing.T, backendURL, stateDir string) *Server {
t.Helper()
dir := t.TempDir()
pass := filepath.Join(dir, "panel.password")
key := filepath.Join(dir, "session.key")
token := filepath.Join(dir, "control.token")
for file, contents := range map[string]string{pass: "test-password-at-least-16", key: strings.Repeat("a", 64), token: "local-token"} {
if err := os.WriteFile(file, []byte(contents), 0600); err != nil {
t.Fatal(err)
}
}
s, err := New(config.Config{Listen: "127.0.0.1:0", APIURL: backendURL, TokenFile: token, PasswordFile: pass, SessionKeyFile: key, Username: "admin", NodesDir: stateDir})
if err != nil {
t.Fatal(err)
}
return s
}
func panelRequest(t *testing.T, s *Server, method, path string, form url.Values, nodeCookie *http.Cookie) *httptest.ResponseRecorder {
t.Helper()
sess := s.auth.makeSession()
var body string
if form != nil {
form.Set("_csrf", s.auth.csrf(strings.Join(strings.Split(sess, ".")[:2], ".")))
body = form.Encode()
}
req := httptest.NewRequest(method, "http://panel.test"+path, strings.NewReader(body))
req.AddCookie(&http.Cookie{Name: sessionCookie, Value: sess})
if nodeCookie != nil {
req.AddCookie(nodeCookie)
}
if form != nil {
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
}
w := httptest.NewRecorder()
s.Handler().ServeHTTP(w, req)
return w
}
func TestModePreferenceAndExistingSingleServerUI(t *testing.T) {
backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
switch r.URL.Path {
case "/api/v1/health":
fmt.Fprint(w, `{"status":"ok"}`)
case "/api/v1/status":
fmt.Fprint(w, `{"version":"0.1.4","mode":"hybrid","uptime_seconds":1080}`)
case "/readyz":
fmt.Fprint(w, `{"status":"ready"}`)
default:
fmt.Fprint(w, `{}`)
}
}))
defer backend.Close()
state := t.TempDir()
s := panelWithNodes(t, backend.URL, state)
w := panelRequest(t, s, "GET", "/configuration", nil, nil)
if w.Code != 200 || strings.Contains(w.Body.String(), `href="/servers"`) || !strings.Contains(w.Body.String(), "Enable multi-server management") {
t.Fatalf("single server configuration was changed: %d, body=%s", w.Code, w.Body.String())
}
w = panelRequest(t, s, "GET", "/servers", nil, nil)
if w.Code != 404 {
t.Fatalf("fleet accessible when off: %d", w.Code)
}
w = panelRequest(t, s, "POST", "/configuration/multi-server", url.Values{"enabled": {"on"}}, nil)
if w.Code != 303 || w.Header().Get("Location") != "/servers?notice=servers-enabled" {
t.Fatalf("toggle enable failed: %d, %s", w.Code, w.Body.String())
}
w = panelRequest(t, s, "GET", "/servers", nil, nil)
if w.Code != 200 || !strings.Contains(w.Body.String(), "Local EasyDNS") || !strings.Contains(w.Body.String(), "Compare zone serials") {
t.Fatalf("fleet view unavailable: %d, %s", w.Code, w.Body.String())
}
w = panelRequest(t, s, "POST", "/configuration/multi-server", url.Values{}, nil)
if w.Code != 303 {
t.Fatalf("toggle disable failed: %d", w.Code)
}
if s.nodes.Enabled() {
t.Fatal("fleet still enabled")
}
w = panelRequest(t, s, "GET", "/servers", nil, nil)
if w.Code != 404 {
t.Fatalf("fleet accessible after disable: %d", w.Code)
}
s2 := panelWithNodes(t, backend.URL, state)
if s2.nodes.Enabled() {
t.Fatal("disabled setting did not persist after restart")
}
w = panelRequest(t, s2, "GET", "/status", nil, nil)
if w.Code != 200 {
t.Fatalf("server status unavailable: %d, %s", w.Code, w.Body.String())
}
if !strings.Contains(w.Body.String(), `VERSION</span><strong>0.1.4</strong>`) {
t.Fatalf("version missing from status strip: %s", w.Body.String())
}
}
func TestFleetTokenRemainsOnServerAndSelectedTarget(t *testing.T) {
var remoteBearer string
local := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
switch r.URL.Path {
case "/api/v1/health":
fmt.Fprint(w, `{"status":"ok"}`)
case "/api/v1/status":
fmt.Fprint(w, `{"version":"0.1.4","mode":"local"}`)
default:
fmt.Fprint(w, `{}`)
}
}))
defer local.Close()
remote := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/api/v1/status" {
remoteBearer = r.Header.Get("Authorization")
}
w.Header().Set("Content-Type", "application/json")
switch r.URL.Path {
case "/api/v1/health":
fmt.Fprint(w, `{"status":"ok"}`)
case "/api/v1/status":
fmt.Fprint(w, `{"version":"0.1.4","mode":"remote"}`)
default:
fmt.Fprint(w, `{}`)
}
}))
defer remote.Close()
state := t.TempDir()
s := panelWithNodes(t, local.URL, state)
if err := s.nodes.SetEnabled(true); err != nil {
t.Fatal(err)
}
w := panelRequest(t, s, "POST", "/servers", url.Values{"name": {"dns-secondary-01"}, "role": {"secondary"}, "url": {remote.URL}, "token": {"remote-private-token"}}, nil)
if w.Code != 303 {
t.Fatalf("add remote server failed: %d, %s", w.Code, w.Body.String())
}
nodes := s.nodes.All()
if len(nodes) != 2 {
t.Fatalf("expected 2 servers, got %d", len(nodes))
}
w = panelRequest(t, s, "GET", "/servers", nil, nil)
if w.Code != 200 || strings.Contains(w.Body.String(), "remote-private-token") {
t.Fatal("remote token leaked in HTML")
}
// A successful context switch uses the remote client's generated control token.
w = panelRequest(t, s, "POST", "/servers/select", url.Values{"server_id": {nodes[1].ID}, "next": {"/status"}}, nil)
if w.Code != 303 || w.Header().Get("Location") != "/status" {
t.Fatalf("failed node selection: %d", w.Code)
}
var selected *http.Cookie
for _, c := range w.Result().Cookies() {
if c.Name == activeNodeCookie {
selected = c
}
}
if selected == nil || !selected.HttpOnly {
t.Fatal("no protected server selection cookie")
}
w = panelRequest(t, s, "GET", "/status", nil, selected)
if w.Code != 200 || !strings.Contains(w.Body.String(), "remote</strong>") || remoteBearer != "Bearer remote-private-token" {
t.Fatalf("remote node not queried: %d bearer=%s", w.Code, remoteBearer)
}
if strings.Contains(w.Body.String(), "remote-private-token") {
t.Fatal("remote bearer appeared in HTML")
}
}
+141
View File
@@ -0,0 +1,141 @@
package server
import (
"fmt"
"net/http"
"net/http/httptest"
"net/url"
"os"
"path/filepath"
"strings"
"testing"
"git.linuxiarz.pl/gru/EasyDNS-Web/internal/config"
)
func release011Backend() http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
switch r.URL.Path {
case "/api/v1/health":
fmt.Fprint(w, `{"status":"ok"}`)
case "/readyz":
fmt.Fprint(w, `{"status":"ready"}`)
case "/api/v1/status":
fmt.Fprint(w, `{"version":"0.1.4","mode":"hybrid","roles":{"primary":1,"secondary":0}}`)
case "/api/v1/policies":
fmt.Fprint(w, `{}`)
default:
fmt.Fprint(w, `{}`)
}
})
}
func TestRelease011CopyAndFooter(t *testing.T) {
s := testPanel(t, release011Backend())
w := httptest.NewRecorder()
s.Handler().ServeHTTP(w, httptest.NewRequest(http.MethodGet, "http://panel.test/login", nil))
if w.Code != http.StatusOK {
t.Fatalf("login status %d", w.Code)
}
body := w.Body.String()
for _, removed := range []string{
"LOCAL CONTROL ROOM", "Access the EasyDNS administration panel.",
"The EasyDNS bearer token stays on the server.",
"Panel authentication is separate from EasyDNS REST API credentials.",
} {
if strings.Contains(body, removed) {
t.Fatalf("obsolete login copy: %q", removed)
}
}
if !strings.Contains(body, "Sign in") || !strings.Contains(body, "name=\"password\"") {
t.Fatal("login form missing")
}
w = panelRequest(t, s, http.MethodGet, "/configuration", nil, nil)
if w.Code != http.StatusOK {
t.Fatalf("configuration status %d: %s", w.Code, w.Body.String())
}
body = w.Body.String()
for _, removed := range []string{"Only verified EasyDNS API operations are available", "What this panel cannot change"} {
if strings.Contains(body, removed) {
t.Fatalf("obsolete configuration/footer copy: %q", removed)
}
}
if !strings.Contains(body, `<footer class="footer">EasyDNS · independent management panel</footer>`) {
t.Fatalf("footer caption missing: %s", body)
}
if !strings.Contains(body, "Configuration workflow") || !strings.Contains(body, `href="/status"`) {
t.Fatal("configuration workflow missing")
}
}
func TestRelease011ConfiguredTOMLMultiServerAndInventory(t *testing.T) {
backend := httptest.NewServer(release011Backend())
defer backend.Close()
remote := httptest.NewServer(release011Backend())
defer remote.Close()
state := t.TempDir()
// An old UI preference must not override a current TOML configuration.
if err := os.WriteFile(filepath.Join(state, "settings.json"), []byte(`{"enabled":false}`), 0600); err != nil {
t.Fatal(err)
}
cfg := config.Config{
Listen: "127.0.0.1:8088", APIURL: backend.URL, APIToken: "local-token",
Username: "admin", Password: "a-long-admin-password", SessionAuto: true,
SessionKeyFile: filepath.Join(state, "session.key"), NodesDir: state,
MultiServer: true, MultiServerExplicit: true,
LocalName: "DNS Primary", LocalRole: "primary", LocalRoleExplicit: true,
Servers: []config.ServerSeed{{Slot: 1, Name: "DNS Secondary", Role: "secondary", URL: remote.URL, Token: "remote-token"}},
}
s, err := New(cfg)
if err != nil {
t.Fatal(err)
}
if !s.nodes.Enabled() {
t.Fatal("explicit TOML setting lost to saved preference")
}
w := panelRequest(t, s, http.MethodGet, "/configuration", nil, nil)
if w.Code != http.StatusOK {
t.Fatalf("configuration status %d", w.Code)
}
if strings.Contains(w.Body.String(), "Panel settings · Multi-server management") || strings.Contains(w.Body.String(), `action="/configuration/multi-server"`) {
t.Fatal("TOML-managed mode has a redundant UI toggle")
}
w = panelRequest(t, s, http.MethodPost, "/configuration/multi-server", url.Values{}, nil)
if w.Code != http.StatusForbidden || !s.nodes.Enabled() {
t.Fatalf("configured mode was editable: %d", w.Code)
}
w = panelRequest(t, s, http.MethodGet, "/servers", nil, nil)
if w.Code != http.StatusOK {
t.Fatalf("servers status %d: %s", w.Code, w.Body.String())
}
body := w.Body.String()
for _, required := range []string{"DNS Primary", "DNS Secondary", ">LOCAL</span>", ">REMOTE</span>", "Primary", "Secondary"} {
if !strings.Contains(body, required) {
t.Fatalf("missing inventory %q", required)
}
}
for _, obsolete := range []string{">ENV</span>", "Configured in .env / systemd", `action="/servers/local/role"`} {
if strings.Contains(body, obsolete) {
t.Fatalf("fixed server exposes obsolete/editor copy: %q", obsolete)
}
}
remoteID := s.nodes.All()[1].ID
if strings.Contains(body, `action="/servers/`+remoteID+`/role"`) || strings.Contains(body, `href="/servers/`+remoteID+`/remove"`) {
t.Fatal("configuration-managed remote server shows mutable actions")
}
w = panelRequest(t, s, http.MethodPost, "/servers/local/role", url.Values{"role": {"secondary"}}, nil)
if w.Code != http.StatusForbidden {
t.Fatalf("fixed local role writable: %d", w.Code)
}
w = panelRequest(t, s, http.MethodPost, "/servers/"+remoteID+"/role", url.Values{"role": {"unassigned"}}, nil)
if w.Code != http.StatusForbidden {
t.Fatalf("fixed remote role writable: %d", w.Code)
}
w = panelRequest(t, s, http.MethodGet, "/servers/"+remoteID+"/remove", nil, nil)
if w.Code != http.StatusForbidden {
t.Fatalf("fixed remote removal available: %d", w.Code)
}
}
+79 -8
View File
@@ -13,8 +13,7 @@ import (
"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"
"git.linuxiarz.pl/gru/EasyDNS-Web/internal/multiserver"
)
var Version = "dev"
@@ -24,18 +23,29 @@ func New(cfg config.Config) (*Server, error) {
if err != nil {
return nil, fmt.Errorf("panel auth: %w", err)
}
client, err := easydns.New(cfg.APIURL, cfg.TokenFile, cfg.APISocket)
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, err
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: telemetry.New(), auth: a, templates: ts}, nil
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.telemetry.Run(ctx, s.api)
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()
@@ -85,10 +95,49 @@ func (s *Server) authorized(w http.ResponseWriter, r *http.Request) {
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":
@@ -137,6 +186,8 @@ func (s *Server) authorized(w http.ResponseWriter, r *http.Request) {
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/"):
@@ -169,7 +220,10 @@ func (s *Server) render(w http.ResponseWriter, r *http.Request, page, title, sub
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}
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)
@@ -203,6 +257,18 @@ func notice(n string) (string, string) {
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:
@@ -216,7 +282,12 @@ 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) {
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")
+211
View File
@@ -0,0 +1,211 @@
package server
import (
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"sync/atomic"
"testing"
"time"
"git.linuxiarz.pl/gru/EasyDNS-Web/internal/easydns"
)
// A node selection must replace the entire target client for that browser,
// not just the label in the toolbar. Different API responses catch regressions
// where the UI silently continues to use the local EasyDNS instance.
func TestNodeSelectionSwitchesZonesStatusTelemetryAndWrites(t *testing.T) {
var localWrites, remoteWrites atomic.Int32
backend := func(zone, mode string, queryCount int, writes *atomic.Int32, expectedBearer string) *httptest.Server {
return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
if r.URL.Path != "/api/v1/health" && r.URL.Path != "/readyz" && r.Header.Get("Authorization") != expectedBearer {
w.WriteHeader(http.StatusUnauthorized)
fmt.Fprint(w, `{"error":{"status":401,"message":"wrong token"}}`)
return
}
switch {
case r.Method == "GET" && r.URL.Path == "/api/v1/health":
fmt.Fprint(w, `{"status":"ok"}`)
case r.Method == "GET" && r.URL.Path == "/api/v1/status":
fmt.Fprintf(w, `{"version":"0.1.4","mode":%q,"roles":{"primary":1,"secondary":0}}`, mode)
case r.Method == "GET" && r.URL.Path == "/api/v1/stats":
fmt.Fprintf(w, `{"queries_total":%d,"responses":{"noerror":%d},"cache":{"hits":5,"misses":2}}`, queryCount, queryCount)
case r.Method == "GET" && r.URL.Path == "/api/v1/zones":
fmt.Fprintf(w, `{"items":[{"name":%q,"kind":"primary","serial":101,"records":1,"loaded":true}],"pagination":{"page":1,"per_page":25,"total":1}}`, zone)
case r.Method == "GET" && r.URL.Path == "/api/v1/audit":
fmt.Fprint(w, `{"items":[]}`)
case r.Method == "DELETE" && r.URL.Path == "/api/v1/cache":
writes.Add(1)
fmt.Fprint(w, `{"removed":1}`)
default:
w.WriteHeader(http.StatusNotFound)
}
}))
}
local := backend("local.example.", "local-mode", 100, &localWrites, "Bearer local-token")
defer local.Close()
remote := backend("remote.example.", "remote-mode", 250, &remoteWrites, "Bearer remote-private-token")
defer remote.Close()
s := panelWithNodes(t, local.URL, t.TempDir())
if err := s.nodes.SetEnabled(true); err != nil {
t.Fatal(err)
}
node, err := s.nodes.Add("dns-secondary-01", "secondary", remote.URL, "remote-private-token")
if err != nil {
t.Fatal(err)
}
w := panelRequest(t, s, "GET", "/zones", nil, nil)
if w.Code != 200 || !strings.Contains(w.Body.String(), "local.example.") || strings.Contains(w.Body.String(), "remote.example.") {
t.Fatalf("default zones must originate on local node, status %d", w.Code)
}
// External JS is permitted by the CSP; inline onchange was blocked in
// production. There is no redundant manual Switch button.
if strings.Contains(w.Body.String(), "onchange=") || !strings.Contains(w.Body.String(), "data-switch-server") || strings.Contains(w.Body.String(), ">Switch</button>") {
t.Fatal("server picker must use external JavaScript without a manual Switch button")
}
if !strings.Contains(w.Body.String(), "ACTIVE SERVER") || !strings.Contains(w.Body.String(), "Local EasyDNS") {
t.Fatal("active data source not shown")
}
w = panelRequest(t, s, "POST", "/servers/select", url.Values{"server_id": {node.ID}, "next": {"/zones"}}, nil)
if w.Code != http.StatusSeeOther || w.Header().Get("Location") != "/zones" {
t.Fatalf("selection failed: %d %s", w.Code, w.Body.String())
}
var nodeCookie *http.Cookie
for _, c := range w.Result().Cookies() {
if c.Name == activeNodeCookie {
nodeCookie = c
break
}
}
if nodeCookie == nil || nodeCookie.Value != node.ID || !nodeCookie.HttpOnly {
t.Fatal("selected remote node was not persisted in protected cookie")
}
w = panelRequest(t, s, "GET", "/zones", nil, nodeCookie)
if w.Code != 200 || !strings.Contains(w.Body.String(), "remote.example.") || strings.Contains(w.Body.String(), "local.example.") {
t.Fatalf("remote zone list is not selected, status %d", w.Code)
}
if !strings.Contains(w.Body.String(), "dns-secondary-01") || !strings.Contains(w.Body.String(), "ACTIVE SERVER") {
t.Fatal("page does not identify remote server context")
}
w = panelRequest(t, s, "GET", "/status", nil, nodeCookie)
if w.Code != 200 || !strings.Contains(w.Body.String(), "remote-mode") || strings.Contains(w.Body.String(), "local-mode") {
t.Fatalf("status endpoint did not switch: %d", w.Code)
}
w = panelRequest(t, s, "GET", "/", nil, nodeCookie)
if w.Code != 200 || !strings.Contains(w.Body.String(), "250") || strings.Contains(w.Body.String(), "local-mode") {
t.Fatalf("overview did not switch: %d", w.Code)
}
_, _, remoteHistory, _ := s.nodes.Get(node.ID)
_, _, localHistory := s.nodes.Default()
t0 := time.Now().UTC().Add(-15 * time.Second)
localHistory.Record(t0, easydns.Stats{QueriesTotal: 100})
localHistory.Record(t0.Add(15*time.Second), easydns.Stats{QueriesTotal: 115}) // 1 QPS
remoteHistory.Record(t0, easydns.Stats{QueriesTotal: 500})
remoteHistory.Record(t0.Add(15*time.Second), easydns.Stats{QueriesTotal: 1100}) // 40 QPS
w = panelRequest(t, s, "GET", "/ui/telemetry", nil, nodeCookie)
if w.Code != 200 {
t.Fatalf("remote telemetry response invalid: %d %s", w.Code, w.Body.String())
}
var out struct {
Samples []struct {
QueryRate *float64 `json:"queryRate"`
} `json:"samples"`
}
if err := json.Unmarshal(w.Body.Bytes(), &out); err != nil || len(out.Samples) != 2 || out.Samples[1].QueryRate == nil || *out.Samples[1].QueryRate != 40 {
t.Fatalf("selected telemetry must be remote-only: %v %s", err, w.Body.String())
}
// Only the selected remote server may receive a destructive operation.
w = panelRequest(t, s, "POST", "/cache/flush", url.Values{"scope": {"all"}, "confirm": {"FLUSH ALL"}}, nodeCookie)
if w.Code != http.StatusSeeOther || localWrites.Load() != 0 || remoteWrites.Load() != 1 {
t.Fatalf("write crossed node boundary: status=%d local=%d remote=%d", w.Code, localWrites.Load(), remoteWrites.Load())
}
w = panelRequest(t, s, "POST", "/servers/select", url.Values{"server_id": {"local"}, "next": {"/zones"}}, nodeCookie)
if w.Code != http.StatusSeeOther {
t.Fatalf("switch back failed: %d", w.Code)
}
var localCookie *http.Cookie
for _, c := range w.Result().Cookies() {
if c.Name == activeNodeCookie {
localCookie = c
break
}
}
w = panelRequest(t, s, "GET", "/zones", nil, localCookie)
if w.Code != 200 || !strings.Contains(w.Body.String(), "local.example.") || strings.Contains(w.Body.String(), "remote.example.") {
t.Fatalf("switching back did not restore local zones: %d", w.Code)
}
}
func TestStaleSelectionNeverExecutesDNSWriteOnDefaultServer(t *testing.T) {
var writes atomic.Int32
local := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method != "GET" {
writes.Add(1)
}
w.Header().Set("Content-Type", "application/json")
fmt.Fprint(w, `{}`)
}))
defer local.Close()
s := panelWithNodes(t, local.URL, t.TempDir())
if err := s.nodes.SetEnabled(true); err != nil {
t.Fatal(err)
}
bogus := &http.Cookie{Name: activeNodeCookie, Value: strings.Repeat("1", 24)}
w := panelRequest(t, s, "POST", "/cache/flush", url.Values{"scope": {"all"}, "confirm": {"FLUSH ALL"}}, bogus)
if w.Code != http.StatusConflict || writes.Load() != 0 {
t.Fatalf("stale server cookie redirected DNS write to local server: %d (%d writes)", w.Code, writes.Load())
}
if !strings.Contains(w.Body.String(), "No DNS operation was performed") {
t.Fatal("missing actionable error for stale node")
}
w = panelRequest(t, s, "GET", "/zones", nil, bogus)
if w.Code != http.StatusSeeOther || w.Header().Get("Location") != "/servers?notice=server-selection-expired" {
t.Fatalf("stale selection GET not explained: %d %s", w.Code, w.Header().Get("Location"))
}
w = panelRequest(t, s, "POST", "/servers/select", url.Values{"server_id": {"local"}, "next": {"/zones"}}, bogus)
if w.Code != http.StatusSeeOther {
t.Fatalf("unable to recover by selecting a new server: %d", w.Code)
}
}
func TestSwitcherScriptAndImmutableFingerprintAssets(t *testing.T) {
script, err := assets.ReadFile("web/static/app.js")
if err != nil {
t.Fatal(err)
}
if !strings.Contains(string(script), "select[data-switch-server]") || !strings.Contains(string(script), "requestSubmit") || !strings.Contains(string(script), "addEventListener('change'") {
t.Fatal("external switcher script no longer submits selection changes")
}
req := httptest.NewRequest(http.MethodGet, "http://panel.test"+assetURL("app.js"), nil)
w := httptest.NewRecorder()
secureHeaders(http.StripPrefix("/static/", staticHandler())).ServeHTTP(w, req)
if w.Code != http.StatusOK || w.Header().Get("Cache-Control") != "public, max-age=31536000, immutable" {
t.Fatalf("fingerprinted JS must support immutable caching: status=%d cache=%q", w.Code, w.Header().Get("Cache-Control"))
}
if !strings.Contains(w.Header().Get("Content-Security-Policy"), "script-src 'self'") {
t.Fatal("strict CSP protection was unexpectedly removed")
}
}
func TestNodeSwitchDestination(t *testing.T) {
cases := map[string]string{
"": "/", "//evil.example": "/", "https://evil.example/": "/", "\\\\evil.example": "/",
"/zones": "/zones", "/zones?kind=secondary": "/zones?kind=secondary",
"/zones/example.com./records/42/edit": "/zones", "/zones/new": "/zones",
"/upstreams/new": "/upstreams", "/servers/compare?zone=example.com.": "/",
"/status": "/status", "/anything": "/",
}
for raw, want := range cases {
if got := nodeSwitchDestination(raw); got != want {
t.Errorf("%q -> %q, want %q", raw, got, want)
}
}
}
+209
View File
@@ -0,0 +1,209 @@
package server
import (
"net/http"
"net/url"
"strings"
)
const activeNodeCookie = "easydns_ui_node"
func clearNodeCookie(w http.ResponseWriter, secure bool) {
http.SetCookie(w, &http.Cookie{Name: activeNodeCookie, Path: "/", Value: "", MaxAge: -1, HttpOnly: true, Secure: secure, SameSite: http.SameSiteStrictMode})
}
func (s *Server) multiServerPreference(w http.ResponseWriter, r *http.Request) {
if s.cfg.MultiServerExplicit {
http.Error(w, "Multi-server mode is configured in TOML or environment; change the configuration and restart the panel.", http.StatusForbidden)
return
}
r.Body = http.MaxBytesReader(w, r.Body, 4096)
if err := r.ParseForm(); err != nil {
http.Error(w, "Invalid form", http.StatusBadRequest)
return
}
value := r.PostForm.Get("enabled")
if value != "" && value != "on" {
http.Error(w, "Invalid preference value", http.StatusBadRequest)
return
}
enabled := value == "on"
if err := s.nodes.SetEnabled(enabled); err != nil {
http.Error(w, "Could not save panel preferences: "+err.Error(), http.StatusInternalServerError)
return
}
if enabled {
redirect(w, r, "/servers?notice=servers-enabled")
return
}
clearNodeCookie(w, s.cfg.CookieSecure)
redirect(w, r, "/configuration?notice=servers-disabled")
}
func (s *Server) serversOverview(w http.ResponseWriter, r *http.Request) {
d := PageData{ServerProbes: s.nodes.ProbeAll(r.Context())}
for _, p := range d.ServerProbes {
if p.State == "healthy" {
d.ServerHealthy++
}
}
s.render(w, r, "servers", "Servers", "Monitor and manage independent EasyDNS installations from one panel.", "servers", "MULTI-SERVER / SERVERS", d)
}
func (s *Server) serverNewForm(w http.ResponseWriter, r *http.Request) {
s.render(w, r, "server-form", "Add server", "Connect another EasyDNS REST API using its own generated control token.", "servers", "MULTI-SERVER / ADD SERVER", PageData{Form: map[string]string{"role": "secondary"}})
}
func (s *Server) serverCreate(w http.ResponseWriter, r *http.Request) {
r.Body = http.MaxBytesReader(w, r.Body, 12<<10)
if err := r.ParseForm(); err != nil {
http.Error(w, "Invalid form", http.StatusBadRequest)
return
}
d := PageData{Form: formValues(r, "name", "role", "url")}
token := strings.TrimSpace(r.PostForm.Get("token")) // never add this to PageData or logs
_, err := s.nodes.Add(d.Form["name"], d.Form["role"], d.Form["url"], token)
if err != nil {
d.Error = err.Error()
s.render(w, r, "server-form", "Add server", "Connect another EasyDNS REST API using its own generated control token.", "servers", "MULTI-SERVER / ADD SERVER", d)
return
}
redirect(w, r, "/servers?notice=server-added")
}
func (s *Server) serverSelect(w http.ResponseWriter, r *http.Request) {
r.Body = http.MaxBytesReader(w, r.Body, 4096)
if err := r.ParseForm(); err != nil {
http.Error(w, "Invalid form", http.StatusBadRequest)
return
}
id := r.PostForm.Get("server_id")
if _, _, _, ok := s.nodes.Get(id); !ok {
http.Error(w, "Unknown server", http.StatusBadRequest)
return
}
http.SetCookie(w, &http.Cookie{Name: activeNodeCookie, Value: id, Path: "/", HttpOnly: true, Secure: s.cfg.CookieSecure, SameSite: http.SameSiteStrictMode, MaxAge: 12 * 60 * 60})
next := nodeSwitchDestination(r.PostForm.Get("next"))
redirect(w, r, next)
}
// nodeSwitchDestination preserves list/diagnostic pages when switching nodes.
// Per-zone forms and detail URLs are reset to the list because the new server
// may not contain the same zone, record, ETag, or other editable resource.
func nodeSwitchDestination(raw string) string {
if raw == "" || !strings.HasPrefix(raw, "/") || strings.HasPrefix(raw, "//") || strings.ContainsAny(raw, "\\\r\n") {
return "/"
}
u, err := url.ParseRequestURI(raw)
if err != nil || u.IsAbs() || u.Host != "" || u.Fragment != "" {
return "/"
}
path := u.Path
switch {
case strings.HasPrefix(path, "/zones/"):
return "/zones"
case strings.HasPrefix(path, "/upstreams/"):
return "/upstreams"
case strings.HasPrefix(path, "/blocklists/"):
return "/blocklists"
case strings.HasPrefix(path, "/servers/") || path == "/servers":
return "/"
case path == "/", path == "/zones", path == "/query", path == "/upstreams", path == "/policies", path == "/views", path == "/acl", path == "/rate-limiting", path == "/blocklists", path == "/cache", path == "/metrics", path == "/audit", path == "/status", path == "/configuration":
return raw
default:
return "/"
}
}
func (s *Server) serverCompare(w http.ResponseWriter, r *http.Request) {
d := PageData{CompareZone: strings.TrimSpace(r.URL.Query().Get("zone"))}
if d.CompareZone != "" {
c, err := s.nodes.Compare(r.Context(), d.CompareZone)
if err != nil {
d.Error = err.Error()
} else {
d.Comparisons = c
for _, item := range c {
if item.Node.Role == "primary" && item.Present && item.Zone.Serial != nil {
d.PrimarySerial = item.Serial
break
}
}
}
}
s.render(w, r, "server-compare", "Zone comparison", "Compare a zone's presence and SOA serial across configured servers.", "servers", "MULTI-SERVER / ZONE COMPARISON", d)
}
func (s *Server) serverAction(w http.ResponseWriter, r *http.Request) {
raw := strings.TrimPrefix(r.URL.Path, "/servers/")
parts := strings.Split(raw, "/")
if len(parts) != 2 || parts[0] == "" {
http.NotFound(w, r)
return
}
id, action := parts[0], parts[1]
node, _, _, ok := s.nodes.Get(id)
if !ok {
http.NotFound(w, r)
return
}
switch {
case action == "remove" && r.Method == "GET":
if node.Local {
http.Error(w, "Local server cannot be removed", http.StatusBadRequest)
return
}
if node.Managed {
http.Error(w, "Configuration-managed servers cannot be removed from this panel.", http.StatusForbidden)
return
}
s.render(w, r, "server-remove", "Remove server connection", "Remove a managed connection without deleting or changing EasyDNS itself.", "servers", "MULTI-SERVER / REMOVE SERVER", PageData{ManagedNode: node})
case action == "remove" && r.Method == "POST":
if node.Local {
http.Error(w, "Local server cannot be removed", http.StatusBadRequest)
return
}
if node.Managed {
http.Error(w, "Configuration-managed servers cannot be removed from this panel.", http.StatusForbidden)
return
}
if r.FormValue("confirm_name") != node.Name {
s.render(w, r, "server-remove", "Remove server connection", "The confirmation name must match.", "servers", "MULTI-SERVER / REMOVE SERVER", PageData{ManagedNode: node, Error: "Type the exact server name to remove this panel connection."})
return
}
if err := s.nodes.Remove(id); err != nil {
http.Error(w, "Unable to remove server: "+err.Error(), http.StatusInternalServerError)
return
}
if s.selectedNode.ID == id {
clearNodeCookie(w, s.cfg.CookieSecure)
}
redirect(w, r, "/servers?notice=server-removed")
case action == "role" && r.Method == "POST":
if node.Managed {
http.Error(w, "Configuration-managed role labels cannot be changed from this panel.", http.StatusForbidden)
return
}
if node.Local && s.cfg.LocalRoleExplicit {
http.Error(w, "The local server label is configured in TOML or environment; change the configuration and restart the panel.", http.StatusForbidden)
return
}
r.Body = http.MaxBytesReader(w, r.Body, 2048)
if err := r.ParseForm(); err != nil {
http.Error(w, "Invalid form", http.StatusBadRequest)
return
}
if err := s.nodes.SetRole(id, r.PostForm.Get("role")); err != nil {
// Role changes affect panel labels only; preserve a user-readable error.
d := PageData{ServerProbes: s.nodes.ProbeAll(r.Context()), Error: err.Error()}
for _, p := range d.ServerProbes {
if p.State == "healthy" {
d.ServerHealthy++
}
}
s.render(w, r, "servers", "Servers", "Monitor and manage independent EasyDNS installations from one panel.", "servers", "MULTI-SERVER / SERVERS", d)
return
}
redirect(w, r, "/servers?notice=server-role")
default:
http.NotFound(w, r)
}
}
// All native EasyDNS operations are carried out through the selected client's
// documented routes. The panel never creates server-side cluster endpoints.
+103
View File
@@ -0,0 +1,103 @@
package server
import (
"bytes"
"crypto/sha256"
"encoding/hex"
"fmt"
"io/fs"
"mime"
"net/http"
"path"
"strings"
"sync"
"time"
)
// BuildID is injected by Docker/Debian build scripts. It deliberately changes
// at build time, even when the public package version stays at 0.1.1.
// In regular `go test` / `go build` content hashes still identify every asset.
var BuildID = "development"
type staticAsset struct {
data []byte
mime string
etag string
}
var staticOnce sync.Once
var staticURLs map[string]string
var staticRoutes map[string]staticAsset
var staticErr error
func makeStaticManifest() {
staticURLs = make(map[string]string)
staticRoutes = make(map[string]staticAsset)
files, err := fs.Sub(assets, "web/static")
if err != nil {
staticErr = err
return
}
err = fs.WalkDir(files, ".", func(filename string, entry fs.DirEntry, walkErr error) error {
if walkErr != nil {
return walkErr
}
if entry.IsDir() {
return nil
}
raw, err := fs.ReadFile(files, filename)
if err != nil {
return err
}
digest := sha256.Sum256(append([]byte(BuildID+"\x00"), raw...))
stamp := hex.EncodeToString(digest[:])[:16]
ext := path.Ext(filename)
hashed := strings.TrimSuffix(filename, ext) + "." + stamp + ext
url := "/static/" + hashed
kind := mime.TypeByExtension(ext)
switch ext {
case ".css":
kind = "text/css; charset=utf-8"
case ".js":
kind = "text/javascript; charset=utf-8"
case ".svg":
kind = "image/svg+xml"
}
if kind == "" {
kind = "application/octet-stream"
}
staticURLs[filename] = url
staticRoutes["/"+hashed] = staticAsset{data: raw, mime: kind, etag: `"` + stamp + `"`}
return nil
})
staticErr = err
}
func assetURL(name string) string {
staticOnce.Do(makeStaticManifest)
if staticErr != nil {
panic(fmt.Errorf("prepare static assets: %w", staticErr))
}
if url, ok := staticURLs[name]; ok {
return url
}
panic("unknown embedded static asset: " + name)
}
func staticHandler() http.Handler {
staticOnce.Do(makeStaticManifest)
if staticErr != nil {
panic(staticErr)
}
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
asset, ok := staticRoutes["/"+strings.TrimPrefix(r.URL.Path, "/")]
if !ok {
http.NotFound(w, r)
return
}
w.Header().Set("Content-Type", asset.mime)
w.Header().Set("Cache-Control", "public, max-age=31536000, immutable")
w.Header().Set("ETag", asset.etag)
http.ServeContent(w, r, path.Base(r.URL.Path), time.Time{}, bytes.NewReader(asset.data))
})
}
+44
View File
@@ -0,0 +1,44 @@
package server
import (
"io"
"net/http"
"net/http/httptest"
"regexp"
"strings"
"testing"
)
func TestFingerprintedAssetsAreImmutableAndUnversionedPathsReject(t *testing.T) {
css := assetURL("app.css")
js := assetURL("app.js")
icon := assetURL("icons.svg")
pattern := regexp.MustCompile(`^/static/[a-z0-9.-]+\.[0-9a-f]{16}\.(css|js|svg)$`)
for _, v := range []string{css, js, icon} {
if !pattern.MatchString(v) {
t.Fatalf("not a fingerprinted filename: %q", v)
}
}
s := testPanel(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { _, _ = io.WriteString(w, `{"status":"ok"}`) }))
r := httptest.NewRequest(http.MethodGet, "http://panel.test/login", nil)
w := httptest.NewRecorder()
s.Handler().ServeHTTP(w, r)
if w.Code != 200 || !strings.Contains(w.Body.String(), css) || !strings.Contains(w.Body.String(), assetURL("vendor/bootstrap.min.css")) {
t.Fatalf("login does not use fingerprinted CSS: %d", w.Code)
}
if strings.Contains(w.Body.String(), "?rev=") || strings.Contains(w.Body.String(), "/static/app.css") {
t.Fatal("old query-based cache busting remains")
}
for _, uri := range []string{css, js, icon} {
w = httptest.NewRecorder()
s.Handler().ServeHTTP(w, httptest.NewRequest(http.MethodGet, "http://panel.test"+uri, nil))
if w.Code != 200 || w.Header().Get("Cache-Control") != "public, max-age=31536000, immutable" {
t.Fatalf("asset %s status=%d cache=%q", uri, w.Code, w.Header().Get("Cache-Control"))
}
}
w = httptest.NewRecorder()
s.Handler().ServeHTTP(w, httptest.NewRequest(http.MethodGet, "http://panel.test/static/app.css", nil))
if w.Code != 404 {
t.Fatalf("unfingerprinted JS/CSS route was exposed: %d", w.Code)
}
}
+55 -42
View File
@@ -6,13 +6,13 @@ import (
"fmt"
"html/template"
"io/fs"
"net/http"
"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/multiserver"
"git.linuxiarz.pl/gru/EasyDNS-Web/internal/telemetry"
)
@@ -20,53 +20,73 @@ import (
var assets embed.FS
type PageData struct {
Status easydns.Status
Health easydns.Health
Stats easydns.Stats
Cache easydns.Cache
Zone easydns.Zone
Zones []easydns.Zone
Records []easydns.Record
Record easydns.Record
Pagination easydns.Pagination
Transfers []easydns.Transfer
Upstreams []easydns.UpstreamGroup
Policies easydns.Policies
Blocklists easydns.Blocklists
Audit []easydns.AuditItem
Query *easydns.QueryResult
Form map[string]string
Filter map[string]string
ETag string
ZoneURL string
IsPrimary bool
Error string
Success string
Action string
Tab string
FieldErrors map[string]string
SamplingCount int
SamplingTime time.Time
SamplingError string
LastRate string
Status easydns.Status
Health easydns.Health
Stats easydns.Stats
Cache easydns.Cache
Zone easydns.Zone
Zones []easydns.Zone
Records []easydns.Record
Record easydns.Record
Pagination easydns.Pagination
Transfers []easydns.Transfer
Upstreams []easydns.UpstreamGroup
Policies easydns.Policies
Blocklists easydns.Blocklists
Audit []easydns.AuditItem
Query *easydns.QueryResult
Form map[string]string
Filter map[string]string
ETag string
ZoneURL string
IsPrimary bool
Error string
Success string
Action string
Tab string
FieldErrors map[string]string
SamplingCount int
SamplingTime time.Time
SamplingError string
LastRate string
ServerProbes []multiserver.Probe
Comparisons []multiserver.Comparison
ManagedNode multiserver.Node
CompareZone string
PrimarySerial string
ServerHealthy int
MetricsMode string
MetricNodes []FleetMetricsNode
MetricTotals easydns.Stats
MetricOnline int
MetricTotal int
MetricHasCache bool
}
type PageView struct {
Title, Subtitle, Page, Active, Breadcrumb, User, CSRF, Message, MessageType string
Data PageData
Body template.HTML
BuildVersion string
MultiServer bool
CanEditMultiServer, LocalRoleConfigured bool
Nodes []multiserver.Node
SelectedNode multiserver.Node
CurrentPath string
}
type Server struct {
cfg config.Config
api *easydns.Client
telemetry *telemetry.History
auth *auth
templates map[string]*template.Template
cfg config.Config
api *easydns.Client
telemetry *telemetry.History
auth *auth
templates map[string]*template.Template
nodes *multiserver.Registry
selectedNode multiserver.Node
}
func funcs() template.FuncMap {
return template.FuncMap{
"asset": assetURL,
"recordTypes": func() []string {
return []string{"A", "AAAA", "CNAME", "MX", "TXT", "NS", "PTR", "SRV", "CAA", "DS", "DNSKEY", "TLSA", "SSHFP", "NAPTR"}
},
@@ -197,10 +217,3 @@ func loadTemplates() (map[string]*template.Template, error) {
}
return result, nil
}
func staticHandler() http.Handler {
sub, err := fs.Sub(assets, "web/static")
if err != nil {
panic(err)
}
return http.FileServer(http.FS(sub))
}
+91 -4
View File
@@ -22,18 +22,105 @@
.breadcrumbs{font:11px/1.2 var(--mono);color:#c7d3ca;letter-spacing:.35px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.top-actions{display:flex;align-items:center;gap:7px;flex-shrink:0}.tool-button,.btn-ui{background:transparent;border:1px solid #49534c;color:#e0e7e0;min-height:31px;display:inline-flex;align-items:center;justify-content:center;gap:7px;padding:6px 11px;border-radius:3px;font-size:12px;font-weight:510;text-decoration:none;line-height:1.2;cursor:pointer;white-space:nowrap;transition:none}.tool-button:hover,.btn-ui:hover{border-color:#97ada0;color:#fff;background:#1a211e}.tool-button:focus-visible,.btn-ui:focus-visible,.field:focus-visible,.sidenav a:focus-visible{outline:2px solid var(--cyan);outline-offset:2px}.ico{width:14px;height:14px;fill:none;stroke:currentColor;stroke-width:1.7;stroke-linecap:round;stroke-linejoin:round;flex-shrink:0}.btn-primary-ui{border-color:#94c488;background:var(--green);color:#10200e;font-weight:690}.btn-primary-ui:hover{background:#b2e6a9;border-color:#b2e6a9;color:#10200e}.btn-danger-ui{border-color:#955651;color:#ffb5ad;background:#251612}.btn-danger-ui:hover{background:#3c2420;border-color:#d18a85;color:#fff}.btn-small{min-height:25px;padding:3px 8px;font-size:11px}.icon-button{display:inline-flex;align-items:center;justify-content:center;width:28px;height:28px;color:#d5dfd7;border:1px solid transparent;border-radius:2px}.icon-button:hover{background:#242f29;color:#fff;border-color:#556256}.icon-button.danger-hover:hover{color:var(--red);border-color:#9d5955}.row-actions{display:flex;gap:3px;justify-content:flex-end}.mobile-menu{display:none}
.content{padding:17px 25px 26px;max-width:2220px;margin:0 auto;min-width:0}.page-head{display:flex;align-items:center;justify-content:space-between;gap:20px;margin-bottom:19px}.eyebrow{font:10px/1.4 var(--mono);color:#a4d291;text-transform:uppercase;letter-spacing:1px;margin-bottom:6px}.page-head h1{font-size:27px;line-height:1.15;font-weight:660;letter-spacing:-.65px}.page-subtitle{font-size:12px;color:#aebdb2;margin-top:4px}.page-head-right{align-self:flex-start;margin-top:5px}.operator-label{font:10px var(--mono);color:#a2ada5;border:1px solid var(--line);padding:6px 9px;border-radius:2px}
.panel{background:var(--panel);border:1px solid var(--line);border-radius:3px;min-width:0;box-shadow:none}.panel-head{padding:12px 14px;border-bottom:1px solid var(--row);display:flex;align-items:center;justify-content:space-between;gap:12px;min-height:48px}.panel-head p{font-size:11px;color:var(--muted);margin-top:2px}.panel-body{padding:16px}.panel-body.compact{padding:12px 14px}.panel-head.border-top{border-top:1px solid var(--line)}.text-link{font-size:11px;color:#9bcce0}.text-link:hover{text-decoration:underline}
.status-strip{display:grid;grid-template-columns:1.65fr repeat(4,1fr);align-items:stretch;min-height:70px;padding:10px 0;gap:0}.status-main{display:flex;flex-direction:column;justify-content:center;padding:0 20px}.status-heading{font-size:15px;display:flex;align-items:center;gap:6px;margin-bottom:3px}.status-heading .dot{width:9px;height:9px;margin-right:2px}.strip-cell{display:flex;flex-direction:column;gap:4px;justify-content:center;padding:0 17px;border-left:1px solid var(--line);min-width:0}.strip-cell:first-child{border-left:none}.strip-cell>span:first-child,.metric-label{color:#a9b7ac;font:10px/1.3 var(--mono);text-transform:uppercase;letter-spacing:.3px}.strip-cell strong{font-size:13px;line-height:1.3;font-weight:580;overflow-wrap:anywhere}.strip-cell small{color:var(--subtle);font-size:10px}.compact-strip{grid-template-columns:repeat(4,minmax(0,1fr))}.compact-strip .strip-cell:first-child{border:none}.zone-strip{grid-template-columns:repeat(6,minmax(0,1fr));min-height:76px}.zone-strip .strip-cell:first-child{border:none}
.status-strip{display:grid;grid-template-columns:1.65fr repeat(4,1fr);align-items:stretch;min-height:70px;padding:10px 0;gap:0}.status-main{display:flex;flex-direction:column;justify-content:center;padding:0 20px}.status-heading{font-size:15px;display:flex;align-items:center;gap:6px;margin-bottom:3px}.status-heading .dot{width:9px;height:9px;margin-right:2px}.strip-cell{display:flex;flex-direction:column;gap:4px;justify-content:center;padding:0 17px;border-left:1px solid var(--line);min-width:0}.strip-cell:first-child{border-left:none}.strip-cell>span:first-child,.metric-label{color:#a9b7ac;font:10px/1.3 var(--mono);text-transform:uppercase;letter-spacing:.3px}.strip-cell strong{font-size:13px;line-height:1.3;font-weight:580;overflow-wrap:anywhere}.strip-cell small{color:var(--subtle);font-size:10px}.compact-strip{grid-template-columns:repeat(5,minmax(0,1fr))}.compact-strip .strip-cell:first-child{border:none}.zone-strip{grid-template-columns:repeat(6,minmax(0,1fr));min-height:76px}.zone-strip .strip-cell:first-child{border:none}
.metrics-grid{display:grid;gap:9px;margin:13px 0}.metrics-grid.six{grid-template-columns:repeat(6,minmax(0,1fr))}.metrics-grid.four{grid-template-columns:repeat(4,minmax(0,1fr))}.metric{min-height:93px;display:flex;flex-direction:column;justify-content:center;padding:12px 14px}.metric strong{font-size:24px;font-weight:650;line-height:1.3;letter-spacing:.2px;margin-top:4px;white-space:nowrap}.metric small{font-size:11px;color:var(--muted);margin-top:3px}.metric-row{max-width:290px}
.chart-grid{display:grid;gap:10px;margin-top:12px}.chart-grid.triple{grid-template-columns:repeat(3,minmax(0,1fr))}.chart-card{padding-bottom:8px;min-height:256px}.chart-card .panel-head{border-bottom:none;padding:12px 14px 6px;align-items:flex-start}.chart-card canvas{display:block;width:calc(100% - 24px);height:169px;margin:7px 12px 0;image-rendering:auto}.chart-foot{padding:8px 14px 1px;font:10px var(--mono);color:#bdcbc0;display:flex;align-items:center;gap:7px;flex-wrap:wrap}.legend-dot{display:inline-block;width:13px;height:2px;background:#aaa;vertical-align:middle}.legend-dot.cyan{background:var(--cyan)}.legend-dot.amber{background:var(--amber)}.legend-dot.red{background:var(--red)}.live-mark{font:9px var(--mono);color:#789c83;white-space:nowrap}
.dashboard-lower{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:10px;margin-top:12px}.dashboard-lower.three-cards{margin-top:14px}.dashboard-lower>.panel{min-height:185px}.data-row{display:flex;justify-content:space-between;align-items:center;gap:12px;border-bottom:1px solid var(--row);padding:9px 0;min-height:34px;font-size:12px}.data-row:first-child{padding-top:4px}.data-row:last-child{border-bottom:none}.data-row span{color:#bac4bc;flex-shrink:0}.data-row strong{font-weight:550;text-align:right;color:#ecf2ed;max-width:67%;min-width:0;word-break:break-word}.data-row.mono{justify-content:flex-start}.barline{display:grid;grid-template-columns:100px minmax(0,1fr) 90px;align-items:center;gap:12px;padding:8px 0;font-size:11px}.barline strong{text-align:right;font:11px var(--mono)}.bar-track{display:block;height:8px;background:#29352f;border-radius:0;overflow:hidden}.bar-fill{display:block;height:100%;background:var(--green);width:0}.bar-fill.warn{background:var(--amber)}.bar-fill.danger{background:var(--red)}.bars-large{margin-top:15px}.bars-large .barline{padding:10px 0}.notice-inline{font-size:11px;color:#adbfae;background:#14201a;border-left:2px solid #739c71;padding:11px 14px;line-height:1.5}.notice{padding:11px 15px;border:1px solid #576951;background:#1b281e;color:#ddf0d8;border-radius:2px;margin-bottom:14px;display:flex;align-items:center;justify-content:space-between;gap:10px;font-size:12px;line-height:1.5}.notice.danger{background:#2b1c1c;color:#ffd2cb;border-color:#855a56}.notice.warn{background:#2d2519;color:#efd1a2;border-color:#756346}.notice-dismiss{border:none;background:none;color:inherit;font-size:18px;line-height:1;cursor:pointer}.empty{padding:28px 16px;text-align:center;color:var(--muted);font-size:12px}
.table-scroll{overflow-x:auto;scrollbar-color:#425049 transparent;scrollbar-width:thin}.data-table{border-collapse:collapse;table-layout:auto;width:100%;white-space:nowrap;font-size:12px}.data-table th{background:#121915;color:#a8b6ab;font:10px/1.35 var(--mono);text-transform:uppercase;letter-spacing:.45px;font-weight:500;text-align:left;padding:12px 13px;border-bottom:1px solid #455149}.data-table td{padding:9px 13px;border-bottom:1px solid var(--row);color:#d9e1da;height:38px;vertical-align:middle;max-width:630px;overflow-wrap:anywhere}.data-table tbody tr:hover td{background:#17211b}.data-table tbody tr:last-child td{border-bottom:none}.data-table .empty{text-align:center;padding:26px;white-space:normal}.data-table .entity,.entity{color:#f1f7f1;font-weight:610}.entity:hover{color:var(--green)}.data-table td.rdata{max-width:560px;white-space:normal;word-break:break-word}.tag{display:inline-block;font:10px/1.35 var(--mono);border:1px solid #647b55;color:#bbddac;padding:2px 6px;border-radius:2px;text-transform:uppercase;letter-spacing:.2px}.tag.blue{border-color:#597e8d;color:#9ccfe1}.tag.red{border-color:#915c58;color:#eda9a2}.tag.amber{border-color:#917245;color:#f2cb84}.tag.muted-tag{border-color:#546158;color:#a3b0a5}.table-footer{border-top:1px solid var(--row);padding:12px 14px;display:flex;gap:10px;align-items:center;justify-content:space-between;color:var(--muted);font-size:11px;min-height:49px}.pagination-ui{display:flex;align-items:center;gap:6px}
.toolbar{display:flex;align-items:center;justify-content:space-between;gap:14px;padding:13px 13px;border-bottom:1px solid var(--line);min-height:55px}.toolbar-form{display:flex;gap:9px;align-items:center;flex-wrap:wrap}.toolbar-end{display:flex;align-items:center;gap:8px;flex-shrink:0}.toolbar-title h2{margin-bottom:3px}.toolbar-title p{color:var(--muted);font-size:11px}.field{width:100%;min-height:33px;border:1px solid #48564c;border-radius:2px;color:#f0f4ed;background:var(--field);padding:7px 11px;outline:none;box-shadow:none}.field:focus{border-color:#a4c493;box-shadow:0 0 0 1px #456d51}.field::placeholder{color:#77857c;opacity:1}.field[type=number]{appearance:textfield}.field[type=number]::-webkit-inner-spin-button{-webkit-appearance:none}.field-search{width:290px}.field-select{width:145px;cursor:pointer;padding-right:20px}.toolbar .field{min-height:31px}.field-label{font-size:12px;font-weight:570;color:#cfd8cd;display:block;margin-bottom:7px}textarea.field{resize:vertical;line-height:1.6}select.field{background-color:#0d120f}.required{color:var(--amber)}
.form-layout{display:grid;grid-template-columns:minmax(0,1.7fr) minmax(280px,.78fr);gap:13px;align-items:start}.policy-layout{grid-template-columns:minmax(0,1.5fr) minmax(270px,1fr)}.form-body{padding:18px}.form-columns{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:14px}.field-row{margin-bottom:18px}.field-row:last-child{margin-bottom:0}.field-row small{font-size:11px;color:var(--subtle);display:block;margin-top:6px}.form-actions{display:flex;gap:9px;align-items:center;justify-content:flex-end;padding-top:18px;margin-top:11px;border-top:1px solid var(--row)}.form-actions .btn-ui{min-width:90px}.readout{display:flex;align-items:center;background:#19211b;color:#c7d1c7}.guide .panel-body p{font-size:12px;line-height:1.6;color:#b6c3b8}.guide .panel-body .data-row{font-size:11px}.guide h3{font-size:12px;margin-bottom:9px}.mode-tabs{display:flex;border-bottom:1px solid var(--line);padding:0 14px}.code-input{min-height:250px;font:12px/1.65 var(--mono)}.code-block{background:#090f0b;border:1px solid #313f33;border-radius:2px;padding:13px;overflow:auto;max-width:100%}.code-block pre,pre.code-block{margin:0;color:#bfdbc7;font:11px/1.6 var(--mono);white-space:pre-wrap;overflow-wrap:anywhere}.code-example{padding:10px;background:#0e1711;border:1px solid #314138;font-size:11px;line-height:2!important;color:#cbe3cd!important}.target-summary{border:1px solid #465147;background:#151e16;padding:10px 15px;margin:15px 0 20px}.confirmation-box{max-width:720px;margin:12px auto}.confirmation-box .panel-body>p{color:#becabf;line-height:1.7;margin:8px 0 20px}.confirmation-box .field{max-width:100%}.border-top{border-top:1px solid var(--line)!important}.operations-grid{display:grid;grid-template-columns:minmax(0,1.5fr) minmax(250px,.9fr);gap:13px;margin-top:14px}.operation{display:flex;justify-content:space-between;align-items:center;gap:16px;padding:15px 4px;border-bottom:1px solid var(--row)}.operation:last-child{border:0}.operation strong{display:block;font-size:12px}.operation small{display:block;font-size:11px;color:#9eada3;margin-top:4px}.operation .btn-ui{flex-shrink:0}.tabs{display:flex;align-items:center;gap:5px;margin:12px 0 14px;border-bottom:1px solid #374039;overflow-x:auto;white-space:nowrap}.tab{padding:11px 18px;display:inline-block;border-bottom:2px solid transparent;color:#bfc9bf;font-size:12px}.tab:hover{color:#fff;background:#171f1a}.tab.active{border-bottom-color:var(--green);color:#f6fff2;font-weight:640}.section-actions{display:flex;gap:9px;margin-top:14px}.pool-head{display:flex;align-items:center;justify-content:space-between;gap:12px;padding:12px 15px;background:#171e19;border-bottom:1px solid var(--line)}.pool-head h3{margin-bottom:3px}.pool-head+.table-scroll{margin-bottom:5px}.response-summary{display:flex;padding:15px 0;border-top:1px solid var(--line);border-bottom:1px solid var(--line);margin:0 16px;gap:0}.response-summary .strip-cell{flex:1}.response-summary .strip-cell:first-child{border-left:none}.danger-panel{border-color:#65413d}
.footer{display:flex;gap:18px;justify-content:space-between;border-top:1px solid #202a23;color:#697b6e;font-size:10px;padding-top:17px;margin-top:22px}.footer span{color:#68766c}
.footer{display:flex;justify-content:flex-end;text-align:right;border-top:1px solid #202a23;color:#697b6e;font-size:10px;padding-top:17px;margin-top:22px}
.mobile-menu{border:1px solid var(--line);background:#142019;color:#fff;padding:5px 9px;border-radius:2px}.sidebar-overlay{display:none}
.login-body{display:grid;place-items:center;min-height:100vh;background:#060908;padding:20px}.login-panel{width:min(440px,100%);background:#111613;border:1px solid #354237;border-radius:3px;padding:32px}.login-brand{font-size:29px;letter-spacing:-1px;font-weight:750;padding-bottom:24px;border-bottom:1px solid var(--line)}.overline{font:10px var(--mono);letter-spacing:1px;color:var(--green);margin-top:23px;margin-bottom:9px}.login-panel h1{font-size:27px;margin-bottom:8px}.login-panel .muted{color:var(--muted);line-height:1.6}.login-help{font-size:11px;color:#829185;line-height:1.6;margin:23px 0 0}
.login-body{display:grid;place-items:center;min-height:100vh;background:#060908;padding:20px}.login-panel{width:min(440px,100%);background:#111613;border:1px solid #354237;border-radius:3px;padding:32px}.login-brand{font-size:29px;letter-spacing:-1px;font-weight:750;padding-bottom:20px;border-bottom:1px solid var(--line)}.login-panel h1{font-size:27px;margin-top:22px;margin-bottom:8px}.login-panel .muted{color:var(--muted);line-height:1.6}
@media(max-width:1570px){.metrics-grid.six{grid-template-columns:repeat(3,minmax(0,1fr))}.chart-card canvas{height:160px}.barline{grid-template-columns:75px minmax(0,1fr) 72px}.strip-cell{padding-left:12px;padding-right:12px}}
@media(max-width:1130px){.shell{grid-template-columns:190px minmax(0,1fr)}.dashboard-lower{grid-template-columns:repeat(2,minmax(0,1fr))}.chart-grid.triple{grid-template-columns:repeat(2,minmax(0,1fr))}.form-layout{grid-template-columns:1fr}.toolbar{flex-wrap:wrap}.status-strip{grid-template-columns:repeat(3,minmax(0,1fr))}.status-main{min-height:53px}.zone-strip{grid-template-columns:repeat(3,minmax(0,1fr))}.operations-grid{grid-template-columns:1fr}}
@media(max-width:820px){.shell{grid-template-columns:1fr}.sidebar{position:fixed;transform:translateX(-100%);width:235px;transition:transform .12s ease;box-shadow:0 0 0 transparent}.sidebar.open{transform:translateX(0)}.sidebar-overlay.open{display:block;position:fixed;inset:0;background:#000b;z-index:20}.mobile-menu{display:block}.top-actions .tool-button span{display:none}.tool-button{padding:6px}.topbar{padding:0 12px}.content{padding:16px 13px}.page-head-right{display:none}.metrics-grid.six{grid-template-columns:repeat(2,minmax(0,1fr))}.status-strip,.compact-strip{grid-template-columns:repeat(2,minmax(0,1fr))}.status-main{grid-column:span 2}.status-strip .strip-cell:nth-child(2n){border-left:0}.field-search{width:180px}.footer span{display:none}}
@media(max-width:820px){.shell{grid-template-columns:1fr}.sidebar{position:fixed;transform:translateX(-100%);width:235px;transition:transform .12s ease;box-shadow:0 0 0 transparent}.sidebar.open{transform:translateX(0)}.sidebar-overlay.open{display:block;position:fixed;inset:0;background:#000b;z-index:20}.mobile-menu{display:block}.top-actions .tool-button span{display:none}.tool-button{padding:6px}.topbar{padding:0 12px}.content{padding:16px 13px}.page-head-right{display:none}.metrics-grid.six{grid-template-columns:repeat(2,minmax(0,1fr))}.status-strip,.compact-strip{grid-template-columns:repeat(2,minmax(0,1fr))}.status-main{grid-column:span 2}.status-strip .strip-cell:nth-child(2n){border-left:0}.field-search{width:180px}}
@media(max-width:540px){.page-head h1{font-size:23px}.dashboard-lower,.chart-grid.triple,.metrics-grid.four,.metrics-grid.six,.form-columns{grid-template-columns:1fr}.toolbar-form{width:100%}.field-search{flex:1;min-width:150px}.toolbar-end{width:100%;justify-content:flex-end}.status-strip{grid-template-columns:repeat(2,minmax(0,1fr))}.zone-strip{grid-template-columns:repeat(2,minmax(0,1fr))}.strip-cell{padding:9px 12px}.status-main{padding:8px 12px}.page-subtitle{font-size:11px}.operator-label,.desktop-only{display:none}.chart-card canvas{height:165px}}
@media(prefers-reduced-motion:reduce){*,*::before,*::after{animation:none!important;transition:none!important;scroll-behavior:auto!important}}
/* Optional multi-server control room. RustProxy-inspired flat OLED components. */
.node-picker{display:flex;align-items:center;gap:7px;margin-right:8px;max-width:300px}
.node-picker-label{font:10px var(--mono);color:var(--subtle);letter-spacing:.5px}
.node-picker .compact-field{min-width:155px;max-width:235px;width:100%;height:31px;padding:5px 24px 5px 8px;font-size:11px;text-overflow:ellipsis}
.field.compact-field{min-height:31px}
/* Selected target is explicit; fleet metrics visibly distinguish multi-node scope. */
.active-server-context{display:flex;align-items:center;flex-wrap:wrap;gap:9px;margin:-7px 0 17px;padding:9px 13px;background:#0d1511;border:1px solid #3f5146;border-left:2px solid var(--green);color:#d5e1d7;font-size:11px}
.active-server-context strong{font-size:12px;color:#fff}
.context-label{font:10px var(--mono);letter-spacing:.35px;color:var(--green)}
.context-label .dot{margin-right:3px}
.context-role{color:#a0bbaa}
.context-target{color:#c0d0c4;overflow-wrap:anywhere}
.context-hint{color:var(--subtle);margin-left:auto}
@media(max-width:1160px){.context-hint{width:100%;margin-left:0}}
@media(max-width:820px){.node-picker{gap:4px;margin-right:2px}.node-picker .compact-field{min-width:96px;max-width:154px}}
@media(max-width:540px){.node-picker-label{display:none}.node-picker .compact-field{min-width:82px;max-width:125px}}
.fleet-summary{display:flex;align-items:stretch;gap:0;padding:0;margin-bottom:15px;min-height:83px}
.fleet-status{flex:2;display:flex;align-items:center;padding:16px 20px;gap:8px}
.fleet-status strong{font-size:18px;letter-spacing:-.2px}
.fleet-status small{display:block;color:var(--muted);font-size:11px;margin-top:4px}
.fleet-stat{flex:1;min-width:120px;display:flex;flex-direction:column;justify-content:center;border-left:1px solid var(--line);padding:15px 18px}
.fleet-stat span{color:var(--subtle);font:10px var(--mono);letter-spacing:.35px}
.fleet-stat strong{font-size:15px;font-weight:620;margin-top:5px}
.fleet-toolbar{display:flex;align-items:center;justify-content:space-between;gap:16px;margin:17px 0 10px}
.fleet-toolbar h2{font-size:16px}
.fleet-toolbar p{margin-top:4px}
.topology-layout{display:grid;grid-template-columns:minmax(280px,1fr) 94px minmax(300px,1fr);gap:8px;align-items:stretch}
.topology-column{display:flex;flex-direction:column;gap:9px;min-width:0}
.topology-caption{font:10px var(--mono);color:var(--subtle);letter-spacing:.6px;padding:2px 4px 5px}
.topology-connector{display:flex;flex-direction:column;align-items:center;justify-content:center;color:var(--subtle);gap:7px}
.topology-connector span{width:1px;flex:1;background:var(--line);min-height:26px}.topology-connector small{font:10px var(--mono);color:var(--amber);white-space:nowrap}
.node-card{padding:16px 20px;min-height:194px;display:flex;flex-direction:column;justify-content:space-between}
.node-card-secondary{min-height:173px}
.node-card-top{display:flex;align-items:center;justify-content:space-between;gap:10px}
.node-role{font:10px var(--mono);letter-spacing:.45px;padding:4px 6px;border:1px solid var(--line);color:var(--muted);border-radius:2px}
.node-role.primary{border-color:#668364;color:var(--green)}.node-role.secondary{border-color:#4e7780;color:var(--cyan)}
.node-health{font-size:12px;text-transform:capitalize;color:var(--muted)}
.node-card h3{font-size:19px;letter-spacing:-.2px;font-weight:650;margin:9px 0 3px}
.node-address{color:var(--subtle);font-size:11px;overflow-wrap:anywhere}
.node-facts{display:flex;gap:0;border-top:1px solid var(--line);border-bottom:1px solid var(--line);margin-top:11px}
.node-facts>div{flex:1;min-width:0;padding:9px 8px;border-right:1px solid var(--line)}.node-facts>div:first-child{padding-left:0}.node-facts>div:last-child{border-right:0;padding-right:0}
.node-facts small{color:var(--subtle);font-size:10px;display:block}.node-facts strong{font-family:var(--mono);font-size:13px;display:block;margin-top:4px}
.node-error{color:var(--red);font-size:11px;overflow-wrap:anywhere;padding-top:8px}
.node-actions{display:flex;align-items:center;justify-content:space-between;gap:10px;padding-top:10px}.node-actions form,.row-actions form{margin:0}
.node-unassigned{padding:14px;margin-top:9px;display:flex;align-items:center;gap:18px}
.topology-disclaimer{font-size:11px;line-height:1.6;color:var(--subtle);margin:10px 3px 14px}
.role-form{display:flex;align-items:center;gap:6px}.role-form .compact-field{min-width:120px;max-width:140px;padding:5px 9px;font-size:12px}.role-form .btn-ui{padding:5px 7px}
.compare-field{min-width:260px;flex:1;max-width:560px}.compare-field label{display:block;margin-bottom:5px}.comparison-reference{padding:12px 16px;background:var(--panel-alt);border-top:1px solid var(--line);font-size:12px;color:var(--muted)}
@media(max-width:1080px){.topology-layout{grid-template-columns:minmax(230px,1fr) 50px minmax(240px,1fr)}.topology-connector small{font-size:8px}.node-picker-label{display:none}.node-picker{max-width:170px}.node-picker .compact-field{min-width:100px}}
@media(max-width:750px){.topology-layout{grid-template-columns:1fr}.topology-connector{flex-direction:row;min-height:28px}.topology-connector span{width:100%;height:1px;min-height:1px}.topology-column{gap:8px}.fleet-summary{flex-wrap:wrap}.fleet-status{flex:1 1 100%}.fleet-stat{flex:1 1 33%;border-top:1px solid var(--line)}.fleet-toolbar{align-items:start;flex-direction:column}.node-picker{max-width:140px}.node-picker .compact-field{min-width:88px}}
/* Multi-server forms reuse the original compact input system. */
.form-card{max-width:900px}.form-card .panel-body{padding:18px 20px}.form-card .field-row label{display:block;margin-bottom:7px;color:var(--text);font-weight:580}.form-card .field-row .field{width:100%}.form-card .required{color:var(--amber)}.form-card .field-row{margin-bottom:19px}.form-card .field-row small{display:block;font-size:11px;color:var(--subtle);margin-top:5px;line-height:1.5}.form-card .form-actions{margin-top:26px}
.compare-field{margin:0}.compare-field input{width:100%}.node-card .text-link{font-size:11px}
/* Optional fleet settings: low-noise, standard OLED control row. */
.panel-preferences{margin-bottom:1px}
.preference-body{display:flex;align-items:center;justify-content:space-between;gap:28px;padding:20px 16px}
.preference-label{display:block;max-width:820px;cursor:pointer}
.preference-title{display:block;font-size:13px;font-weight:640;color:var(--text);margin-bottom:5px}
.preference-description{display:block;font-size:12px;color:var(--muted);line-height:1.6}
.preference-controls{display:flex;align-items:center;gap:15px;flex-shrink:0}
.preference-switch{display:flex;align-items:center;gap:8px;cursor:pointer;color:var(--muted);font-size:12px}
.preference-switch input{width:17px;height:17px;accent-color:var(--green);cursor:pointer}
.preference-note{border-top:1px solid var(--line);padding:12px 16px;color:var(--subtle);font-size:11px;line-height:1.6}
.preference-note strong{color:var(--muted)}
@media(max-width:850px){.preference-body{align-items:flex-start;flex-direction:column;gap:16px}.preference-controls{width:100%;justify-content:space-between}}
/* Fleet Metrics: matching RustProxy-inspired OLED density, no decorative UI. */
.metrics-mode-bar{display:flex;align-items:center;justify-content:space-between;gap:18px;padding:13px 15px;margin-bottom:13px;background:var(--panel)}
.metrics-mode-description{display:flex;flex-direction:column;gap:4px;min-width:0}
.metrics-mode-description strong{font-size:14px;line-height:1.3}
.metrics-mode-description small{font-size:11px;color:var(--muted)}
.metrics-mode-tabs{display:inline-flex;align-items:center;gap:2px;padding:3px;border:1px solid var(--line);background:var(--field);flex-shrink:0}
.metrics-mode-tabs a{color:var(--muted);font-size:12px;padding:8px 17px;border:1px solid transparent;text-align:center;min-width:90px}
.metrics-mode-tabs a:hover{background:#1e2923;color:var(--text)}
.metrics-mode-tabs a.is-active{background:var(--nav-active);border-color:#5a7a5d;color:#e8f4e3;font-weight:650}
.fleet-coverage{display:flex;align-items:center;justify-content:space-between;gap:12px;padding:12px 16px;min-height:53px;margin:12px 0}
.fleet-coverage-main{display:flex;gap:9px;align-items:center;white-space:nowrap;font-size:12px}
.fleet-coverage-description{color:var(--muted);font-size:11px;line-height:1.5;text-align:right}
.fleet-coverage .dot{margin-right:0}
.metric .metric-text{font-size:19px;color:var(--cyan);white-space:normal}
.fleet-swatch{display:inline-block;width:12px;height:3px;vertical-align:middle;margin-right:9px;background:var(--cyan)}
.fleet-color-0{background:#72cfe1}.fleet-color-1{background:#f1b42b}.fleet-color-2{background:#a5d996}.fleet-color-3{background:#ba9be6}.fleet-color-4{background:#e98b87}.fleet-color-5{background:#85a8ff}.fleet-color-6{background:#e0bf9a}.fleet-color-7{background:#75d3ad}.fleet-color-8{background:#d9a6ce}.fleet-color-9{background:#d1cc83}.fleet-color-10{background:#b4d5e9}.fleet-color-11{background:#b48c7e}.fleet-color-12{background:#a5bb7f}.fleet-color-13{background:#cc92a1}.fleet-color-14{background:#8fb5b3}.fleet-color-15{background:#c6bbd5}
.fleet-methodology{font-size:11px}
@media(max-width:900px){.metrics-mode-bar{flex-direction:column;align-items:stretch}.metrics-mode-tabs{align-self:flex-start}.fleet-coverage{align-items:flex-start;flex-direction:column}.fleet-coverage-description{text-align:left}}
@media(max-width:540px){.metrics-mode-tabs{width:100%}.metrics-mode-tabs a{flex:1;min-width:0;padding:9px}.fleet-coverage-main{flex-wrap:wrap;white-space:normal}}
+9
View File
@@ -9,6 +9,15 @@
cover?.addEventListener('click', close);
document.addEventListener('keydown', e => {if(e.key === 'Escape') close();});
document.querySelectorAll('.notice-dismiss').forEach(el => el.addEventListener('click', () => el.closest('.notice')?.remove()));
// Strict CSP disallows inline onchange handlers. The server selector
// submits the CSRF-protected form immediately on selection change.
document.querySelectorAll('select[data-switch-server]').forEach(select => {
select.addEventListener('change', () => {
if (!select.form || !select.value) return;
if (typeof select.form.requestSubmit === 'function') select.form.requestSubmit();
else select.form.submit();
});
});
document.querySelectorAll('.bar-fill[data-count]').forEach(bar => {
const count = Number(bar.dataset.count), total = Number(bar.dataset.total);
const ratio = Number.isFinite(count) && Number.isFinite(total) && total > 0 ? 100 * count / total : 0;
+137 -51
View File
@@ -1,55 +1,141 @@
/* Small, dependency-free canvas telemetry renderer.
* Draws only measured, non-synthetic EasyDNS API sample history.
* A 15-second backend poll stores samples in process memory. */
/* EasyDNS telemetry charts. Source: authenticated Go panel samples of the
* existing EasyDNS GET /api/v1/stats endpoint. There is no synthetic history.
* Fleet aggregate QPS is server-aligned and requires complete coverage. */
(() => {
'use strict';
const COLORS={cyan:'#72cfe1',amber:'#f1b42b',red:'#ec8588',grid:'#303a34',muted:'#8d9d91',text:'#dce6df'};
const chartTypes={
queries:{series:[['queryRate','Queries / s','cyan']],unit:'/s'},
cache:{series:[['cacheHitRate','Cache hit %','cyan']],unit:'%',range:[0,100]},
latency:{series:[['p50ms','p50','cyan'],['p95ms','p95','amber'],['p99ms','p99','red']],unit:'ms'},
blocked:{series:[['blocked','Blocked / s','amber']],unit:'/s'},
responses:{series:[['noerror','NOERROR','cyan'],['nxdomain','NXDOMAIN','amber'],['servfail','SERVFAIL','red']],unit:'/s'}
};
let samples=[];let lastPoll='';
function render(c){
const type=chartTypes[c.dataset.dnsChart];if(!type)return;
const dpr=Math.min(2,window.devicePixelRatio||1);
const box=c.getBoundingClientRect();if(box.width<30)return;
const width=box.width,height=box.height;
c.width=Math.round(width*dpr);c.height=Math.round(height*dpr);
const ctx=c.getContext('2d');if(!ctx)return;ctx.setTransform(dpr,0,0,dpr,0,0);ctx.clearRect(0,0,width,height);
const pad={left:49,right:12,top:10,bottom:25};const pw=Math.max(5,width-pad.left-pad.right),ph=Math.max(5,height-pad.top-pad.bottom);
const series=type.series.map(([key,label,color])=>({key,label,color:COLORS[color],vals:samples.map(s=>typeof s[key]==='number'&&Number.isFinite(s[key])?s[key]:null)}));
const observed=series.flatMap(x=>x.vals.filter(v=>v!==null));
ctx.font='10px ui-monospace,Consolas,monospace';ctx.textBaseline='middle';
if(samples.length<2||observed.length<2){ctx.fillStyle=COLORS.muted;ctx.textAlign='center';ctx.fillText('Collecting live samples…',width/2,height/2-2);ctx.fillText('First rate after 2 successful polls',width/2,height/2+15);return;}
let min=type.range?type.range[0]:0,max=type.range?type.range[1]:Math.max(...observed,0.001)*1.16;
if(!Number.isFinite(max)||max===min)max=min+1;
const x=i=>pad.left+pw*(i/Math.max(1,samples.length-1));
const y=v=>pad.top+ph*(1-(v-min)/(max-min));
ctx.textAlign='right';ctx.lineWidth=1;for(let tick=0;tick<=4;tick++){
const value=min+(max-min)*tick/4,py=y(value);
ctx.strokeStyle=COLORS.grid;ctx.setLineDash([2,4]);ctx.beginPath();ctx.moveTo(pad.left,py);ctx.lineTo(width-pad.right,py);ctx.stroke();
ctx.fillStyle=COLORS.muted;const label=max<=10?value.toFixed(1):Math.round(value).toString();ctx.fillText(label+type.unit,pad.left-8,py);
'use strict';
const COLORS = {cyan:'#72cfe1', amber:'#f1b42b', red:'#ec8588',grid:'#303a34',muted:'#8d9d91',text:'#dce6df'};
const NODE_COLORS = ['#72cfe1','#f1b42b','#a5d996','#ba9be6','#e98b87','#85a8ff','#e0bf9a','#75d3ad','#d9a6ce','#d1cc83','#b4d5e9','#b48c7e','#a5bb7f','#cc92a1','#8fb5b3','#c6bbd5'];
const chartTypes = {
queries:{series:[['queryRate','Queries / s','cyan']],unit:'/s'},
cache:{series:[['cacheHitRate','Cache hit %','cyan']],unit:'%',range:[0,100]},
latency:{series:[['p50ms','p50','cyan'],['p95ms','p95','amber'],['p99ms','p99','red']],unit:'ms'},
blocked:{series:[['blocked','Blocked / s','amber']],unit:'/s'},
responses:{series:[['noerror','NOERROR','cyan'],['nxdomain','NXDOMAIN','amber'],['servfail','SERVFAIL','red']],unit:'/s'},
nxdomain:{series:[['nxdomain','NXDOMAIN','amber']],unit:'/s'}
};
const root = document.querySelector('[data-metrics-mode]');
const mode = root?.dataset.metricsMode || 'single';
let telemetry = {samples:[], nodes:[]};
const canvases = [...document.querySelectorAll('canvas[data-dns-chart]')];
if (!canvases.length) return;
function asPoints(samples, key) {
return (Array.isArray(samples) ? samples : []).map(s => {
const time = Date.parse(s.time);
const value = s[key];
return {time, value: typeof value === 'number' && Number.isFinite(value) ? value : null};
}).filter(p => Number.isFinite(p.time));
}
ctx.setLineDash([]);ctx.textAlign='center';ctx.fillStyle=COLORS.muted;
[0,.25,.5,.75,1].forEach(p=>{const idx=Math.min(samples.length-1,Math.round(p*(samples.length-1)));const t=new Date(samples[idx].time);if(!Number.isNaN(t.getTime()))ctx.fillText(t.toLocaleTimeString(undefined,{hour:'2-digit',minute:'2-digit'}),x(idx),height-9);});
series.forEach(s=>{ctx.beginPath();ctx.strokeStyle=s.color;ctx.lineWidth=1.65;ctx.lineJoin='round';let connected=false;
s.vals.forEach((v,i)=>{if(v===null){connected=false;return;}const px=x(i),py=y(v);if(!connected){ctx.moveTo(px,py);connected=true;}else{ctx.lineTo(px,py);}});ctx.stroke();
function seriesFor(typeName) {
const kind = chartTypes[typeName];
if (!kind) return [];
const nodes = Array.isArray(telemetry.nodes) ? telemetry.nodes : [];
if (mode === 'split' || (mode === 'aggregate' && typeName === 'latency')) {
const key = mode === 'split'
? ({queries:'queryRate',responses:'noerror',cache:'cacheHitRate',latency:'p95ms',blocked:'blocked',nxdomain:'nxdomain'}[typeName])
: 'p95ms';
return nodes.map((n,i) => ({label: String(n.name || n.id || 'Server'), color: NODE_COLORS[i % NODE_COLORS.length], points: asPoints(n.samples, key)}));
}
return kind.series.map(([key,label,color]) => ({label, color:COLORS[color], points:asPoints(telemetry.samples, key)}));
}
function render(canvas) {
const type = chartTypes[canvas.dataset.dnsChart]; if (!type) return;
const rect = canvas.getBoundingClientRect();
if (rect.width < 30 || rect.height < 30) return;
const width = rect.width, height = rect.height, dpr = Math.min(2, window.devicePixelRatio || 1);
canvas.width = Math.round(width * dpr); canvas.height = Math.round(height * dpr);
const ctx = canvas.getContext('2d'); if (!ctx) return;
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
ctx.clearRect(0, 0, width, height);
const pad = {left:48,right:12,top:10,bottom:25};
const plotW = Math.max(5,width-pad.left-pad.right), plotH = Math.max(5,height-pad.top-pad.bottom);
const series = seriesFor(canvas.dataset.dnsChart);
const observed = series.flatMap(s => s.points.filter(p => p.value !== null));
ctx.font = '10px ui-monospace,Consolas,monospace'; ctx.textBaseline = 'middle';
if (observed.length === 0) {
ctx.fillStyle=COLORS.muted; ctx.textAlign='center';
ctx.fillText('Collecting live samples…',width/2,height/2-4);
ctx.fillText(mode === 'aggregate' ? 'All nodes must report fresh readings' : 'First rate after 2 successful polls',width/2,height/2+14);
return;
}
const times = series.flatMap(s => s.points.map(p=>p.time));
const start = Math.min(...times), end = Math.max(...times);
const timeSpan = Math.max(1000,end-start);
const x = t => pad.left + plotW * (t-start)/timeSpan;
const min = type.range ? type.range[0] : 0;
let max = type.range ? type.range[1] : Math.max(0.001,...observed.map(p=>p.value)) * 1.16;
if (!Number.isFinite(max) || max <= min) max = min+1;
const y = val => pad.top + plotH * (1 - (val-min)/(max-min));
ctx.textAlign = 'right'; ctx.lineWidth = 1;
for (let tick=0;tick<=4;tick++) {
const v=min+(max-min)*tick/4, py=y(v);
ctx.strokeStyle=COLORS.grid;ctx.setLineDash([2,4]);ctx.beginPath();ctx.moveTo(pad.left,py);ctx.lineTo(width-pad.right,py);ctx.stroke();
ctx.fillStyle=COLORS.muted;
ctx.fillText((max <= 10 ? v.toFixed(1) : Math.round(v).toString()) + type.unit,pad.left-8,py);
}
ctx.setLineDash([]);ctx.textAlign='center';ctx.fillStyle=COLORS.muted;
[0,.25,.5,.75,1].forEach(f=>{
const t=new Date(start+f*timeSpan);
ctx.fillText(t.toLocaleTimeString(undefined,{hour:'2-digit',minute:'2-digit'}),x(start+f*timeSpan),height-9);
});
series.forEach(s => {
ctx.beginPath(); ctx.strokeStyle=s.color; ctx.lineWidth=1.7; ctx.lineJoin='round';
let previous=null;
s.points.forEach(p => {
if (p.value===null) {previous=null;return;}
const px=x(p.time), py=y(p.value);
// A server outage may leave a long period without any samples. Do not
// draw a fabricated continuous line across a missing-data interval.
if (!previous || p.time-previous.time>30000) ctx.moveTo(px,py);
else ctx.lineTo(px,py);
previous=p;
});
ctx.stroke();
// A single measured rate is drawn as a point, never extended into a
// synthetic line or repeated as historical data.
const valid = s.points.filter(p=>p.value!==null);
if (valid.length === 1) {
ctx.beginPath();ctx.fillStyle=s.color;
ctx.arc(x(valid[0].time),y(valid[0].value),2.5,0,Math.PI*2);ctx.fill();
}
});
}
function updateLegends() {
if (mode === 'single') return; // Preserve original static per-metric legends.
document.querySelectorAll('[data-chart-legend]').forEach(el => {
const chartType=el.dataset.chartLegend;
const series=seriesFor(chartType);
el.replaceChildren();
series.forEach(s => {
const marker=document.createElement('span');
marker.className='legend-dot';marker.style.background=s.color;
const label=document.createElement('span');label.textContent=s.label;
el.append(marker,label);
});
if (mode==='aggregate' && chartType!=='latency') {
const scope=document.createElement('span');scope.className='subtle';
scope.textContent='Complete fleet samples only'; el.append(scope);
}
});
}
async function poll() {
try {
const path='/ui/telemetry?mode='+encodeURIComponent(mode);
const r=await fetch(path,{credentials:'same-origin',cache:'no-store',headers:{Accept:'application/json'}});
if(!r.ok || !(r.headers.get('content-type')||'').includes('json'))return;
const payload=await r.json();
if (mode !== 'single' && payload.mode !== mode) return;
telemetry={samples:Array.isArray(payload.samples)?payload.samples:[],nodes:Array.isArray(payload.nodes)?payload.nodes:[]};
updateLegends();canvases.forEach(render);
} catch (_) { // Keep last genuine readings; do not fill gaps with zeroes.
}
}
document.addEventListener('DOMContentLoaded',()=>{
const observer=new ResizeObserver(()=>canvases.forEach(render));
canvases.forEach(c=>observer.observe(c));
poll();setInterval(poll,15000);
});
}
async function poll(){
try{
const r=await fetch('/ui/telemetry',{credentials:'same-origin',cache:'no-store',headers:{Accept:'application/json'}});
if(!r.ok||!(r.headers.get('content-type')||'').includes('json'))return;
const data=await r.json();samples=Array.isArray(data.samples)?data.samples:[];lastPoll=data.lastPoll;
document.querySelectorAll('canvas[data-dns-chart]').forEach(render);
}catch(_){/* Missing data stays empty; never fabricate data. */}
}
document.addEventListener('DOMContentLoaded',()=>{
const canvases=document.querySelectorAll('canvas[data-dns-chart]');if(!canvases.length)return;
const observer=new ResizeObserver(()=>canvases.forEach(render));canvases.forEach(c=>observer.observe(c));
poll();setInterval(poll,15000);
});
})();
+13 -7
View File
@@ -3,14 +3,17 @@
<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<meta name="color-scheme" content="dark"><meta name="theme-color" content="#050706">
<title>{{.Title}} · EasyDNS</title>
<link rel="icon" href="/static/favicon.svg" type="image/svg+xml">
<link rel="stylesheet" href="/static/vendor/bootstrap.min.css"><link rel="stylesheet" href="/static/app.css">
<script defer src="/static/app.js"></script><script defer src="/static/charts.js"></script>
<link rel="icon" href="{{asset "favicon.svg"}}" type="image/svg+xml">
<link rel="stylesheet" href="{{asset "vendor/bootstrap.min.css"}}"><link rel="stylesheet" href="{{asset "app.css"}}">
<script defer src="{{asset "app.js"}}"></script><script defer src="{{asset "charts.js"}}"></script>
</head><body>
<div class="shell">
<aside class="sidebar" id="sidebar" aria-label="Primary navigation">
<div class="brand"><a href="/" aria-label="EasyDNS Overview">EasyDNS</a></div>
<div class="sidebar-content">
{{if .MultiServer}}<div class="nav-section">FLEET</div>
<nav class="sidenav" aria-label="Managed servers"><a {{if eq .Active "servers"}}class="active" aria-current="page"{{end}} href="/servers">Servers</a></nav>
{{end}}
<div class="nav-section">DNS</div>
<nav class="sidenav" aria-label="DNS"><a {{if eq .Active "overview"}}class="active" aria-current="page"{{end}} href="/">Overview</a><a {{if eq .Active "zones"}}class="active" aria-current="page"{{end}} href="/zones">Zones</a><a {{if eq .Active "query"}}class="active" aria-current="page"{{end}} href="/query">DNS lookup</a></nav>
<div class="nav-section">RESOLUTION &amp; POLICY</div>
@@ -18,17 +21,20 @@
<div class="nav-section">MONITORING &amp; SYSTEM</div>
<nav class="sidenav" aria-label="Monitoring"><a {{if eq .Active "cache"}}class="active" aria-current="page"{{end}} href="/cache">Cache</a><a {{if eq .Active "metrics"}}class="active" aria-current="page"{{end}} href="/metrics">Metrics</a><a {{if eq .Active "audit"}}class="active" aria-current="page"{{end}} href="/audit">Audit log</a><a {{if eq .Active "status"}}class="active" aria-current="page"{{end}} href="/status">Server status</a><a {{if eq .Active "configuration"}}class="active" aria-current="page"{{end}} href="/configuration">Configuration</a></nav>
</div>
<div class="sidebar-foot"><span class="indicator"></span> Local control panel <small>EasyDNS API connection</small></div>
<div class="sidebar-foot"><span class="indicator"></span> {{if .MultiServer}}Multi-server enabled<small>Active: {{.SelectedNode.Name}}</small>{{else}}Local control panel<small>EasyDNS API connection</small>{{end}}</div>
</aside>
<div class="workspace">
<header class="topbar"><button class="mobile-menu" type="button" id="menuToggle" aria-controls="sidebar" aria-expanded="false" aria-label="Open navigation">☰</button><div class="breadcrumbs">{{.Breadcrumb}}</div>
<div class="top-actions"><a href="https://git.linuxiarz.pl/gru/EasyDNS" target="_blank" rel="noopener noreferrer" class="tool-button"><svg class="ico"><use href="/static/icons.svg#book"/></svg><span>Documentation</span></a><a href="/audit" class="tool-button"><svg class="ico"><use href="/static/icons.svg#list"/></svg><span>Audit</span></a><a href="/configuration" class="tool-button"><svg class="ico"><use href="/static/icons.svg#settings"/></svg><span>Configuration</span></a><form method="post" action="/logout" class="inline"><input type="hidden" name="_csrf" value="{{.CSRF}}"><button type="submit" class="tool-button"><svg class="ico"><use href="/static/icons.svg#logout"/></svg><span>Sign out</span></button></form></div>
<div class="top-actions">{{if .MultiServer}}
<form action="/servers/select" method="post" class="node-picker" aria-label="Active EasyDNS server"><input type="hidden" name="_csrf" value="{{.CSRF}}"><input type="hidden" name="next" value="{{.CurrentPath}}"><label class="sr-only" for="active-node">Active server</label><span class="node-picker-label">SERVER</span><select class="field compact-field" id="active-node" name="server_id" data-switch-server>{{range .Nodes}}<option value="{{.ID}}" {{if eq .ID $.SelectedNode.ID}}selected{{end}}>{{.Name}} ({{.Role}})</option>{{end}}</select></form>
{{end}}<a href="https://git.linuxiarz.pl/gru/EasyDNS" target="_blank" rel="noopener noreferrer" class="tool-button"><svg class="ico"><use href="{{asset "icons.svg"}}#book"/></svg><span>Documentation</span></a><a href="/audit" class="tool-button"><svg class="ico"><use href="{{asset "icons.svg"}}#list"/></svg><span>Audit</span></a><a href="/configuration" class="tool-button"><svg class="ico"><use href="{{asset "icons.svg"}}#settings"/></svg><span>Configuration</span></a><form method="post" action="/logout" class="inline"><input type="hidden" name="_csrf" value="{{.CSRF}}"><button type="submit" class="tool-button"><svg class="ico"><use href="{{asset "icons.svg"}}#logout"/></svg><span>Sign out</span></button></form></div>
</header>
<main class="content" id="main">
<div class="page-head"><div class="page-head-left"><p class="eyebrow"><span class="indicator"></span> EasyDNS control room</p><h1>{{.Title}}</h1><p class="page-subtitle">{{.Subtitle}}</p></div><div class="page-head-right"><span class="operator-label">{{.User}}</span></div></div>
<div class="page-head"><div class="page-head-left"><p class="eyebrow"><span class="indicator"></span> {{if .MultiServer}}Managing {{.SelectedNode.Name}} · {{.SelectedNode.Role}} label{{else}}EasyDNS control room{{end}}</p><h1>{{.Title}}</h1><p class="page-subtitle">{{.Subtitle}}</p></div><div class="page-head-right"><span class="operator-label">{{.User}}</span></div></div>
{{if and .MultiServer (ne .Active "servers")}}<div class="active-server-context" role="status">{{if and (eq .Active "metrics") (ne .Data.MetricsMode "single")}}<span class="context-label"><span class="dot ok"></span>FLEET METRICS</span><strong>All configured servers</strong><span class="context-hint">Charts compare servers; the top selector still controls other DNS pages.</span>{{else}}<span class="context-label"><span class="dot ok"></span>ACTIVE SERVER</span><strong>{{.SelectedNode.Name}}</strong><span class="context-role">{{.SelectedNode.Role}} label</span><span class="context-target mono" title="EasyDNS API target">{{.SelectedNode.URL}}</span><span class="context-hint">All DNS data and actions on this page target this server only.</span>{{end}}</div>{{end}}
{{if .Message}}<div class="notice {{.MessageType}}" role="alert"><span>{{.Message}}</span><button class="notice-dismiss" type="button" aria-label="Dismiss notice">×</button></div>{{end}}
{{template "content" .}}
<footer class="footer">EasyDNS · independent management panel <span>Only verified EasyDNS API operations are available</span></footer>
<footer class="footer">EasyDNS · independent management panel</footer>
</main>
</div>
</div>
@@ -1,3 +1,3 @@
{{define "content"}}<div class="status-strip panel compact-strip"><div class="strip-cell"><span>CONFIGURED LISTS</span><strong>{{len .Data.Blocklists.Lists}}</strong></div><div class="strip-cell"><span>LOADED LISTS</span><strong>{{len .Data.Blocklists.Loaded}}</strong></div><div class="strip-cell"><span>ACTIVE RULES</span><strong>{{int .Data.Blocklists.Rules}}</strong></div><div class="strip-cell"><span>UPDATE INTERVAL</span><strong>{{.Data.Blocklists.UpdateInterval}}</strong></div></div>
<section class="panel mt-panel"><div class="toolbar"><div class="toolbar-title"><h2>Configured feeds</h2><p>Rule sources and their effective enablement.</p></div><a class="btn-ui btn-primary-ui" href="/blocklists/new"><svg class="ico"><use href="/static/icons.svg#plus"/></svg>Add rule</a></div><div class="table-scroll"><table class="data-table"><thead><tr><th>NAME</th><th>CATEGORY</th><th>SOURCE FILE</th><th>REMOTE URL</th><th>ENABLED</th><th>UPDATE INTERVAL</th></tr></thead><tbody>{{range .Data.Blocklists.Lists}}<tr><td class="entity">{{string (get . "name")}}</td><td>{{string (get . "category")}}</td><td class="mono">{{string (get . "file")}}</td><td class="mono break-any">{{string (get . "url")}}</td><td>{{string (get . "enabled")}}</td><td class="mono">{{string (get . "update_interval")}}</td></tr>{{else}}<tr><td class="empty" colspan="6">No blocklist feeds configured.</td></tr>{{end}}</tbody></table></div></section>
<section class="panel mt-panel"><div class="toolbar"><div class="toolbar-title"><h2>Configured feeds</h2><p>Rule sources and their effective enablement.</p></div><a class="btn-ui btn-primary-ui" href="/blocklists/new"><svg class="ico"><use href="{{asset "icons.svg"}}#plus"/></svg>Add rule</a></div><div class="table-scroll"><table class="data-table"><thead><tr><th>NAME</th><th>CATEGORY</th><th>SOURCE FILE</th><th>REMOTE URL</th><th>ENABLED</th><th>UPDATE INTERVAL</th></tr></thead><tbody>{{range .Data.Blocklists.Lists}}<tr><td class="entity">{{string (get . "name")}}</td><td>{{string (get . "category")}}</td><td class="mono">{{string (get . "file")}}</td><td class="mono break-any">{{string (get . "url")}}</td><td>{{string (get . "enabled")}}</td><td class="mono">{{string (get . "update_interval")}}</td></tr>{{else}}<tr><td class="empty" colspan="6">No blocklist feeds configured.</td></tr>{{end}}</tbody></table></div></section>
<section class="panel mt-panel"><div class="panel-head"><div><h2>Remote list sync state</h2><p>Read-only update and download results</p></div></div><div class="table-scroll"><table class="data-table"><thead><tr><th>NAME</th><th>LAST SUCCESS</th><th>LAST ATTEMPT</th><th>RESULT</th><th>MESSAGE</th></tr></thead><tbody>{{range $key,$v:=.Data.Blocklists.State}}<tr><td class="mono">{{$key}}</td><td class="mono">{{string (get $v "last_success")}}</td><td class="mono">{{string (get $v "last_attempt")}}</td><td>{{string (get $v "ok")}}</td><td>{{string (get $v "message")}}</td></tr>{{else}}<tr><td class="empty" colspan="5">No remote feed sync state available.</td></tr>{{end}}</tbody></table></div></section><div class="notice-inline mt-panel">REST can add individual block rules, but cannot list/remove them individually or force a remote feed download.</div>{{end}}
@@ -1,4 +1,15 @@
{{define "content"}}<div class="form-layout policy-layout"><section class="panel"><div class="panel-head"><div><h2>Visible runtime configuration</h2><p>Selected runtime parameters exposed by EasyDNS</p></div></div><div class="panel-body compact"><div class="data-row"><span>Server mode</span><strong>{{.Data.Status.Mode}}</strong></div><div class="data-row"><span>Version</span><strong>{{.Data.Status.Version}}</strong></div><div class="data-row"><span>Default resolution</span><strong>{{.Data.Status.Roles.DefaultResolution}}</strong></div><div class="data-row"><span>DNSSEC validation</span><strong>{{string .Data.Status.DNSSECValidation}}</strong></div><div class="data-row"><span>Block action</span><strong>{{string (get .Data.Policies.Policy "block_action")}}</strong></div><div class="data-row"><span>API allowed clients</span><strong>{{join .Data.Policies.APIAllowedClients ", "}}</strong></div><div class="data-row"><span>Recursion allowed clients</span><strong>{{join .Data.Policies.RecursionAllowedClients ", "}}</strong></div></div>
{{define "content"}}
{{if .CanEditMultiServer}}
<section class="panel panel-preferences" id="multi-server-preference">
<div class="panel-head"><div><h2>Panel settings · Multi-server management</h2><p>Optional management of multiple independent EasyDNS installations.</p></div><span class="tag {{if .MultiServer}}green{{else}}muted-tag{{end}}">{{if .MultiServer}}ENABLED{{else}}DISABLED BY DEFAULT{{end}}</span></div>
<form method="post" action="/configuration/multi-server" class="preference-body"><input type="hidden" name="_csrf" value="{{.CSRF}}">
<label class="preference-label" for="enable-multiserver"><span class="preference-title">Enable multi-server management</span><span class="preference-description">Show the Servers topology, switch between installations and compare zone serials. When disabled, the panel works exactly as before with your local EasyDNS instance.</span></label>
<div class="preference-controls"><label class="preference-switch" for="enable-multiserver"><input type="checkbox" id="enable-multiserver" name="enabled" value="on" {{if .MultiServer}}checked{{end}}><span>Enable</span></label><button type="submit" class="btn-ui btn-primary-ui">Save panel setting</button></div>
</form>
<div class="preference-note">This setting affects the <strong>web panel only</strong>. No DNS server configuration, AXFR/IXFR links or NOTIFY targets are changed. Previously saved remote connections are kept when the option is disabled. Remote APIs require HTTPS by default. Private-network HTTP is available only with EASYDNS_UI_ALLOW_INSECURE_HTTP=true; bearer tokens would then travel without encryption.</div>
</section>
{{end}}
<div class="form-layout policy-layout{{if .CanEditMultiServer}} mt-panel{{end}}"><section class="panel"><div class="panel-head"><div><h2>Visible runtime configuration</h2><p>Selected runtime parameters exposed by EasyDNS</p></div></div><div class="panel-body compact"><div class="data-row"><span>Server mode</span><strong>{{.Data.Status.Mode}}</strong></div><div class="data-row"><span>Version</span><strong>{{.Data.Status.Version}}</strong></div><div class="data-row"><span>Default resolution</span><strong>{{.Data.Status.Roles.DefaultResolution}}</strong></div><div class="data-row"><span>DNSSEC validation</span><strong>{{string .Data.Status.DNSSECValidation}}</strong></div><div class="data-row"><span>Block action</span><strong>{{string (get .Data.Policies.Policy "block_action")}}</strong></div><div class="data-row"><span>API allowed clients</span><strong>{{join .Data.Policies.APIAllowedClients ", "}}</strong></div><div class="data-row"><span>Recursion allowed clients</span><strong>{{join .Data.Policies.RecursionAllowedClients ", "}}</strong></div></div>
<div class="panel-head border-top"><div><h2>Hot reload</h2><p>Reload configuration from disk. EasyDNS reports errors and preserves prior active configuration.</p></div></div>
<form method="post" action="/configuration/reload" class="form-body"><input type="hidden" name="_csrf" value="{{.CSRF}}"><label class="field-label" for="reloadConfirm">Type RELOAD to confirm</label><input class="field mono" id="reloadConfirm" name="confirm" required pattern="RELOAD" autocomplete="off" placeholder="RELOAD"><div class="form-actions"><button class="btn-ui btn-primary-ui" type="submit"><svg class="ico"><use href="/static/icons.svg#refresh"/></svg>Reload EasyDNS configuration</button></div></form></section>
<aside class="panel guide"><div class="panel-head"><h2>What this panel cannot change</h2></div><div class="panel-body"><p>The REST API does not expose arbitrary configuration file editing, token rotation, server restarts, listener updates, ACL edits or rate limiter changes.</p><div class="notice-inline">EasyDNS creates <span class="mono">control.token</span> itself when its TCP API is enabled. The Go process reads that file server-side. It is never sent to your browser.</div><p class="mt-3 muted">This page never displays the token or pretends to modify local configuration.</p></div></aside></div>{{end}}
<form method="post" action="/configuration/reload" class="form-body"><input type="hidden" name="_csrf" value="{{.CSRF}}"><label class="field-label" for="reloadConfirm">Type RELOAD to confirm</label><input class="field mono" id="reloadConfirm" name="confirm" required pattern="RELOAD" autocomplete="off" placeholder="RELOAD"><div class="form-actions"><button class="btn-ui btn-primary-ui" type="submit"><svg class="ico"><use href="{{asset "icons.svg"}}#refresh"/></svg>Reload EasyDNS configuration</button></div></form></section>
<aside class="panel guide"><div class="panel-head"><div><h2>Configuration workflow</h2><p>Apply and verify your EasyDNS changes</p></div></div><div class="panel-body"><div class="data-row"><span>1. Update DNS configuration</span><strong>On the server</strong></div><p class="muted">Edit the EasyDNS configuration on the selected host, then use Hot reload to apply it.</p><div class="data-row"><span>2. Verify the service</span><strong>Check status</strong></div><p class="muted">Confirm health, readiness, server mode and zone state after a reload.</p><div class="data-row"><span>3. Review changes</span><strong>Audit log</strong></div><p class="muted">Inspect administrative events and investigate any failed operations.</p><div class="section-actions"><a class="btn-ui" href="/status">Server status</a><a class="btn-ui" href="/audit">Audit log</a></div></div></aside></div>{{end}}
@@ -1,4 +1,4 @@
{{define "login"}}<!doctype html><html lang="en" data-bs-theme="dark"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Sign in · EasyDNS</title><link rel="stylesheet" href="/static/vendor/bootstrap.min.css"><link rel="stylesheet" href="/static/app.css"></head>
<body class="login-body"><main class="login-panel"><div class="login-brand">EasyDNS</div><p class="overline">LOCAL CONTROL ROOM</p><h1>Sign in</h1><p class="muted mb-4">Access the EasyDNS administration panel. The EasyDNS bearer token stays on the server.</p>
{{define "login"}}<!doctype html><html lang="en" data-bs-theme="dark"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Sign in · EasyDNS</title><link rel="stylesheet" href="{{asset "vendor/bootstrap.min.css"}}"><link rel="stylesheet" href="{{asset "app.css"}}"></head>
<body class="login-body"><main class="login-panel"><div class="login-brand">EasyDNS</div><h1>Sign in</h1>
{{with index . "Error"}}{{if .}}<div class="notice danger" role="alert">{{.}}</div>{{end}}{{end}}
<form method="post" action="/login" autocomplete="on"><label class="field-label" for="username">Username</label><input class="field" id="username" name="username" autocomplete="username" value="{{index . "Username"}}" required><label class="field-label mt-3" for="password">Password</label><input class="field" type="password" id="password" name="password" autocomplete="current-password" required><button class="btn-ui btn-primary-ui w-100 mt-4" type="submit">Sign in</button></form><p class="login-help">Panel authentication is separate from EasyDNS REST API credentials.</p></main></body></html>{{end}}
<form method="post" action="/login" autocomplete="on"><label class="field-label" for="username">Username</label><input class="field" id="username" name="username" autocomplete="username" value="{{index . "Username"}}" required><label class="field-label mt-3" for="password">Password</label><input class="field" type="password" id="password" name="password" autocomplete="current-password" required><button class="btn-ui btn-primary-ui w-100 mt-4" type="submit">Sign in</button></form></main></body></html>{{end}}
@@ -1,4 +1,17 @@
{{define "content"}}<div class="metrics-grid six"><div class="panel metric"><span class="metric-label">DNS QUERIES</span><strong>{{int .Data.Stats.QueriesTotal}}</strong><small>Cumulative counter</small></div><div class="panel metric"><span class="metric-label">CACHE HIT RATE</span><strong class="success">{{pct .Data.Stats.CacheHitRate}}</strong><small>Latest cache ratio</small></div><div class="panel metric"><span class="metric-label">P50 LATENCY</span><strong>{{ms .Data.Stats.LatencyP50S}}</strong><small>Live histogram</small></div><div class="panel metric"><span class="metric-label">P95 LATENCY</span><strong>{{ms .Data.Stats.LatencyP95S}}</strong><small>Live histogram</small></div><div class="panel metric"><span class="metric-label">P99 LATENCY</span><strong>{{ms .Data.Stats.LatencyP99S}}</strong><small>Live histogram</small></div><div class="panel metric"><span class="metric-label">RATE LIMITED</span><strong class="warning">{{int .Data.Stats.RateLimited}}</strong><small>Cumulative count</small></div></div>
{{define "content"}}
{{if and .MultiServer (gt (len .Nodes) 1)}}
<div class="metrics-mode-bar panel">
<div class="metrics-mode-description"><span class="metric-label">METRICS SCOPE</span><strong>{{if eq .Data.MetricsMode "aggregate"}}All servers · aggregate{{else if eq .Data.MetricsMode "split"}}All servers · comparison{{else}}{{.SelectedNode.Name}} · single server{{end}}</strong><small>Choose how EasyDNS samples are presented. This does not change the DNS configuration.</small></div>
<nav class="metrics-mode-tabs" aria-label="Metrics display mode">
<a href="/metrics?mode=aggregate" {{if eq .Data.MetricsMode "aggregate"}}class="is-active" aria-current="page"{{end}}>Aggregate</a>
<a href="/metrics?mode=split" {{if eq .Data.MetricsMode "split"}}class="is-active" aria-current="page"{{end}}>Split</a>
<a href="/metrics?mode=single" {{if eq .Data.MetricsMode "single"}}class="is-active" aria-current="page"{{end}}>Single</a>
</nav>
</div>
{{end}}
<div class="metrics-view" data-metrics-mode="{{.Data.MetricsMode}}">
{{if eq .Data.MetricsMode "single"}}
<div class="metrics-grid six"><div class="panel metric"><span class="metric-label">DNS QUERIES</span><strong>{{int .Data.Stats.QueriesTotal}}</strong><small>Cumulative counter</small></div><div class="panel metric"><span class="metric-label">CACHE HIT RATE</span><strong class="success">{{pct .Data.Stats.CacheHitRate}}</strong><small>Latest cache ratio</small></div><div class="panel metric"><span class="metric-label">P50 LATENCY</span><strong>{{ms .Data.Stats.LatencyP50S}}</strong><small>Live histogram</small></div><div class="panel metric"><span class="metric-label">P95 LATENCY</span><strong>{{ms .Data.Stats.LatencyP95S}}</strong><small>Live histogram</small></div><div class="panel metric"><span class="metric-label">P99 LATENCY</span><strong>{{ms .Data.Stats.LatencyP99S}}</strong><small>Live histogram</small></div><div class="panel metric"><span class="metric-label">RATE LIMITED</span><strong class="warning">{{int .Data.Stats.RateLimited}}</strong><small>Cumulative count</small></div></div>
<div class="chart-grid triple"><section class="panel chart-card"><div class="panel-head"><div><h2>DNS query throughput</h2><p>Measured requests per second</p></div></div><canvas data-dns-chart="queries" role="img" aria-label="DNS query rate"></canvas><div class="chart-foot"><span class="legend-dot cyan"></span> DNS queries / s</div></section>
<section class="panel chart-card"><div class="panel-head"><div><h2>Response codes</h2><p>Rates from cumulative result counters</p></div></div><canvas data-dns-chart="responses" role="img" aria-label="DNS responses over time"></canvas><div class="chart-foot"><span class="legend-dot cyan"></span> NOERROR <span class="legend-dot amber"></span> NXDOMAIN <span class="legend-dot red"></span> SERVFAIL</div></section>
<section class="panel chart-card"><div class="panel-head"><div><h2>Cache efficiency</h2><p>Hit share calculated per poll</p></div></div><canvas data-dns-chart="cache" role="img" aria-label="Cache hit ratio"></canvas><div class="chart-foot"><span class="legend-dot cyan"></span> Cache hit %</div></section></div>
@@ -8,4 +21,55 @@
<div class="dashboard-lower mt-panel"><section class="panel"><div class="panel-head"><h2>Query sources</h2></div><div class="table-scroll"><table class="data-table"><thead><tr><th>SOURCE</th><th>COUNT (CUMULATIVE)</th></tr></thead><tbody>{{range $key,$v:=.Data.Stats.Sources}}<tr><td class="mono">{{$key}}</td><td class="mono right">{{int $v}}</td></tr>{{else}}<tr><td class="empty" colspan="2">No query source counters.</td></tr>{{end}}</tbody></table></div></section>
<section class="panel"><div class="panel-head"><h2>Cache counters</h2></div><div class="panel-body compact"><div class="data-row"><span>Entries</span><strong>{{int .Data.Stats.Cache.Entries}}</strong></div><div class="data-row"><span>Hits</span><strong>{{int .Data.Stats.Cache.Hits}}</strong></div><div class="data-row"><span>Misses</span><strong>{{int .Data.Stats.Cache.Misses}}</strong></div><div class="data-row"><span>Evictions</span><strong>{{int .Data.Stats.Cache.Evictions}}</strong></div></div></section>
<section class="panel"><div class="panel-head"><h2>Telemetry sampling</h2></div><div class="panel-body compact"><div class="data-row"><span>Samples stored in UI memory</span><strong>{{.Data.SamplingCount}}</strong></div><div class="data-row"><span>Polling frequency</span><strong>15 s</strong></div><div class="data-row"><span>Last sample</span><strong>{{if .Data.SamplingTime.IsZero}}—{{else}}{{.Data.SamplingTime.Format "15:04:05"}}{{end}}</strong></div><div class="notice-inline">No artificial 24-hour chart data. Samples are collected only while the Go service runs, and reset on restart.</div></div></section></div>
{{else}}
<div class="fleet-coverage panel" role="status">
<div class="fleet-coverage-main"><span class="dot {{if eq .Data.MetricOnline .Data.MetricTotal}}ok{{else}}warn{{end}}"></span><strong>{{.Data.MetricOnline}} / {{.Data.MetricTotal}} responding</strong><span class="subtle">Current /api/v1/stats snapshot</span></div>
<div class="fleet-coverage-description">{{if eq .Data.MetricsMode "aggregate"}}Additive counters are summed across responding servers. Charts need fresh readings from every server.{{else}}Each server has its own chart line; missing data stays missing.{{end}}</div>
</div>
{{if lt .Data.MetricOnline .Data.MetricTotal}}<div class="notice warn" role="status"><span>Partial data: at least one server is unavailable. Counter totals below include only responding servers. Aggregate rate charts show gaps instead of misleading reduced totals.</span></div>{{end}}
{{if eq .Data.MetricsMode "aggregate"}}
<div class="metrics-grid six">
<div class="panel metric"><span class="metric-label">RESPONDING SERVERS</span><strong>{{.Data.MetricOnline}} / {{.Data.MetricTotal}}</strong><small>Live API reachability</small></div>
<div class="panel metric"><span class="metric-label">DNS QUERIES</span><strong>{{if .Data.MetricOnline}}{{int .Data.MetricTotals.QueriesTotal}}{{else}}—{{end}}</strong><small>Sum of current counters</small></div>
<div class="panel metric"><span class="metric-label">WEIGHTED CACHE HIT</span><strong class="success">{{if .Data.MetricHasCache}}{{pct .Data.MetricTotals.CacheHitRate}}{{else}}—{{end}}</strong><small>Hits / total cache lookups</small></div>
<div class="panel metric"><span class="metric-label">BLOCKED QUERIES</span><strong class="warning">{{if .Data.MetricOnline}}{{int .Data.MetricTotals.Blocked}}{{else}}—{{end}}</strong><small>Sum of counters</small></div>
<div class="panel metric"><span class="metric-label">RATE LIMITED</span><strong>{{if .Data.MetricOnline}}{{int .Data.MetricTotals.RateLimited}}{{else}}—{{end}}</strong><small>Sum of counters</small></div>
<div class="panel metric"><span class="metric-label">P95 LATENCY</span><strong class="metric-text">Per server</strong><small>Percentiles cannot be added</small></div>
</div>
{{else}}
<div class="panel mt-panel"><div class="panel-head"><div><h2>Server metrics</h2><p>Direct snapshots from each configured EasyDNS API. The selected server in the header does not filter this fleet view.</p></div></div>
<div class="table-scroll"><table class="data-table"><thead><tr><th>SERVER</th><th>ROLE (PANEL LABEL)</th><th>API</th><th>QUERIES</th><th>CACHE HIT</th><th>P95</th><th>BLOCKED</th><th>SAMPLES</th></tr></thead><tbody>
{{range $i, $n := .Data.MetricNodes}}<tr><td><span class="fleet-swatch fleet-color-{{$i}}"></span><strong>{{$n.Node.Name}}</strong></td><td class="upper mono subtle">{{$n.Node.Role}}</td><td>{{if $n.Available}}<span class="dot ok"></span>Responding{{else}}<span class="dot danger"></span>Unavailable{{end}}</td><td class="mono">{{if $n.Available}}{{int $n.Stats.QueriesTotal}}{{else}}—{{end}}</td><td class="mono">{{if $n.Available}}{{pct $n.Stats.CacheHitRate}}{{else}}—{{end}}</td><td class="mono">{{if $n.Available}}{{ms $n.Stats.LatencyP95S}}{{else}}—{{end}}</td><td class="mono">{{if $n.Available}}{{int $n.Stats.Blocked}}{{else}}—{{end}}</td><td class="mono">{{$n.Samples}}</td></tr>{{end}}
</tbody></table></div></div>
{{end}}
<div class="chart-grid triple">
<section class="panel chart-card"><div class="panel-head"><div><h2>DNS query throughput</h2><p>{{if eq .Data.MetricsMode "aggregate"}}Sum of per-server QPS where all servers have fresh samples{{else}}Measured QPS for each server{{end}}</p></div></div><canvas data-dns-chart="queries" role="img" aria-label="Fleet DNS query throughput"></canvas><div class="chart-foot" data-chart-legend="queries">Only real poll samples</div></section>
<section class="panel chart-card"><div class="panel-head"><div><h2>{{if eq .Data.MetricsMode "aggregate"}}Response codes{{else}}NOERROR by server{{end}}</h2><p>Per-second result counter changes</p></div></div><canvas data-dns-chart="responses" role="img" aria-label="Fleet DNS response rates"></canvas><div class="chart-foot" data-chart-legend="responses">Only real poll samples</div></section>
<section class="panel chart-card"><div class="panel-head"><div><h2>Cache efficiency</h2><p>{{if eq .Data.MetricsMode "aggregate"}}Weighted by cache hit/miss operation rates{{else}}Per-server cache hit percentage{{end}}</p></div></div><canvas data-dns-chart="cache" role="img" aria-label="Fleet DNS cache hit ratios"></canvas><div class="chart-foot" data-chart-legend="cache">Only real poll samples</div></section>
</div>
<div class="chart-grid triple">
<section class="panel chart-card"><div class="panel-head"><div><h2>Resolver latency p95</h2><p>Individual server p95 snapshots — never aggregated</p></div></div><canvas data-dns-chart="latency" role="img" aria-label="Resolver p95 latency by server"></canvas><div class="chart-foot" data-chart-legend="latency">Per-server observations</div></section>
<section class="panel chart-card"><div class="panel-head"><div><h2>Blocked query rate</h2><p>{{if eq .Data.MetricsMode "aggregate"}}Sum of blocked QPS{{else}}Per-server blocked QPS{{end}}</p></div></div><canvas data-dns-chart="blocked" role="img" aria-label="Blocked DNS queries by server"></canvas><div class="chart-foot" data-chart-legend="blocked">Only real poll samples</div></section>
{{if eq .Data.MetricsMode "split"}}
<section class="panel chart-card"><div class="panel-head"><div><h2>NXDOMAIN by server</h2><p>Per-second counter changes</p></div></div><canvas data-dns-chart="nxdomain" role="img" aria-label="NXDOMAIN DNS response rates by server"></canvas><div class="chart-foot" data-chart-legend="nxdomain">Only real poll samples</div></section>
{{else}}
<section class="panel chart-card"><div class="panel-head"><div><h2>Response count mix</h2><p>Summed cumulative counters from responding servers</p></div></div><div class="panel-body compact bars-large">{{range $key,$v:=.Data.MetricTotals.Responses}}<div class="barline"><span class="mono upper">{{$key}}</span><div class="bar-track"><span class="bar-fill {{statusclass $key}}" data-count="{{$v}}" data-total="{{$.Data.MetricTotals.QueriesTotal}}"></span></div><strong>{{int $v}}</strong></div>{{else}}<div class="empty">No available response counters.</div>{{end}}</div></section>
{{end}}
</div>
<div class="dashboard-lower mt-panel">
<section class="panel"><div class="panel-head"><h2>{{if eq .Data.MetricsMode "aggregate"}}Summed query sources{{else}}Server sample health{{end}}</h2></div>
{{if eq .Data.MetricsMode "aggregate"}}<div class="table-scroll"><table class="data-table"><thead><tr><th>SOURCE</th><th>COUNT</th></tr></thead><tbody>{{range $key,$v:=.Data.MetricTotals.Sources}}<tr><td class="mono">{{$key}}</td><td class="mono right">{{int $v}}</td></tr>{{else}}<tr><td colspan="2" class="empty">No source counters.</td></tr>{{end}}</tbody></table></div>
{{else}}<div class="panel-body compact">{{range .Data.MetricNodes}}<div class="data-row"><span>{{.Node.Name}}</span><strong>{{if .LastPoll.IsZero}}Waiting for samples{{else}}{{.LastPoll.Format "15:04:05 UTC"}}{{if .LastError}} · poll failed{{end}}{{end}}</strong></div>{{end}}</div>{{end}}
</section>
<section class="panel"><div class="panel-head"><h2>{{if eq .Data.MetricsMode "aggregate"}}Summed cache counters{{else}}Latency by node{{end}}</h2></div>
{{if eq .Data.MetricsMode "aggregate"}}<div class="panel-body compact"><div class="data-row"><span>Entries</span><strong>{{int .Data.MetricTotals.Cache.Entries}}</strong></div><div class="data-row"><span>Hits</span><strong>{{int .Data.MetricTotals.Cache.Hits}}</strong></div><div class="data-row"><span>Misses</span><strong>{{int .Data.MetricTotals.Cache.Misses}}</strong></div><div class="data-row"><span>Evictions</span><strong>{{int .Data.MetricTotals.Cache.Evictions}}</strong></div></div>
{{else}}<div class="table-scroll"><table class="data-table"><thead><tr><th>SERVER</th><th>P50</th><th>P95</th><th>P99</th></tr></thead><tbody>{{range .Data.MetricNodes}}<tr><td>{{.Node.Name}}</td><td>{{if .Available}}{{ms .Stats.LatencyP50S}}{{else}}—{{end}}</td><td>{{if .Available}}{{ms .Stats.LatencyP95S}}{{else}}—{{end}}</td><td>{{if .Available}}{{ms .Stats.LatencyP99S}}{{else}}—{{end}}</td></tr>{{end}}</tbody></table></div>{{end}}
</section>
<section class="panel"><div class="panel-head"><h2>How fleet metrics work</h2></div><div class="panel-body compact fleet-methodology"><div class="data-row"><span>Poll interval</span><strong>15 seconds</strong></div><div class="data-row"><span>History</span><strong>Up to 6 hours, in RAM</strong></div><div class="data-row"><span>Chart gaps</span><strong>Missing or stale readings</strong></div><div class="notice-inline mt-panel">Counters reset on each DNS service restart. Cumulative totals sum each server's current counters, not a common 24-hour interval. Aggregate QPS requires every registered node; no synthetic zeros. Cache hit % is calculated from hit/miss rates. Latency percentiles are shown separately for each node.</div></div></section>
</div>
{{end}}
</div>
{{end}}
@@ -1,3 +1,3 @@
{{define "content"}}<div class="form-layout"><section class="panel"><div class="panel-head"><div><h2>DNS resolver diagnostic</h2><p>One-shot DNS query through this EasyDNS server</p></div></div><form method="get" action="/query" class="form-body"><div class="form-columns"><div class="field-row"><label for="qname" class="field-label">Domain name <span class="required">*</span></label><input id="qname" class="field mono" name="name" value="{{selectval .Data.Form "name"}}" required placeholder="example.org"></div><div class="field-row"><label for="qtype" class="field-label">Record type</label><select id="qtype" class="field" name="type">{{range recordTypes}}<option value="{{.}}" {{if eq . (selectval $.Data.Form "type")}}selected{{end}}>{{.}}</option>{{end}}</select></div></div><div class="form-actions"><button class="btn-ui btn-primary-ui" type="submit"><svg class="ico"><use href="/static/icons.svg#search"/></svg>Run lookup</button></div></form>
{{define "content"}}<div class="form-layout"><section class="panel"><div class="panel-head"><div><h2>DNS resolver diagnostic</h2><p>One-shot DNS query through this EasyDNS server</p></div></div><form method="get" action="/query" class="form-body"><div class="form-columns"><div class="field-row"><label for="qname" class="field-label">Domain name <span class="required">*</span></label><input id="qname" class="field mono" name="name" value="{{selectval .Data.Form "name"}}" required placeholder="example.org"></div><div class="field-row"><label for="qtype" class="field-label">Record type</label><select id="qtype" class="field" name="type">{{range recordTypes}}<option value="{{.}}" {{if eq . (selectval $.Data.Form "type")}}selected{{end}}>{{.}}</option>{{end}}</select></div></div><div class="form-actions"><button class="btn-ui btn-primary-ui" type="submit"><svg class="ico"><use href="{{asset "icons.svg"}}#search"/></svg>Run lookup</button></div></form>
{{if .Data.Query}}<div class="response-summary"><div class="strip-cell"><span>RESPONSE CODE</span><strong class="{{statusclass .Data.Query.RCode}}">{{.Data.Query.RCode}}</strong></div><div class="strip-cell"><span>AUTHORITATIVE</span><strong>{{if .Data.Query.AA}}Yes{{else}}No{{end}}</strong></div><div class="strip-cell"><span>TIME</span><strong>{{float .Data.Query.ElapsedMS}} ms</strong></div></div><div class="panel-head"><h2>Answer section</h2></div><div class="table-scroll"><table class="data-table"><thead><tr><th>NAME</th><th>TYPE</th><th>TTL</th><th>RDATA</th></tr></thead><tbody>{{range .Data.Query.Answers}}<tr><td class="mono">{{.Name}}</td><td><span class="tag green">{{.Type}}</span></td><td>{{.TTL}}</td><td class="mono">{{.Data}}</td></tr>{{else}}<tr><td class="empty" colspan="4">No answer records.</td></tr>{{end}}</tbody></table></div><div class="panel-head"><h2>Authority section</h2></div><div class="table-scroll"><table class="data-table"><thead><tr><th>NAME</th><th>TYPE</th><th>TTL</th><th>RDATA</th></tr></thead><tbody>{{range .Data.Query.Authority}}<tr><td class="mono">{{.Name}}</td><td><span class="tag blue">{{.Type}}</span></td><td>{{.TTL}}</td><td class="mono">{{.Data}}</td></tr>{{else}}<tr><td class="empty" colspan="4">No authority records returned.</td></tr>{{end}}</tbody></table></div>{{end}}</section>
<aside class="panel guide"><div class="panel-head"><h2>Diagnostics</h2></div><div class="panel-body"><p>The query is sent through the actual EasyDNS listener using the server API. It is not an external DNS testing service.</p><div class="data-row"><span>Query history</span><strong>Unavailable</strong></div><div class="data-row"><span>Live lookup</span><strong class="success">Supported</strong></div><div class="notice-inline mt-panel">The EasyDNS API defaults an unrecognized type to A. This UI limits the type selector to recognized values.</div></div></aside></div>{{end}}
@@ -3,6 +3,6 @@
<div class="form-columns"><div class="field-row"><label class="field-label" for="recordName">Record name <span class="required">*</span></label><input class="field mono" id="recordName" name="name" required value="{{selectval .Data.Form "name"}}" placeholder="www or @"><small>@ for zone apex; relative names are allowed.</small></div><div class="field-row"><label class="field-label" for="recordType">Record type <span class="required">*</span></label><select class="field" name="type" id="recordType" required><option value="">Select record type</option>{{range recordTypes}}<option value="{{.}}" {{if eq (selectval $.Data.Form "type") .}}selected{{end}} {{if eq . "SOA"}}disabled{{end}}>{{.}}</option>{{end}}</select><small>SOA changes require whole-zone replacement.</small></div></div>
<div class="field-row"><label class="field-label" for="recordData">Record data (RDATA) <span class="required">*</span></label><textarea id="recordData" class="field mono" name="data" rows="4" required placeholder="192.0.2.10">{{selectval .Data.Form "data"}}</textarea><small>Use the syntax expected for the selected RR type; Rust validates exact RDATA format.</small></div>
<div class="form-columns"><div class="field-row"><label class="field-label" for="recordTTL">TTL in seconds <span class="required">*</span></label><input class="field mono" id="recordTTL" name="ttl" type="number" min="0" max="4294967295" required value="{{selectval .Data.Form "ttl"}}"><small>0–4,294,967,295. Default: 3600.</small></div><div class="field-row"><label class="field-label">Current zone serial</label><div class="field readout mono">{{.Data.Zone.SerialText}}</div><small>Changes to the serial may trigger HTTP 412.</small></div></div>
<div class="form-actions"><a href="{{.Data.ZoneURL}}/records" class="btn-ui">Cancel</a><button class="btn-ui btn-primary-ui" type="submit"><svg class="ico"><use href="/static/icons.svg#save"/></svg>{{if eq .Data.Action "edit"}}Save changes{{else}}Add record{{end}}</button></div></form>{{else}}<div class="panel-body"><div class="notice-inline">This zone is secondary or unavailable. Record modifications are not allowed.</div></div>{{end}}</section>
<div class="form-actions"><a href="{{.Data.ZoneURL}}/records" class="btn-ui">Cancel</a><button class="btn-ui btn-primary-ui" type="submit"><svg class="ico"><use href="{{asset "icons.svg"}}#save"/></svg>{{if eq .Data.Action "edit"}}Save changes{{else}}Add record{{end}}</button></div></form>{{else}}<div class="panel-body"><div class="notice-inline">This zone is secondary or unavailable. Record modifications are not allowed.</div></div>{{end}}</section>
<aside class="panel guide"><div class="panel-head"><h2>Write behavior</h2></div><div class="panel-body"><p>This form uses an existing EasyDNS operation. There is no record-details endpoint; edits are populated from the record list.</p><div class="data-row"><span>Change conflict</span><strong>412</strong></div><div class="data-row"><span>Validation error</span><strong>400 / 422</strong></div><div class="data-row"><span>Secondary zone</span><strong>409</strong></div><div class="notice-inline mt-panel">The server may assign a different record ID after changing the name, type or value.</div></div></aside>
</div>{{end}}
@@ -0,0 +1,11 @@
{{define "content"}}
<section class="panel"><div class="panel-head"><div><h2>Compare SOA serials</h2><p>Read-only lookup of the same zone on each managed EasyDNS server.</p></div><a class="btn-ui btn-small" href="/servers">Back to servers</a></div>
<div class="panel-body"><form class="toolbar" method="get" action="/servers/compare"><div class="field-row compare-field"><label for="compare-zone">Zone name</label><input class="field mono" id="compare-zone" name="zone" value="{{.Data.CompareZone}}" placeholder="example.com." maxlength="253" required></div><button type="submit" class="btn-ui btn-primary-ui">Compare zone</button></form></div>
{{if .Data.Comparisons}}<div class="comparison-reference">{{if .Data.PrimarySerial}}Reference: Primary label · serial <strong class="mono">{{.Data.PrimarySerial}}</strong>{{else}}Primary reference serial unavailable. This comparison cannot determine whether serials match the Primary node.{{end}}</div>
<div class="table-scroll"><table class="data-table"><thead><tr><th>SERVER</th><th>PANEL LABEL</th><th>REPORTED ZONE ROLE</th><th>SOA SERIAL</th><th>ZONE STATE</th><th>VERSUS PRIMARY LABEL</th><th class="right">ACTION</th></tr></thead><tbody>
{{range .Data.Comparisons}}<tr><td class="entity">{{.Node.Name}}</td><td><span class="tag {{if eq .Node.Role "primary"}}green{{else}}muted-tag{{end}}">{{.Node.Role}}</span></td><td>{{if .Present}}{{.Zone.Kind}}{{else}}—{{end}}</td><td class="mono">{{.Serial}}</td><td>{{if .Present}}<span class="dot {{if or .Zone.Expired (not .Zone.Loaded)}}warn{{else}}ok{{end}}"></span>{{.Zone.StateText}}{{else}}<span class="muted">{{.Error}}</span>{{end}}</td><td>{{if .Present}}{{if $.Data.PrimarySerial}}{{if .MatchesPrimary}}<span class="success">Serial matches</span>{{else}}<span class="warning">Serial differs</span>{{end}}{{else}}<span class="subtle">No primary reference</span>{{end}}{{else}}—{{end}}</td><td class="right">{{if .Present}}<form method="post" action="/servers/select"><input type="hidden" name="_csrf" value="{{$.CSRF}}"><input type="hidden" name="server_id" value="{{.Node.ID}}"><input type="hidden" name="next" value="{{zoneurl $.Data.CompareZone}}"><button type="submit" class="btn-ui btn-small">Open zone</button></form>{{else}}—{{end}}</td></tr>{{end}}
</tbody></table></div>
{{else}}<div class="panel-body"><p class="muted">Enter a DNS zone to inspect its state and serial number on every configured server. This uses the native <span class="mono">GET /api/v1/zones/{zone}</span> endpoint on each instance.</p></div>{{end}}
</section>
<div class="notice-inline mt-panel">Different SOA serials are an observation, not proof of a failed transfer: clocks, propagation, refresh intervals, and RFC 1982 serial arithmetic may matter. This panel does not initiate replication automatically. Open a secondary zone to use its existing “Sync now” operation.</div>
{{end}}
@@ -0,0 +1,13 @@
{{define "content"}}
<div class="form-layout">
<section class="panel form-card"><div class="panel-head"><div><h2>Remote EasyDNS connection</h2><p>Add an existing installation. The server's DNS configuration is not modified.</p></div><span class="tag green">PANEL ONLY</span></div>
<div class="panel-body"><form method="post" action="/servers" autocomplete="off"><input type="hidden" name="_csrf" value="{{.CSRF}}">
<div class="field-row"><label for="node-name">Display name <strong class="required">*</strong></label><input class="field" id="node-name" name="name" maxlength="64" required placeholder="dns-secondary-01" value="{{selectval .Data.Form "name"}}"><small>Only used in the EasyDNS web panel.</small></div>
<div class="field-row"><label for="node-role">Topology label <strong class="required">*</strong></label><select class="field" id="node-role" name="role"><option value="secondary" {{if eq (selectval .Data.Form "role") "secondary"}}selected{{end}}>Secondary</option><option value="primary" {{if eq (selectval .Data.Form "role") "primary"}}selected{{end}}>Primary</option><option value="unassigned" {{if eq (selectval .Data.Form "role") "unassigned"}}selected{{end}}>Unassigned</option></select><small>Display label only. Does not convert zones or set up replication.</small></div>
<div class="field-row"><label for="node-url">EasyDNS API base URL <strong class="required">*</strong></label><input class="field mono" id="node-url" name="url" type="url" required placeholder="https://dns-secondary-01.example.net:9953" value="{{selectval .Data.Form "url"}}"><small>Remote URLs must use HTTPS with a trusted certificate. HTTP is allowed only on 127.0.0.1, ::1, or localhost (e.g., over an SSH tunnel). No path.</small></div>
<div class="field-row"><label for="node-token">Generated EasyDNS control token <strong class="required">*</strong></label><input class="field mono" id="node-token" name="token" type="password" required minlength="1" maxlength="4096" spellcheck="false" autocomplete="new-password" placeholder="Paste the token from the remote EasyDNS installation"><small>Stored in a private server-side file (0600); never returned to the browser or rendered in this form.</small></div>
<div class="form-actions"><a class="btn-ui" href="/servers">Cancel</a><button class="btn-ui btn-primary-ui" type="submit">Save connection</button></div>
</form></div></section>
<aside class="panel guide"><div class="panel-head"><h2>Before connecting</h2></div><div class="panel-body"><div class="data-row"><span>1. Install EasyDNS</span><strong>Each server</strong></div><p class="muted">Each remote server must run its own EasyDNS REST API and use its own generated control token.</p><div class="data-row"><span>2. Secure transport</span><strong>TLS or tunnel</strong></div><p class="muted">Protect the REST API behind an authenticated TLS endpoint or a private loopback tunnel. Never expose plain HTTP and bearer credentials over a network.</p><div class="data-row"><span>3. Configure DNS roles</span><strong>Outside panel</strong></div><p class="muted">Primary zones, secondary zones, source addresses, transfer ACLs and NOTIFY targets remain native EasyDNS configuration.</p><div class="data-row"><span>4. Review status</span><strong>Servers</strong></div><p class="muted">After saving, the Servers page probes each node and shows its actual health and zone counts.</p></div></aside>
</div>
{{end}}
@@ -0,0 +1,6 @@
{{define "content"}}
<section class="panel form-card"><div class="panel-head"><div><h2>Remove managed connection</h2><p>No action is sent to EasyDNS. Only this panel's connection metadata and stored bearer token are removed.</p></div><span class="tag danger">REMOVE</span></div>
<div class="panel-body"><div class="data-row"><span>Name</span><strong>{{.Data.ManagedNode.Name}}</strong></div><div class="data-row"><span>Endpoint</span><strong class="mono">{{.Data.ManagedNode.URL}}</strong></div><div class="data-row"><span>Panel role</span><strong>{{.Data.ManagedNode.Role}}</strong></div>
<form method="post" action="/servers/{{.Data.ManagedNode.ID}}/remove" autocomplete="off"><input type="hidden" name="_csrf" value="{{.CSRF}}"><div class="field-row mt-4"><label for="confirm-name">Type <strong class="mono">{{.Data.ManagedNode.Name}}</strong> to confirm</label><input class="field" id="confirm-name" name="confirm_name" required spellcheck="false"></div><div class="form-actions"><a href="/servers" class="btn-ui">Cancel</a><button type="submit" class="btn-ui btn-danger-ui">Remove connection</button></div></form>
</div></section>
{{end}}
@@ -0,0 +1,40 @@
{{define "content"}}
<div class="fleet-summary panel">
<div class="fleet-status"><span class="dot {{if eq .Data.ServerHealthy (len .Data.ServerProbes)}}ok{{else}}warn{{end}}"></span><div><strong>{{.Data.ServerHealthy}} / {{len .Data.ServerProbes}} responding</strong><small>Live checks: GET /api/v1/health and GET /api/v1/status on every configured installation</small></div></div>
<div class="fleet-stat"><span>MANAGED SERVERS</span><strong>{{len .Data.ServerProbes}}</strong></div>
<div class="fleet-stat"><span>TOPOLOGY</span><strong>Operator-defined</strong></div>
<div class="fleet-stat"><span>REPLICATION</span><strong>Native DNS transfers</strong></div>
</div>
<div class="fleet-toolbar">
<div><h2>Topology</h2><p class="muted tiny">Primary and Secondary are panel labels. The real DNS role is reported separately per installation.</p></div>
<div class="toolbar-end"><a class="btn-ui" href="/servers/compare"><svg class="ico"><use href="{{asset "icons.svg"}}#search"/></svg> Compare zone serials</a><a class="btn-ui btn-primary-ui" href="/servers/new"><svg class="ico"><use href="{{asset "icons.svg"}}#plus"/></svg>Add server</a></div>
</div>
<div class="topology-layout">
<div class="topology-column"><p class="topology-caption">PRIMARY · MANAGEMENT LABEL</p>
{{range .Data.ServerProbes}}{{if eq .Node.Role "primary"}}
<article class="node-card panel" aria-label="Primary node {{.Node.Name}}"><div class="node-card-top"><span class="node-role primary">PRIMARY</span><span class="node-health"><span class="dot {{if eq .State "healthy"}}ok{{else if eq .State "degraded"}}warn{{else}}danger{{end}}"></span>{{.State}}</span></div>
<h3>{{.Node.Name}}</h3><p class="mono node-address">{{.Node.URL}}</p>
<div class="node-facts"><div><small>Server version</small><strong>{{if .Status.Version}}{{.Status.Version}}{{else}}Unavailable{{end}}</strong></div><div><small>Actual primary zones</small><strong>{{.Status.Roles.Primary}}</strong></div><div><small>Actual secondary zones</small><strong>{{.Status.Roles.Secondary}}</strong></div></div>
{{if .Error}}<p class="node-error">{{.Error}}</p>{{end}}
<div class="node-actions"><form action="/servers/select" method="post"><input type="hidden" name="_csrf" value="{{$.CSRF}}"><input type="hidden" name="server_id" value="{{.Node.ID}}"><input type="hidden" name="next" value="/"><button class="btn-ui" type="submit">Manage server</button></form><a class="text-link" href="#server-inventory">Details ↓</a></div></article>
{{end}}{{end}}
</div>
<div class="topology-connector" aria-hidden="true"><span></span><small>AXFR / IXFR*</small><span></span></div>
<div class="topology-column"><p class="topology-caption">SECONDARIES · MANAGEMENT LABEL</p>
{{range .Data.ServerProbes}}{{if eq .Node.Role "secondary"}}
<article class="node-card node-card-secondary panel" aria-label="Secondary node {{.Node.Name}}"><div class="node-card-top"><span class="node-role secondary">SECONDARY</span><span class="node-health"><span class="dot {{if eq .State "healthy"}}ok{{else if eq .State "degraded"}}warn{{else}}danger{{end}}"></span>{{.State}}</span></div>
<h3>{{.Node.Name}}</h3><p class="mono node-address">{{.Node.URL}}</p><div class="node-facts"><div><small>Version</small><strong>{{if .Status.Version}}{{.Status.Version}}{{else}}Unavailable{{end}}</strong></div><div><small>Actual secondary zones</small><strong>{{.Status.Roles.Secondary}}</strong></div><div><small>Actual primary zones</small><strong>{{.Status.Roles.Primary}}</strong></div></div>
{{if .Error}}<p class="node-error">{{.Error}}</p>{{end}}
<div class="node-actions"><form action="/servers/select" method="post"><input type="hidden" name="_csrf" value="{{$.CSRF}}"><input type="hidden" name="server_id" value="{{.Node.ID}}"><input type="hidden" name="next" value="/"><button class="btn-ui" type="submit">Manage server</button></form></div></article>
{{end}}{{end}}
</div>
</div>
{{range .Data.ServerProbes}}{{if eq .Node.Role "unassigned"}}<section class="node-unassigned panel"><span class="tag muted-tag">UNASSIGNED</span> <strong>{{.Node.Name}}</strong> <span class="muted">{{.State}} · {{.Node.URL}}</span></section>{{end}}{{end}}
<p class="topology-disclaimer">* Diagram indicates the intended topology, not a detected transfer connection. EasyDNS primary/secondary zone relationships must be configured on the DNS servers. The UI cannot create secondary zones through REST.</p>
<section class="panel mt-panel" id="server-inventory"><div class="panel-head"><div><h2>Managed installations</h2><p>Change local display roles, switch context, or remove a remote connection. These actions do not reconfigure DNS.</p></div></div>
<div class="table-scroll"><table class="data-table"><thead><tr><th>SERVER</th><th>API URL</th><th>STATUS</th><th>PRIMARY ZONES*</th><th>SECONDARY ZONES*</th><th>LABEL</th><th class="right">ACTIONS</th></tr></thead><tbody>
{{range .Data.ServerProbes}}<tr><td class="entity">{{.Node.Name}}{{if .Node.Local}}<span class="tag muted-tag ms-2">LOCAL</span>{{else}}<span class="tag muted-tag ms-2">REMOTE</span>{{end}}</td><td class="mono muted">{{.Node.URL}}</td><td><span class="dot {{if eq .State "healthy"}}ok{{else if eq .State "degraded"}}warn{{else}}danger{{end}}"></span>{{.State}}</td><td class="mono">{{if eq .State "offline"}}—{{else}}{{.Status.Roles.Primary}}{{end}}</td><td class="mono">{{if eq .State "offline"}}—{{else}}{{.Status.Roles.Secondary}}{{end}}</td><td>{{if or .Node.Managed (and .Node.Local $.LocalRoleConfigured)}}<span class="subtle">{{if eq .Node.Role "primary"}}Primary{{else if eq .Node.Role "secondary"}}Secondary{{else}}Unassigned{{end}}</span>{{else}}<form action="/servers/{{.Node.ID}}/role" method="post" class="role-form"><input type="hidden" name="_csrf" value="{{$.CSRF}}"><label class="sr-only" for="role-{{.Node.ID}}">Label for {{.Node.Name}}</label><select class="field compact-field" id="role-{{.Node.ID}}" name="role"><option value="primary" {{if eq .Node.Role "primary"}}selected{{end}}>Primary</option><option value="secondary" {{if eq .Node.Role "secondary"}}selected{{end}}>Secondary</option><option value="unassigned" {{if eq .Node.Role "unassigned"}}selected{{end}}>Unassigned</option></select><button class="btn-ui btn-small" type="submit">Save</button></form>{{end}}</td><td class="right"><div class="row-actions"><form method="post" action="/servers/select"><input type="hidden" name="_csrf" value="{{$.CSRF}}"><input type="hidden" name="server_id" value="{{.Node.ID}}"><input type="hidden" name="next" value="/"><button type="submit" class="btn-ui btn-small">Open</button></form>{{if and (not .Node.Local) (not .Node.Managed)}}<a href="/servers/{{.Node.ID}}/remove" class="btn-ui btn-small btn-danger-ui">Remove</a>{{end}}</div></td></tr>
{{end}}
</tbody></table></div></section>
<div class="notice-inline mt-panel">* Zone counts are read from each server's actual <span class="mono">/api/v1/status</span> response. An offline node's DNS role cannot be verified. No cluster quorum, leader election, or automated replication is implied.</div>
{{end}}
@@ -1,4 +1,4 @@
{{define "content"}}<section class="panel"><div class="toolbar"><div class="toolbar-title"><h2>Resolver pools</h2><p>Runtime upstream health and forwarding strategy.</p></div><a class="btn-ui btn-primary-ui" href="/upstreams/new"><svg class="ico"><use href="/static/icons.svg#plus"/></svg>Add upstream</a></div>
{{define "content"}}<section class="panel"><div class="toolbar"><div class="toolbar-title"><h2>Resolver pools</h2><p>Runtime upstream health and forwarding strategy.</p></div><a class="btn-ui btn-primary-ui" href="/upstreams/new"><svg class="ico"><use href="{{asset "icons.svg"}}#plus"/></svg>Add upstream</a></div>
{{range .Data.Upstreams}}<div class="pool-head"><div><h3>{{.Group}}</h3><span class="subtle">Strategy: {{.Strategy}}</span></div><span class="tag blue">{{len .Servers}} servers</span></div><div class="table-scroll"><table class="data-table"><thead><tr><th>ADDRESS</th><th>HEALTH</th><th>QUERIES</th><th>FAILURES</th><th>EWMA RTT</th><th>CIRCUIT</th><th>LAST ERROR</th></tr></thead><tbody>
{{range .Servers}}<tr><td class="mono entity">{{.Address}}</td><td><span class="dot {{if .Stats.Healthy}}ok{{else}}warn{{end}}"></span>{{if .Stats.Healthy}}Healthy{{else}}Unavailable{{end}}</td><td class="mono">{{int .Stats.Queries}}</td><td class="mono">{{int .Stats.Failures}}</td><td class="mono">{{if .Stats.EWMARTTMS}}{{float .Stats.EWMARTTMS}} ms{{else}}—{{end}}</td><td class="mono">{{if .Stats.CircuitOpenForMS}}Open{{else}}Closed / unknown{{end}}</td><td class="muted">{{if .Stats.LastError}}{{.Stats.LastError}}{{else}}—{{end}}</td></tr>{{else}}<tr><td class="empty" colspan="7">No servers in this pool.</td></tr>{{end}}
</tbody></table></div>{{else}}<div class="empty">No upstream groups returned by EasyDNS.</div>{{end}}</section><div class="notice-inline mt-panel">The API supports adding an upstream address, but does not provide a REST method to edit or remove upstreams or reorder pools.</div>{{end}}
@@ -5,5 +5,5 @@
{{if eq .Data.Action "import"}}<div class="field-row"><label class="field-label" for="zoneFile">Complete zone file <span class="required">*</span></label><textarea id="zoneFile" class="field mono code-input" name="zone_file" rows="13" spellcheck="false" required placeholder="$TTL 3600&#10;@ IN SOA ns1.example.org. hostmaster.example.org. 1 3600 900 1209600 300&#10;@ IN NS ns1.example.org.">{{selectval .Data.Form "zone_file"}}</textarea><small>Paste original zone file content you own. EasyDNS does not expose zone files for download via REST.</small></div>
{{else}}<div class="field-row"><label class="field-label" for="zoneNS">Nameservers <span class="required">*</span></label><textarea id="zoneNS" class="field mono" name="ns" rows="4" placeholder="ns1.example.org.&#10;ns2.example.org." required>{{selectval .Data.Form "ns"}}</textarea><small>One FQDN per line; the API generates a minimal SOA/NS zone.</small></div><div class="field-row"><label class="field-label" for="hostmaster">SOA hostmaster</label><input id="hostmaster" class="field mono" name="hostmaster" value="{{selectval .Data.Form "hostmaster"}}" placeholder="hostmaster.example.org."></div>{{end}}
<div class="form-columns"><div class="field-row"><label class="field-label" for="transferAcl">Transfer ACL (optional)</label><textarea class="field mono" id="transferAcl" name="transfer_acl" rows="3" placeholder="192.0.2.0/24">{{selectval .Data.Form "transfer_acl"}}</textarea><small>Networks, one per line.</small></div><div class="field-row"><label class="field-label" for="notify">NOTIFY targets (optional)</label><textarea class="field mono" id="notify" name="notify" rows="3" placeholder="192.0.2.20:53">{{selectval .Data.Form "notify"}}</textarea><small>IP:port socket addresses, one per line.</small></div></div>
<div class="form-actions"><a href="/zones" class="btn-ui">Cancel</a><button class="btn-ui btn-primary-ui" type="submit"><svg class="ico"><use href="/static/icons.svg#plus"/></svg>Create primary zone</button></div>
<div class="form-actions"><a href="/zones" class="btn-ui">Cancel</a><button class="btn-ui btn-primary-ui" type="submit"><svg class="ico"><use href="{{asset "icons.svg"}}#plus"/></svg>Create primary zone</button></div>
</form></section><aside class="panel guide"><div class="panel-head"><h2>Creation details</h2></div><div class="panel-body"><p>This is a configuration-changing operation. EasyDNS validates the zone, persists it in the API overlay and reloads the runtime.</p><div class="data-row"><span>Already exists</span><strong>409</strong></div><div class="data-row"><span>Invalid zone file</span><strong>422</strong></div><div class="data-row"><span>Invalid request</span><strong>400</strong></div><div class="notice-inline mt-panel">The nameservers/hostmaster form does not create secondary zones.</div></div></aside></div>{{end}}
@@ -22,10 +22,10 @@
</div>
<div class="section-actions"><a class="btn-ui btn-primary-ui" href="{{.Data.ZoneURL}}/records">View DNS records</a><a class="btn-ui" href="{{.Data.ZoneURL}}/transfers">Transfer history</a><a class="btn-ui" href="{{.Data.ZoneURL}}/operations">Zone operations</a></div>
{{else if eq .Data.Tab "records"}}
<section class="panel"><div class="toolbar"><form class="toolbar-form" method="get" action="{{.Data.ZoneURL}}/records"><input class="field field-search" name="name" placeholder="Record name begins with..." aria-label="Filter record names" value="{{selectval .Data.Filter "name"}}"><select class="field field-select" aria-label="Record type" name="type"><option value="">All types</option>{{range $type := recordTypes}}<option value="{{$type}}" {{if eq (selectval $.Data.Filter "type") $type}}selected{{end}}>{{$type}}</option>{{end}}</select><button type="submit" class="btn-ui"><svg class="ico"><use href="/static/icons.svg#search"/></svg>Filter</button></form>
<div class="toolbar-end"><span class="subtle desktop-only">{{.Data.Pagination.Total}} records</span>{{if .Data.IsPrimary}}<a class="btn-ui btn-primary-ui" href="{{.Data.ZoneURL}}/records/new"><svg class="ico"><use href="/static/icons.svg#plus"/></svg>Add record</a>{{else}}<span class="tag muted-tag">Secondary · read-only</span>{{end}}</div></div>
<section class="panel"><div class="toolbar"><form class="toolbar-form" method="get" action="{{.Data.ZoneURL}}/records"><input class="field field-search" name="name" placeholder="Record name begins with..." aria-label="Filter record names" value="{{selectval .Data.Filter "name"}}"><select class="field field-select" aria-label="Record type" name="type"><option value="">All types</option>{{range $type := recordTypes}}<option value="{{$type}}" {{if eq (selectval $.Data.Filter "type") $type}}selected{{end}}>{{$type}}</option>{{end}}</select><button type="submit" class="btn-ui"><svg class="ico"><use href="{{asset "icons.svg"}}#search"/></svg>Filter</button></form>
<div class="toolbar-end"><span class="subtle desktop-only">{{.Data.Pagination.Total}} records</span>{{if .Data.IsPrimary}}<a class="btn-ui btn-primary-ui" href="{{.Data.ZoneURL}}/records/new"><svg class="ico"><use href="{{asset "icons.svg"}}#plus"/></svg>Add record</a>{{else}}<span class="tag muted-tag">Secondary · read-only</span>{{end}}</div></div>
<div class="table-scroll"><table class="data-table"><thead><tr><th>NAME</th><th>TYPE</th><th>RDATA</th><th>TTL</th>{{if .Data.IsPrimary}}<th class="right">ACTIONS</th>{{end}}</tr></thead><tbody>
{{range .Data.Records}}<tr><td class="mono entity">{{.Name}}</td><td><span class="tag green">{{.Type}}</span></td><td class="mono rdata">{{.Data}}</td><td class="mono">{{.TTL}}</td>{{if $.Data.IsPrimary}}<td class="right">{{if ne .Type "SOA"}}<div class="row-actions"><a href="{{$.Data.ZoneURL}}/records/{{.ID}}/edit?page={{$.Data.Pagination.Page}}" class="icon-button" aria-label="Edit record {{.Name}}" title="Edit"><svg class="ico"><use href="/static/icons.svg#edit"/></svg></a><a href="{{$.Data.ZoneURL}}/records/{{.ID}}/delete?page={{$.Data.Pagination.Page}}" class="icon-button danger-hover" aria-label="Delete record {{.Name}}" title="Delete"><svg class="ico"><use href="/static/icons.svg#trash"/></svg></a></div>{{else}}<span class="subtle" title="SOA is managed by zone replacement">Managed</span>{{end}}</td>{{end}}</tr>{{else}}<tr><td class="empty" colspan="5">No records returned for this filter.</td></tr>{{end}}
{{range .Data.Records}}<tr><td class="mono entity">{{.Name}}</td><td><span class="tag green">{{.Type}}</span></td><td class="mono rdata">{{.Data}}</td><td class="mono">{{.TTL}}</td>{{if $.Data.IsPrimary}}<td class="right">{{if ne .Type "SOA"}}<div class="row-actions"><a href="{{$.Data.ZoneURL}}/records/{{.ID}}/edit?page={{$.Data.Pagination.Page}}" class="icon-button" aria-label="Edit record {{.Name}}" title="Edit"><svg class="ico"><use href="{{asset "icons.svg"}}#edit"/></svg></a><a href="{{$.Data.ZoneURL}}/records/{{.ID}}/delete?page={{$.Data.Pagination.Page}}" class="icon-button danger-hover" aria-label="Delete record {{.Name}}" title="Delete"><svg class="ico"><use href="{{asset "icons.svg"}}#trash"/></svg></a></div>{{else}}<span class="subtle" title="SOA is managed by zone replacement">Managed</span>{{end}}</td>{{end}}</tr>{{else}}<tr><td class="empty" colspan="5">No records returned for this filter.</td></tr>{{end}}
</tbody></table></div><div class="table-footer"><span>{{len .Data.Records}} / {{.Data.Pagination.Total}} records · page {{.Data.Pagination.Page}}</span><div class="pagination-ui">{{if gt .Data.Pagination.Page 1}}<a class="btn-ui btn-small" href="{{.Data.ZoneURL}}/records?page={{dec .Data.Pagination.Page}}&amp;name={{selectval .Data.Filter "name"}}&amp;type={{selectval .Data.Filter "type"}}">Previous</a>{{end}}{{if lt (multiply .Data.Pagination.Page .Data.Pagination.PerPage) .Data.Pagination.Total}}<a class="btn-ui btn-small" href="{{.Data.ZoneURL}}/records?page={{inc .Data.Pagination.Page}}&amp;name={{selectval .Data.Filter "name"}}&amp;type={{selectval .Data.Filter "type"}}">Next</a>{{end}}</div></div></section>
<div class="notice-inline mt-panel">Writes are protected with the zone serial ETag. SOA records are managed through whole-zone replacement; secondaries are read-only.</div>
{{else if eq .Data.Tab "transfers"}}
@@ -34,8 +34,8 @@
<section class="panel"><div class="panel-head"><div><h2>DNSSEC status</h2><p>Inspection only. Key lifecycle and signing changes are not exposed through REST.</p></div></div><div class="panel-body">{{if .Data.Zone.DNSSEC}}<div class="code-block"><pre>{{asjson .Data.Zone.DNSSEC}}</pre></div>{{else}}<div class="empty">No DNSSEC status returned for this zone.</div>{{end}}</div></section>
{{else if eq .Data.Tab "operations"}}
<div class="operations-grid"><section class="panel"><div class="panel-head"><div><h2>Supported zone actions</h2><p>Available operations depend on the zone role and configuration</p></div></div><div class="panel-body">
{{if .Data.Zone.IsSecondary}}<form method="post" action="{{.Data.ZoneURL}}/sync" class="operation"><input type="hidden" name="_csrf" value="{{.CSRF}}"><input type="hidden" name="confirm" value="yes"><div><strong>Synchronize secondary</strong><small>Request an immediate refresh from its primary.</small></div><button class="btn-ui" type="submit"><svg class="ico"><use href="/static/icons.svg#refresh"/></svg>Sync now</button></form>{{end}}
{{if .Data.Zone.Config.Notify}}<form method="post" action="{{.Data.ZoneURL}}/notify" class="operation"><input type="hidden" name="_csrf" value="{{.CSRF}}"><input type="hidden" name="confirm" value="yes"><div><strong>Send DNS NOTIFY</strong><small>{{len .Data.Zone.Config.Notify}} configured targets · HTTP 202 means accepted, not delivered</small></div><button class="btn-ui" type="submit"><svg class="ico"><use href="/static/icons.svg#bell"/></svg>Send NOTIFY</button></form>{{end}}
{{if .Data.Zone.IsSecondary}}<form method="post" action="{{.Data.ZoneURL}}/sync" class="operation"><input type="hidden" name="_csrf" value="{{.CSRF}}"><input type="hidden" name="confirm" value="yes"><div><strong>Synchronize secondary</strong><small>Request an immediate refresh from its primary.</small></div><button class="btn-ui" type="submit"><svg class="ico"><use href="{{asset "icons.svg"}}#refresh"/></svg>Sync now</button></form>{{end}}
{{if .Data.Zone.Config.Notify}}<form method="post" action="{{.Data.ZoneURL}}/notify" class="operation"><input type="hidden" name="_csrf" value="{{.CSRF}}"><input type="hidden" name="confirm" value="yes"><div><strong>Send DNS NOTIFY</strong><small>{{len .Data.Zone.Config.Notify}} configured targets · HTTP 202 means accepted, not delivered</small></div><button class="btn-ui" type="submit"><svg class="ico"><use href="{{asset "icons.svg"}}#bell"/></svg>Send NOTIFY</button></form>{{end}}
{{if .Data.Zone.IsPrimary}}<div class="operation"><div><strong>Replace zone contents</strong><small>Submit a complete operator-provided zone file. No original file download.</small></div><a href="{{.Data.ZoneURL}}/replace" class="btn-ui">Replace zone</a></div>{{end}}
<div class="operation"><div><strong>Delete API-created zone</strong><small>Only zones created in the API overlay are deletable; others return HTTP 409.</small></div><a href="{{.Data.ZoneURL}}/delete" class="btn-ui btn-danger-ui">Delete zone</a></div>
{{if and (not .Data.Zone.IsSecondary) (not .Data.Zone.IsPrimary)}}<div class="empty">Zone operations require a loaded zone.</div>{{end}}
@@ -1,10 +1,10 @@
{{define "content"}}
<div class="status-strip panel compact-strip"><div class="strip-cell"><span>TOTAL ZONES (CURRENT FILTER)</span><strong>{{int .Data.Pagination.Total}}</strong></div><div class="strip-cell"><span>ITEMS PER PAGE</span><strong>{{.Data.Pagination.PerPage}}</strong></div><div class="strip-cell"><span>CURRENT PAGE</span><strong>{{.Data.Pagination.Page}}</strong></div><div class="strip-cell"><span>ZONE TYPES</span><strong>Primary · Secondary</strong></div></div>
<section class="panel mt-panel"><div class="toolbar">
<form action="/zones" method="get" class="toolbar-form"><label class="sr-only" for="searchZones">Search zones</label><input class="field field-search" id="searchZones" name="name" placeholder="Search zones by name" value="{{selectval .Data.Filter "name"}}"><select class="field field-select" name="kind" aria-label="Zone type"><option value="">All types</option><option value="primary" {{if eq (selectval .Data.Filter "kind") "primary"}}selected{{end}}>Primary</option><option value="secondary" {{if eq (selectval .Data.Filter "kind") "secondary"}}selected{{end}}>Secondary</option></select><button class="btn-ui" type="submit"><svg class="ico"><use href="/static/icons.svg#search"/></svg> Search</button></form>
<div class="toolbar-end"><a class="btn-ui" href="/zones/import"><svg class="ico"><use href="/static/icons.svg#upload"/></svg> Import zone file</a><a class="btn-ui btn-primary-ui" href="/zones/new"><svg class="ico"><use href="/static/icons.svg#plus"/></svg> Add zone</a></div></div>
<form action="/zones" method="get" class="toolbar-form"><label class="sr-only" for="searchZones">Search zones</label><input class="field field-search" id="searchZones" name="name" placeholder="Search zones by name" value="{{selectval .Data.Filter "name"}}"><select class="field field-select" name="kind" aria-label="Zone type"><option value="">All types</option><option value="primary" {{if eq (selectval .Data.Filter "kind") "primary"}}selected{{end}}>Primary</option><option value="secondary" {{if eq (selectval .Data.Filter "kind") "secondary"}}selected{{end}}>Secondary</option></select><button class="btn-ui" type="submit"><svg class="ico"><use href="{{asset "icons.svg"}}#search"/></svg> Search</button></form>
<div class="toolbar-end"><a class="btn-ui" href="/zones/import"><svg class="ico"><use href="{{asset "icons.svg"}}#upload"/></svg> Import zone file</a><a class="btn-ui btn-primary-ui" href="/zones/new"><svg class="ico"><use href="{{asset "icons.svg"}}#plus"/></svg> Add zone</a></div></div>
<div class="table-scroll"><table class="data-table"><thead><tr><th>ZONE NAME</th><th>TYPE</th><th>SERIAL</th><th>RECORDS</th><th>STATE</th><th>TRANSFER / SYNC</th><th>LAST SUCCESSFUL SYNC</th><th class="right">ACTION</th></tr></thead><tbody>
{{range .Data.Zones}}<tr><td><a class="entity" href="{{zoneurl .Name}}">{{.Name}}</a></td><td><span class="tag {{if .IsSecondary}}blue{{else}}green{{end}}">{{.Kind}}</span></td><td class="mono">{{.SerialText}}</td><td class="mono">{{.Records}}</td><td><span class="dot {{if .Loaded}}{{if .Expired}}danger{{else}}ok{{end}}{{else}}warn{{end}}"></span>{{.StateText}}</td><td>{{if .IsSecondary}}<span class="dot {{statusclass .SyncText}}"></span>{{.SyncText}}{{else}}<span class="subtle">—</span>{{end}}</td><td class="mono subtle">{{if .IsSecondary}}{{.LastSync}}{{else}}—{{end}}</td><td class="right"><a class="btn-ui btn-small" href="{{zoneurl .Name}}">Open <svg class="ico"><use href="/static/icons.svg#arrow-right"/></svg></a></td></tr>{{else}}<tr><td class="empty" colspan="8">No zones match the current filter, or the API is not available.</td></tr>{{end}}
{{range .Data.Zones}}<tr><td><a class="entity" href="{{zoneurl .Name}}">{{.Name}}</a></td><td><span class="tag {{if .IsSecondary}}blue{{else}}green{{end}}">{{.Kind}}</span></td><td class="mono">{{.SerialText}}</td><td class="mono">{{.Records}}</td><td><span class="dot {{if .Loaded}}{{if .Expired}}danger{{else}}ok{{end}}{{else}}warn{{end}}"></span>{{.StateText}}</td><td>{{if .IsSecondary}}<span class="dot {{statusclass .SyncText}}"></span>{{.SyncText}}{{else}}<span class="subtle">—</span>{{end}}</td><td class="mono subtle">{{if .IsSecondary}}{{.LastSync}}{{else}}—{{end}}</td><td class="right"><a class="btn-ui btn-small" href="{{zoneurl .Name}}">Open <svg class="ico"><use href="{{asset "icons.svg"}}#arrow-right"/></svg></a></td></tr>{{else}}<tr><td class="empty" colspan="8">No zones match the current filter, or the API is not available.</td></tr>{{end}}
</tbody></table></div>
<div class="table-footer"><span>Showing {{len .Data.Zones}} of {{int .Data.Pagination.Total}} zones · page {{.Data.Pagination.Page}}</span><div class="pagination-ui"><a class="btn-ui btn-small" href="/zones?page=1&amp;name={{selectval .Data.Filter "name"}}&amp;kind={{selectval .Data.Filter "kind"}}">First</a>{{if gt .Data.Pagination.Page 1}}<a class="btn-ui btn-small" href="/zones?page={{dec .Data.Pagination.Page}}&amp;name={{selectval .Data.Filter "name"}}&amp;kind={{selectval .Data.Filter "kind"}}">Previous</a>{{end}}{{if lt (multiply .Data.Pagination.Page .Data.Pagination.PerPage) .Data.Pagination.Total}}<a class="btn-ui btn-small" href="/zones?page={{inc .Data.Pagination.Page}}&amp;name={{selectval .Data.Filter "name"}}&amp;kind={{selectval .Data.Filter "kind"}}">Next</a>{{end}}</div></div>
</section><div class="notice-inline mt-panel">Primary zones can be created through REST. Secondary zone creation and general zone configuration editing are not exposed by EasyDNS.</div>
+116
View File
@@ -0,0 +1,116 @@
package telemetry
import (
"time"
)
// FleetNode is an authenticated panel-only view of measured samples. It
// contains no credentials or server configuration mutation capabilities.
// Each node owns a separate history; no synthetic data is produced.
type FleetNode struct {
ID string `json:"id"`
Name string `json:"name"`
Role string `json:"role"`
Samples []Sample `json:"samples"`
Error string `json:"error,omitempty"`
LastPoll time.Time `json:"lastPoll"`
}
// FleetPoint contains only quantities for which across-node arithmetic is
// valid. Percentile latency is intentionally excluded: it cannot be computed
// from separately reported per-node p50/p95/p99 values.
type FleetPoint struct {
Time time.Time `json:"time"`
QueryRate *float64 `json:"queryRate"`
NoErrorRate *float64 `json:"noerror"`
NXDomainRate *float64 `json:"nxdomain"`
ServFailRate *float64 `json:"servfail"`
RefusedRate *float64 `json:"refused"`
BlockedRate *float64 `json:"blocked"`
CacheHitRate *float64 `json:"cacheHitRate"`
Contributors int `json:"contributors"`
}
const fleetStep = 15 * time.Second
const fleetMaxAge = 23 * time.Second
// AggregateFleet produces timestamp-aligned, fully-covered sum-of-rates
// points for all registered servers. Each node contributes its latest real
// reading at or before the UTC grid timestamp, no older than 23 seconds.
// Missing/reset/stale samples produce a gap (null), never a misleading 0 or a
// reduced total disguised as a whole-fleet total. Cache ratio is weighted by
// cache hit/miss operations per second, not averaged from percentages.
func AggregateFleet(nodes []FleetNode) []FleetPoint {
if len(nodes) == 0 {
return nil
}
var earliest, latest time.Time
for _, n := range nodes {
for _, p := range n.Samples {
if earliest.IsZero() || p.Time.Before(earliest) {
earliest = p.Time
}
if latest.IsZero() || p.Time.After(latest) {
latest = p.Time
}
}
}
if earliest.IsZero() {
return nil
}
start := earliest.Truncate(fleetStep).Add(fleetStep)
end := latest.Truncate(fleetStep).Add(fleetStep)
if end.Before(start) {
return nil
}
// Bound comparison data to the same six-hour, 1440-poll memory horizon as
// each node's History. Never add empty points before the first poll.
if end.Sub(start) > time.Duration(maxSamples-1)*fleetStep {
start = end.Add(-time.Duration(maxSamples-1) * fleetStep)
}
points := make([]FleetPoint, 0, int(end.Sub(start)/fleetStep)+1)
index := make([]int, len(nodes))
for t := start; !t.After(end); t = t.Add(fleetStep) {
point := FleetPoint{Time: t}
var query, noerror, nxdomain, servfail, refused, blocked float64
var hitQPS, missQPS float64
cacheComplete := true
for i, n := range nodes {
for index[i] < len(n.Samples) && !n.Samples[index[i]].Time.After(t) {
index[i]++
}
if index[i] == 0 {
cacheComplete = false
continue
}
sample := n.Samples[index[i]-1]
if age := t.Sub(sample.Time); age < 0 || age > fleetMaxAge || sample.QueryRate == nil || sample.NoErrorRate == nil || sample.NXDomainRate == nil || sample.ServFailRate == nil || sample.RefusedRate == nil || sample.BlockedRate == nil {
cacheComplete = false
continue
}
point.Contributors++
query += *sample.QueryRate
noerror += *sample.NoErrorRate
nxdomain += *sample.NXDomainRate
servfail += *sample.ServFailRate
refused += *sample.RefusedRate
blocked += *sample.BlockedRate
if sample.cacheHitQPS == nil || sample.cacheMissQPS == nil {
cacheComplete = false
} else {
hitQPS += *sample.cacheHitQPS
missQPS += *sample.cacheMissQPS
}
}
if point.Contributors == len(nodes) {
point.QueryRate, point.NoErrorRate, point.NXDomainRate = &query, &noerror, &nxdomain
point.ServFailRate, point.RefusedRate, point.BlockedRate = &servfail, &refused, &blocked
if cacheComplete && hitQPS+missQPS > 0 {
ratio := 100 * hitQPS / (hitQPS + missQPS)
point.CacheHitRate = &ratio
}
}
points = append(points, point)
}
return points
}
+92
View File
@@ -0,0 +1,92 @@
package telemetry
import (
"encoding/json"
"math"
"strings"
"testing"
"time"
"git.linuxiarz.pl/gru/EasyDNS-Web/internal/easydns"
)
func fleetStats(queries, hits, misses uint64) easydns.Stats {
return easydns.Stats{
QueriesTotal: queries,
Responses: map[string]uint64{"noerror": queries / 2, "nxdomain": queries / 4},
Blocked: queries / 10,
Cache: easydns.Cache{Hits: hits, Misses: misses},
LatencyP95S: .021,
}
}
func TestFleetAggregateSumsRatesAndWeightsCacheCounts(t *testing.T) {
base := time.Date(2026, 11, 30, 10, 0, 2, 0, time.UTC)
inputs := []struct {
name string
off time.Duration
first, last easydns.Stats
}{
{"primary", 0, fleetStats(100, 10, 10), fleetStats(130, 30, 10)},
{"secondary-1", 2 * time.Second, fleetStats(200, 0, 0), fleetStats(260, 0, 60)},
{"secondary-2", 5 * time.Second, fleetStats(50, 0, 0), fleetStats(95, 10, 10)},
}
var nodes []FleetNode
for i, tc := range inputs {
h := New()
h.Record(base.Add(tc.off), tc.first)
h.Record(base.Add(tc.off+15*time.Second), tc.last)
samples, _, _ := h.Snapshot()
nodes = append(nodes, FleetNode{ID: string(rune('a' + i)), Name: tc.name, Samples: samples})
}
points := AggregateFleet(nodes)
if len(points) != 2 {
t.Fatalf("expected grid points at 10:00:15 and 10:00:30, got %d", len(points))
}
last := points[len(points)-1]
if last.Contributors != 3 || last.QueryRate == nil || math.Abs(*last.QueryRate-9) > .0001 {
t.Fatalf("3-node sum must be (30+60+45)/15 = 9 QPS: %+v", last)
}
// 20 hits + 0 hits + 10 hits vs 0 + 60 + 10 misses = 30%.
if last.CacheHitRate == nil || math.Abs(*last.CacheHitRate-30) > .0001 {
t.Fatalf("fleet cache ratio must be weighted 30%%, not avg of percentages: %+v", last)
}
if last.NoErrorRate == nil || *last.NoErrorRate <= 0 || last.BlockedRate == nil {
t.Fatalf("additive response/blocked rates missing: %+v", last)
}
body, err := json.Marshal(last)
if err != nil {
t.Fatal(err)
}
if strings.Contains(string(body), "p95") || strings.Contains(string(body), "p50") {
t.Fatal("aggregated latency percentiles would be invalid")
}
}
func TestFleetAggregateNeverTreatsMissingNodesAsZero(t *testing.T) {
base := time.Date(2026, 11, 30, 10, 0, 2, 0, time.UTC)
a, b := New(), New()
a.Record(base, fleetStats(100, 10, 10))
a.Record(base.Add(15*time.Second), fleetStats(145, 30, 10))
b.Record(base.Add(3*time.Second), fleetStats(500, 20, 20)) // no second sample: rate unknown
points := AggregateFleet([]FleetNode{{ID: "a", Samples: historySamples(a)}, {ID: "b", Samples: historySamples(b)}})
last := points[len(points)-1]
if last.QueryRate != nil || last.CacheHitRate != nil || last.Contributors != 1 {
t.Fatalf("partial fleet must produce gap, not 3 QPS presented as total: %+v", last)
}
// Counter reset on one node must also introduce a null, not a negative QPS.
b.Record(base.Add(18*time.Second), fleetStats(0, 0, 0))
points = AggregateFleet([]FleetNode{{ID: "a", Samples: historySamples(a)}, {ID: "b", Samples: historySamples(b)}})
last = points[len(points)-1]
if last.QueryRate != nil || last.Contributors != 1 {
t.Fatalf("reset must not show a partial aggregate as full: %+v", last)
}
}
func TestFleetEmptyHistory(t *testing.T) {
if AggregateFleet(nil) != nil || AggregateFleet([]FleetNode{{Name: "no readings"}}) != nil {
t.Fatal("fleet with no readings must stay empty")
}
}
func historySamples(h *History) []Sample { s, _, _ := h.Snapshot(); return s }
+6
View File
@@ -33,6 +33,10 @@ type Sample struct {
P50MS float64 `json:"p50ms"`
P95MS float64 `json:"p95ms"`
P99MS float64 `json:"p99ms"`
// Per-second cache increments allow mathematically weighted fleet cache
// ratios. These are derived from real counters and never sent to the browser.
cacheHitQPS *float64
cacheMissQPS *float64
}
type History struct {
@@ -66,6 +70,8 @@ func (h *History) Record(t time.Time, s easydns.Stats) {
if p.CacheHits >= prev.CacheHits && p.CacheMisses >= prev.CacheMisses {
hits := p.CacheHits - prev.CacheHits
misses := p.CacheMisses - prev.CacheMisses
p.cacheHitQPS = delta(prev.CacheHits, p.CacheHits, secs)
p.cacheMissQPS = delta(prev.CacheMisses, p.CacheMisses, secs)
if hits+misses > 0 {
v := 100 * float64(hits) / float64(hits+misses)
p.CacheHitRate = &v