- test(ui): avoid a literal em dash in the em dash check - fix(cli): accept any positive int64 audit count and share the last active admin rule - fix(api): limit audit before_id to 2^53-1 - fix(api): audit unmatched api requests, bound every request body and record audit write failures - fix(ui): recheck the account in the login transaction and require existing zones on zone pages - fix(api): recheck the acting admin and the stored password hash in change transactions - fix(db): keep committed outcomes on lock release failure, narrow the records contract and trace sql statements - fix(db): make the initial migration restartable and verify the application schema - fix(auth): never move last_seen_at backwards on concurrent session touches - test(api): cover lock release failure after commit and handler tracing without secrets - fix(test): redact credentials from mysql setup errors - fix(audit): retain addressed objects on admin refusals - test(db): cover migration restarts and records contract ranges in mysql - test(api): verify account races and audit rollback in mysql - fix(auth): reject password changes after account deletion - docs: document unknown api audit entries - fix(audit): bound failure retries and redact sensitive sql parameters - fix(test): isolate docker resources and cover image cli commands - test(auth): expect unauthorized after an account deletion race - fix(db): verify application column widths and foreign keys
702 lines
24 KiB
Go
702 lines
24 KiB
Go
// 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("<svg></svg>")},
|
|
"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)<script(\s[^>]*)?>`)
|
|
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, "<!DOCTYPE html>") {
|
|
t.Errorf("%s: output does not start with the doctype", name)
|
|
}
|
|
if !strings.Contains(body, "<title>") || !strings.Contains(body, "- Test DNS</title>") {
|
|
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, "<script") && strings.Contains(body, "</script>") {
|
|
idx := strings.Index(body, "<script")
|
|
end := strings.Index(body[idx:], "</script>")
|
|
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]], "<label class=\"choice\">") {
|
|
continue
|
|
}
|
|
match := idAttr.FindStringSubmatch(control)
|
|
if match == nil {
|
|
t.Errorf("%s: control without id or label: %s", name, control)
|
|
continue
|
|
}
|
|
if !strings.Contains(body, `for="`+match[1]+`"`) {
|
|
t.Errorf("%s: control %s has no label", name, match[1])
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestRenderScriptsPerPage(t *testing.T) {
|
|
renderer := mustRenderer(t)
|
|
for _, page := range []string{"zones", "zone", "import", "audit", "account", "users", "user"} {
|
|
_, body, _ := renderPage(t, renderer, page, dataFor("admin"))
|
|
want := `<script type="module" src="` + renderer.staticPrefix() + `js/` + page + `.js"></script>`
|
|
if !strings.Contains(body, want) {
|
|
t.Errorf("%s: missing %s", page, want)
|
|
}
|
|
}
|
|
for _, page := range []string{"login", "not_found", "forbidden"} {
|
|
_, body, _ := renderPage(t, renderer, page, dataFor("anonymous"))
|
|
if strings.Contains(body, "<script") {
|
|
t.Errorf("%s: unexpected script", page)
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestRenderLayoutNavigation(t *testing.T) {
|
|
renderer := mustRenderer(t)
|
|
_, admin, _ := renderPage(t, renderer, "zones", dataFor("admin"))
|
|
_, user, _ := renderPage(t, renderer, "zones", dataFor("user"))
|
|
_, anon, _ := renderPage(t, renderer, "login", dataFor("anonymous"))
|
|
for _, want := range []string{`href="/audit"`, `href="/account"`, `action="/logout"`, `method="post"`, `href="/users"`, `aria-current="page"`, ">alice<", ">admin<"} {
|
|
if !strings.Contains(admin, want) {
|
|
t.Errorf("admin layout lacks %s", want)
|
|
}
|
|
}
|
|
if strings.Contains(user, `href="/users"`) {
|
|
t.Error("user layout shows the Users link")
|
|
}
|
|
for _, want := range []string{`href="/audit"`, `href="/account"`, `action="/logout"`, ">carol<", ">user<"} {
|
|
if !strings.Contains(user, want) {
|
|
t.Errorf("user layout lacks %s", want)
|
|
}
|
|
}
|
|
for _, unwanted := range []string{`action="/logout"`, `href="/audit"`, `href="/account"`, `href="/users"`} {
|
|
if strings.Contains(anon, unwanted) {
|
|
t.Errorf("anonymous layout shows %s", unwanted)
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestRenderControlsByRole(t *testing.T) {
|
|
renderer := mustRenderer(t)
|
|
type check struct {
|
|
page string
|
|
adminOnly []string
|
|
everyoneSees []string
|
|
userOnlyExtra []string
|
|
}
|
|
checks := []check{
|
|
{
|
|
page: "zones",
|
|
adminOnly: []string{`id="new-zone"`, `id="zone-dialog"`, `id="zone-form"`, `name="extra_ns"`},
|
|
everyoneSees: []string{`id="zone-search"`, `id="zones-body"`},
|
|
},
|
|
{
|
|
page: "zone",
|
|
adminOnly: []string{`id="users-panel"`, `id="danger"`, `id="zone-delete-confirm"`, `id="zone-user-pick"`},
|
|
everyoneSees: []string{`id="record-add"`, `id="record-dialog"`, `id="soa-dialog"`, `id="bulk-delete"`, `id="filter-type"`, `id="filter-text"`, `id="export-link"`, `id="import-link"`, `id="problems-panel"`, `id="soa-managed"`},
|
|
},
|
|
{
|
|
page: "account",
|
|
everyoneSees: []string{`id="password-form"`, `name="current"`, `name="repeat"`},
|
|
userOnlyExtra: []string{`id="account-zones"`},
|
|
},
|
|
}
|
|
for _, c := range checks {
|
|
_, admin, _ := renderPage(t, renderer, c.page, dataFor("admin"))
|
|
_, user, _ := renderPage(t, renderer, c.page, dataFor("user"))
|
|
for _, want := range c.adminOnly {
|
|
if !strings.Contains(admin, want) {
|
|
t.Errorf("%s: admin lacks %s", c.page, want)
|
|
}
|
|
if strings.Contains(user, want) {
|
|
t.Errorf("%s: user has %s", c.page, want)
|
|
}
|
|
}
|
|
for _, want := range c.everyoneSees {
|
|
if !strings.Contains(admin, want) || !strings.Contains(user, want) {
|
|
t.Errorf("%s: %s missing for admin or user", c.page, want)
|
|
}
|
|
}
|
|
for _, want := range c.userOnlyExtra {
|
|
if strings.Contains(admin, want) || !strings.Contains(user, want) {
|
|
t.Errorf("%s: %s should be present for users only", c.page, want)
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestRenderUserPageSelfAndOther(t *testing.T) {
|
|
renderer := mustRenderer(t)
|
|
other := dataFor("admin")
|
|
other.TargetUser = "bob"
|
|
_, body, _ := renderPage(t, renderer, "user", other)
|
|
for _, want := range []string{`id="role-form"`, `id="password-form"`, `id="zone-add-form"`, `id="user-delete-form"`, `id="user-delete-confirm"`, `id="user-readonly"`} {
|
|
if !strings.Contains(body, want) {
|
|
t.Errorf("other user: missing %s", want)
|
|
}
|
|
}
|
|
self := dataFor("admin")
|
|
self.TargetUser = "alice"
|
|
_, body, _ = renderPage(t, renderer, "user", self)
|
|
for _, unwanted := range []string{`id="role-form"`, `id="password-form"`, `id="user-delete-form"`, `id="zone-add-form"`} {
|
|
if strings.Contains(body, unwanted) {
|
|
t.Errorf("own user: unexpected %s", unwanted)
|
|
}
|
|
}
|
|
if !strings.Contains(body, `href="/account"`) || !strings.Contains(body, `id="user-self"`) {
|
|
t.Error("own user: link to the account page missing")
|
|
}
|
|
}
|
|
|
|
func TestRenderUsersAndAuditAndImport(t *testing.T) {
|
|
renderer := mustRenderer(t)
|
|
_, users, _ := renderPage(t, renderer, "users", dataFor("admin"))
|
|
for _, want := range []string{`id="new-user"`, `id="show-deleted"`, `id="user-dialog"`, `name="username"`, `name="role"`, `name="password"`, `name="repeat"`} {
|
|
if !strings.Contains(users, want) {
|
|
t.Errorf("users: missing %s", want)
|
|
}
|
|
}
|
|
_, audit, _ := renderPage(t, renderer, "audit", dataFor("user"))
|
|
for _, want := range []string{`name="zone"`, `name="actor"`, `name="operation"`, `name="kind"`, `name="outcome"`, `id="audit-more"`, `<option>zone_import</option>`} {
|
|
if !strings.Contains(audit, want) {
|
|
t.Errorf("audit: missing %s", want)
|
|
}
|
|
}
|
|
_, imp, _ := renderPage(t, renderer, "import", dataFor("user"))
|
|
for _, want := range []string{`value="merge" checked`, `value="replace"`, `id="import-content"`, `id="import-file"`, `id="import-apply"`, `id="import-preview"`} {
|
|
if !strings.Contains(imp, want) {
|
|
t.Errorf("import: missing %s", want)
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestRenderRootAttributes(t *testing.T) {
|
|
renderer := mustRenderer(t)
|
|
_, body, _ := renderPage(t, renderer, "zone", dataFor("user"))
|
|
for _, want := range []string{`id="app"`, `data-page="zone"`, `data-username="carol"`, `data-role="user"`, `data-zone="example.org."`, `data-target-user="bob"`} {
|
|
if !strings.Contains(body, want) {
|
|
t.Errorf("root element lacks %s", want)
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestRenderLogin(t *testing.T) {
|
|
renderer := mustRenderer(t)
|
|
data := pageData{AppName: "Test DNS", Next: "/zones/example.org."}
|
|
_, body, _ := renderPage(t, renderer, "login", data)
|
|
for _, want := range []string{`action="/login"`, `method="post"`, `name="username"`, `name="password"`, `name="next" value="/zones/example.org."`} {
|
|
if !strings.Contains(body, want) {
|
|
t.Errorf("login: missing %s", want)
|
|
}
|
|
}
|
|
if strings.Contains(body, "No administrator exists") || strings.Contains(body, `role="alert"`) {
|
|
t.Error("login: unexpected notice")
|
|
}
|
|
|
|
data.NoActiveAdmin = true
|
|
_, body, _ = renderPage(t, renderer, "login", data)
|
|
if !strings.Contains(body, "No administrator exists") || !strings.Contains(body, "user add <username> admin") {
|
|
t.Error("login: bootstrap notice missing")
|
|
}
|
|
|
|
data.BootstrapCommand = "docker exec -i web /app user add <name> admin"
|
|
data.Error = "invalid username or password"
|
|
_, body, _ = renderPage(t, renderer, "login", data)
|
|
if !strings.Contains(body, "docker exec -i web /app user add <name> admin") {
|
|
t.Error("login: custom bootstrap command missing")
|
|
}
|
|
if !strings.Contains(body, `role="alert"`) || !strings.Contains(body, "invalid username or password") {
|
|
t.Error("login: error missing")
|
|
}
|
|
}
|
|
|
|
func TestRenderStatus(t *testing.T) {
|
|
renderer := mustRenderer(t)
|
|
for _, status := range []int{http.StatusNotFound, http.StatusForbidden, http.StatusUnauthorized, http.StatusTooManyRequests} {
|
|
rec := httptest.NewRecorder()
|
|
renderer.render(rec, status, "login", pageData{AppName: "x"})
|
|
if rec.Code != status {
|
|
t.Errorf("status %d, got %d", status, rec.Code)
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestRenderEscaping(t *testing.T) {
|
|
renderer := mustRenderer(t)
|
|
script := `<script>alert(1)</script>`
|
|
quote := `"><img src=x onerror=alert(1)>`
|
|
data := pageData{
|
|
AppName: script,
|
|
Username: script,
|
|
Role: "admin",
|
|
Zone: quote,
|
|
TargetUser: quote,
|
|
Next: quote,
|
|
Error: script,
|
|
}
|
|
for _, page := range allPages {
|
|
_, body, _ := renderPage(t, renderer, page, data)
|
|
if strings.Contains(body, script) {
|
|
t.Errorf("%s: unescaped script", page)
|
|
}
|
|
if strings.Contains(body, quote) || strings.Contains(body, "<img") {
|
|
t.Errorf("%s: unescaped attribute payload", page)
|
|
}
|
|
for _, m := range inlineScript.FindAllString(body, -1) {
|
|
if !strings.Contains(m, "src=") {
|
|
t.Errorf("%s: injected script tag %s", page, m)
|
|
}
|
|
}
|
|
}
|
|
_, body, _ := renderPage(t, renderer, "zone", data)
|
|
if !strings.Contains(body, "<script>alert(1)</script>") {
|
|
t.Error("zone: escaped username missing")
|
|
}
|
|
if !strings.Contains(body, ""><img src=x onerror=alert(1)>") {
|
|
t.Error("zone: escaped zone name missing")
|
|
}
|
|
_, body, _ = renderPage(t, renderer, "login", data)
|
|
if !strings.Contains(body, "<script>alert(1)</script>") {
|
|
t.Error("login: escaped error missing")
|
|
}
|
|
}
|
|
|
|
func TestZonePagesRequireAnExistingZone(t *testing.T) {
|
|
h := newWebHarness(t)
|
|
admin := h.user("admin", roleAdmin)
|
|
alice := h.user("alice", roleUser)
|
|
h.store.addZone(testZone)
|
|
h.store.addZone(otherZone)
|
|
h.store.addZone("undotted.org")
|
|
h.store.delegate(testZone, alice)
|
|
h.store.delegate("stale.org.", alice)
|
|
at, ut := h.login(admin), h.login(alice)
|
|
for _, suffix := range []string{"", "/import"} {
|
|
page := func(token, zone string) webResult {
|
|
return h.do(webRequest{method: "GET", path: "/zones/" + zone + suffix, token: token})
|
|
}
|
|
for _, c := range []struct {
|
|
token, zone string
|
|
status int
|
|
}{
|
|
{at, "example.org.", 200},
|
|
{at, "Example.ORG", 200},
|
|
{at, "undotted.org", 200},
|
|
{at, "missing.org", 404},
|
|
{at, "stale.org.", 404},
|
|
{ut, "example.org", 200},
|
|
{ut, "stale.org.", 404},
|
|
{ut, "other.org.", 404},
|
|
{ut, "missing.org", 404},
|
|
} {
|
|
if res := page(c.token, c.zone); res.status != c.status || len(res.audit) != 0 {
|
|
t.Errorf("%s%s: %d, want %d", c.zone, suffix, res.status, c.status)
|
|
}
|
|
}
|
|
missing, stale, other := page(ut, "missing.org"), page(ut, "stale.org"), page(ut, "other.org")
|
|
if missing.body != stale.body || missing.body != other.body || !strings.Contains(missing.body, "alice") {
|
|
t.Errorf("%s: not found pages differ", suffix)
|
|
}
|
|
if adminMissing := page(at, "missing.org"); !strings.Contains(adminMissing.body, "admin") {
|
|
t.Errorf("%s: admin not found page", suffix)
|
|
}
|
|
}
|
|
h.store.failOn["ZoneExists"] = errDatabase
|
|
if res := h.do(webRequest{method: "GET", path: "/zones/example.org.", token: at}); res.status != 503 {
|
|
t.Fatal(res.status)
|
|
}
|
|
}
|