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") { 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) } } }