// SPDX-License-Identifier: GPL-2.0-or-later // Copyright (C) 2026 Bryan Joshua Pedini package main import ( "errors" "io/fs" "net/http" "net/http/httptest" "regexp" "strings" "testing" "testing/fstest" ) type failingFS struct{} func (failingFS) Open(string) (fs.File, error) { return nil, errors.New("open failed") } func testStaticFS() fstest.MapFS { return fstest.MapFS{ "css/app.css": {Data: []byte("body{}")}, "js/app.js": {Data: []byte("export {};")}, "js/page.js": {Data: []byte("export {};")}, "icon.svg": {Data: []byte("")}, "data.bin": {Data: []byte{1, 2, 3}}, } } func mustRenderer(t *testing.T) *pageRenderer { t.Helper() renderer, err := newPageRenderer() if err != nil { t.Fatalf("newPageRenderer: %v", err) } return renderer } func TestStaticHashStable(t *testing.T) { first, err := staticHash(testStaticFS()) if err != nil { t.Fatal(err) } second, err := staticHash(testStaticFS()) if err != nil { t.Fatal(err) } if first != second { t.Fatalf("hash is not stable: %s != %s", first, second) } if len(first) != 16 { t.Fatalf("hash length = %d, want 16", len(first)) } } func TestStaticHashDetectsChanges(t *testing.T) { base, _ := staticHash(testStaticFS()) changed := testStaticFS() changed["css/app.css"] = &fstest.MapFile{Data: []byte("body{color:red}")} renamed := testStaticFS() renamed["css/other.css"] = renamed["css/app.css"] delete(renamed, "css/app.css") added := testStaticFS() added["js/extra.js"] = &fstest.MapFile{Data: []byte("")} for name, fsys := range map[string]fstest.MapFS{"content": changed, "name": renamed, "added": added} { got, err := staticHash(fsys) if err != nil { t.Fatal(err) } if got == base { t.Errorf("hash did not change after %s change", name) } } } func TestStaticHashBoundaryBetweenFiles(t *testing.T) { left := fstest.MapFS{"a": {Data: []byte("bc")}, "d": {Data: []byte("e")}} right := fstest.MapFS{"a": {Data: []byte("b")}, "cd": {Data: []byte("e")}} one, _ := staticHash(left) two, _ := staticHash(right) if one == two { t.Fatal("different file layouts produced the same hash") } } func TestStaticHashError(t *testing.T) { if _, err := staticHash(failingFS{}); err == nil { t.Fatal("expected an error") } } func TestNewPageRendererErrors(t *testing.T) { good := fstest.MapFS{ "layout.html": {Data: []byte(`{{define "layout"}}{{template "content" .}}{{end}}`)}, "partials/p.html": {Data: []byte(`{{define "p"}}x{{end}}`)}, "pages/home.html": {Data: []byte(`{{define "content"}}ok{{end}}`)}, "pages/broken.html": {Data: []byte(`{{define "content"}}{{end`)}, "pages/missing.html": {Data: []byte(`{{define "other"}}x{{end}}`)}, } if _, err := newPageRendererFS(failingFS{}, testStaticFS()); err == nil { t.Error("expected an error for an unreadable template tree") } if _, err := newPageRendererFS(good, failingFS{}); err == nil { t.Error("expected an error for an unreadable static tree") } empty := fstest.MapFS{"layout.html": {Data: []byte("x")}} if _, err := newPageRendererFS(empty, testStaticFS()); err == nil { t.Error("expected an error without pages") } if _, err := newPageRendererFS(good, testStaticFS()); err == nil { t.Error("expected an error for a template that does not parse") } delete(good, "pages/broken.html") if _, err := newPageRendererFS(good, testStaticFS()); err != nil { t.Errorf("unexpected error: %v", err) } } func TestStaticHandler(t *testing.T) { renderer, err := newPageRendererFS(minimalTemplates(), testStaticFS()) if err != nil { t.Fatal(err) } handler := renderer.staticHandler() prefix := renderer.staticPrefix() if !strings.HasPrefix(prefix, "/static/") || !strings.HasSuffix(prefix, "/") { t.Fatalf("unexpected prefix %q", prefix) } cases := map[string]string{ "css/app.css": "text/css; charset=utf-8", "js/app.js": "text/javascript; charset=utf-8", "icon.svg": "image/svg+xml", "data.bin": "application/octet-stream", } for name, contentType := range cases { rec := httptest.NewRecorder() handler.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, prefix+name, nil)) if rec.Code != http.StatusOK { t.Errorf("%s: status %d", name, rec.Code) continue } if got := rec.Header().Get("Content-Type"); got != contentType { t.Errorf("%s: content type %q, want %q", name, got, contentType) } if got := rec.Header().Get("Cache-Control"); got != "public, max-age=31536000, immutable" { t.Errorf("%s: cache control %q", name, got) } if got := rec.Header().Get("X-Content-Type-Options"); got != "nosniff" { t.Errorf("%s: nosniff %q", name, got) } } rec := httptest.NewRecorder() handler.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, prefix+"css/app.css", nil)) if rec.Body.String() != "body{}" { t.Errorf("body = %q", rec.Body.String()) } } func TestStaticHandlerHead(t *testing.T) { renderer, _ := newPageRendererFS(minimalTemplates(), testStaticFS()) rec := httptest.NewRecorder() renderer.staticHandler().ServeHTTP(rec, httptest.NewRequest(http.MethodHead, renderer.staticPrefix()+"css/app.css", nil)) if rec.Code != http.StatusOK || rec.Body.Len() != 0 { t.Fatalf("HEAD: status %d, body %d bytes", rec.Code, rec.Body.Len()) } if rec.Header().Get("Content-Length") != "6" { t.Errorf("content length %q", rec.Header().Get("Content-Length")) } } func TestStaticHandlerMethod(t *testing.T) { renderer, _ := newPageRendererFS(minimalTemplates(), testStaticFS()) rec := httptest.NewRecorder() renderer.staticHandler().ServeHTTP(rec, httptest.NewRequest(http.MethodPost, renderer.staticPrefix()+"css/app.css", nil)) if rec.Code != http.StatusMethodNotAllowed || rec.Header().Get("Allow") != "GET, HEAD" { t.Fatalf("POST: status %d, allow %q", rec.Code, rec.Header().Get("Allow")) } } func TestStaticHandlerNotFound(t *testing.T) { renderer, _ := newPageRendererFS(minimalTemplates(), testStaticFS()) handler := renderer.staticHandler() prefix := renderer.staticPrefix() paths := []string{ "/static/0000000000000000/css/app.css", "/static/css/app.css", "/static/", "/other/css/app.css", prefix, prefix + "missing.css", prefix + "css", prefix + "css/", prefix + "js/", prefix + "../css/app.css", prefix + "css/../../css/app.css", prefix + "css/../css/app.css", prefix + "./css/app.css", prefix + "/css/app.css", prefix + "css//app.css", prefix + "..", prefix + "css\\app.css", prefix + "..\\css\\app.css", prefix + "css/app.css/", prefix + "css/app.css\x00.png", } for _, p := range paths { req := httptest.NewRequest(http.MethodGet, "/", nil) req.URL.Path = p rec := httptest.NewRecorder() handler.ServeHTTP(rec, req) if rec.Code != http.StatusNotFound { t.Errorf("%q: status %d, want 404", p, rec.Code) } if strings.Contains(rec.Body.String(), "app.css") && strings.Contains(rec.Body.String(), "body{}") { t.Errorf("%q: leaked a file", p) } } } func TestStaticHandlerEmbeddedAssets(t *testing.T) { renderer := mustRenderer(t) handler := renderer.staticHandler() for _, name := range []string{"css/app.css", "js/common.js", "js/records.js", "js/zones.js", "js/zone.js", "js/import.js", "js/audit.js", "js/account.js", "js/users.js", "js/user.js"} { rec := httptest.NewRecorder() handler.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, renderer.staticPrefix()+name, nil)) if rec.Code != http.StatusOK { t.Errorf("%s: status %d", name, rec.Code) } if rec.Body.Len() == 0 { t.Errorf("%s: empty body", name) } } } func TestEmbeddedFilesRules(t *testing.T) { check := func(root fs.FS, name string) { err := fs.WalkDir(root, ".", func(p string, entry fs.DirEntry, err error) error { if err != nil || entry.IsDir() { return err } data, err := fs.ReadFile(root, p) if err != nil { return err } text := string(data) if strings.Contains(text, "\u2014") { t.Errorf("%s/%s contains an em dash", name, p) } if strings.HasSuffix(p, ".js") || strings.HasSuffix(p, ".css") { if !strings.Contains(text[:min(len(text), 200)], "SPDX-License-Identifier: GPL-2.0-or-later") { t.Errorf("%s/%s lacks the SPDX header", name, p) } } if strings.HasSuffix(p, ".js") { for _, banned := range []string{"innerHTML", "outerHTML", "insertAdjacentHTML", "document.write", "eval(", "setAttribute(\"style\""} { if strings.Contains(text, banned) { t.Errorf("%s/%s uses %s", name, p, banned) } } } return nil }) if err != nil { t.Fatal(err) } } templates, _ := fs.Sub(uiTemplateFiles, "templates/html") static, _ := fs.Sub(uiStaticFiles, "static") check(templates, "templates") check(static, "static") } func minimalTemplates() fstest.MapFS { return fstest.MapFS{ "layout.html": {Data: []byte(`{{define "layout"}}{{template "content" .}}{{end}}`)}, "partials/p.html": {Data: []byte(`{{define "p"}}x{{end}}`)}, "pages/home.html": {Data: []byte(`{{define "content"}}home {{.Username}}{{end}}`)}, } } func TestRenderErrors(t *testing.T) { renderer, err := newPageRendererFS(minimalTemplates(), testStaticFS()) if err != nil { t.Fatal(err) } rec := httptest.NewRecorder() renderer.render(rec, http.StatusOK, "nope", pageData{}) if rec.Code != http.StatusInternalServerError { t.Errorf("unknown page: status %d", rec.Code) } } func TestRenderExecutionError(t *testing.T) { templates := fstest.MapFS{ "layout.html": {Data: []byte(`{{define "layout"}}partial{{template "content" .}}{{end}}`)}, "partials/p.html": {Data: []byte(`{{define "p"}}x{{end}}`)}, "pages/bad.html": {Data: []byte(`{{define "content"}}{{call .Username}}{{end}}`)}, } renderer, err := newPageRendererFS(templates, testStaticFS()) if err != nil { t.Fatal(err) } rec := httptest.NewRecorder() renderer.render(rec, http.StatusOK, "bad", pageData{Username: "x"}) if rec.Code != http.StatusInternalServerError { t.Fatalf("status %d, want 500", rec.Code) } if strings.Contains(rec.Body.String(), "partial") { t.Error("partial output was written before the error") } } func TestPageDataSection(t *testing.T) { cases := map[string]string{ "zones": "zones", "zone": "zones", "import": "zones", "users": "users", "user": "users", "audit": "audit", "account": "account", "login": "login", } for page, want := range cases { if got := (pageData{Page: page}).Section(); got != want { t.Errorf("Section(%s) = %q, want %q", page, got, want) } } if !(pageData{Role: "admin"}).IsAdmin() || (pageData{Role: "user"}).IsAdmin() || (pageData{}).IsAdmin() { t.Error("IsAdmin is wrong") } } var ( styleAttr = regexp.MustCompile(`(?i)\sstyle\s*=`) eventAttr = regexp.MustCompile(`(?i)\son[a-z]+\s*=`) inlineScript = regexp.MustCompile(`(?is)]*)?>`) formControl = regexp.MustCompile(`(?is)<(input|select|textarea)\s[^>]*>`) idAttr = regexp.MustCompile(`\sid="([^"]+)"`) typeHidden = regexp.MustCompile(`type="hidden"`) ariaLabelAttr = regexp.MustCompile(`aria-label="`) ) func renderPage(t *testing.T, renderer *pageRenderer, page string, data pageData) (int, string, http.Header) { t.Helper() rec := httptest.NewRecorder() renderer.render(rec, http.StatusOK, page, data) return rec.Code, rec.Body.String(), rec.Header() } var allPages = []string{"login", "zones", "zone", "import", "audit", "account", "users", "user", "not_found", "forbidden"} func dataFor(role string) pageData { data := pageData{AppName: "Test DNS", Zone: "example.org.", TargetUser: "bob"} switch role { case "admin": data.Username, data.Role = "alice", "admin" case "user": data.Username, data.Role = "carol", "user" } return data } func TestRenderEveryPage(t *testing.T) { renderer := mustRenderer(t) for _, page := range allPages { for _, role := range []string{"admin", "user", "anonymous"} { status, body, header := renderPage(t, renderer, page, dataFor(role)) name := page + "/" + role if status != http.StatusOK { t.Errorf("%s: status %d", name, status) } if got := header.Get("Content-Type"); got != "text/html; charset=utf-8" { t.Errorf("%s: content type %q", name, got) } if header.Get("Cache-Control") != "no-store" { t.Errorf("%s: cache control %q", name, header.Get("Cache-Control")) } if !strings.HasPrefix(body, "") { t.Errorf("%s: output does not start with the doctype", name) } if !strings.Contains(body, "") || !strings.Contains(body, "- Test DNS") { t.Errorf("%s: title is wrong", name) } if !strings.Contains(body, renderer.staticPrefix()+"css/app.css") { t.Errorf("%s: stylesheet missing", name) } if !strings.Contains(body, `aria-live="polite"`) { t.Errorf("%s: live region missing", name) } if styleAttr.MatchString(body) || eventAttr.MatchString(body) { t.Errorf("%s: inline style or event handler", name) } for _, m := range inlineScript.FindAllString(body, -1) { if !strings.Contains(m, `src="`+renderer.staticPrefix()+`js/`) || !strings.Contains(m, `type="module"`) { t.Errorf("%s: unexpected script tag %s", name, m) } } if strings.Contains(body, "") { idx := strings.Index(body, "") if strings.TrimSpace(body[idx+strings.Index(body[idx:], ">")+1:idx+end]) != "" { t.Errorf("%s: inline script body", name) } } checkLabels(t, name, body) } } } func checkLabels(t *testing.T, name, body string) { t.Helper() for _, loc := range formControl.FindAllStringIndex(body, -1) { control := body[loc[0]:loc[1]] if typeHidden.MatchString(control) || ariaLabelAttr.MatchString(control) { continue } if strings.HasSuffix(body[:loc[0]], "