Files
coredns-web-ui/middleware_test.go
T
bryanpedini 65d16c2fc6
Test / test (push) Successful in 25m39s
Build and publish image / image (push) Successful in 16m16s
fix: replace named locks with Galera-compatible row locks
2026-11-20 16:27:15 +01:00

919 lines
37 KiB
Go

// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright (C) 2026 Bryan Joshua Pedini
package main
import (
"bytes"
"context"
"database/sql"
"database/sql/driver"
"encoding/json"
"errors"
"fmt"
"io"
"log/slog"
"net"
"net/http"
"net/http/httptest"
"net/netip"
"reflect"
"slices"
"strings"
"testing"
"time"
"github.com/go-sql-driver/mysql"
)
func decodeRequest(body, contentType string, limit int64) *apiContext {
r := httptest.NewRequest("POST", "/api/v1/x", strings.NewReader(body))
if contentType != "" {
r.Header.Set("Content-Type", contentType)
}
return &apiContext{Request: r, bodyLimit: limit}
}
type decodeTarget struct {
Name string `json:"name"`
TTL int64 `json:"ttl"`
Flag bool `json:"flag"`
Items []int `json:"items"`
}
func TestDecodeJSON(t *testing.T) {
cases := []struct {
body string
ctype string
limit int64
status int
msg string
field string
}{
{`{"name":"a","ttl":5}`, "application/json", 0, 0, "", ""},
{`{"name":"a"}`, "application/json; charset=utf-8", 0, 0, "", ""},
{" \n{} \n", "application/json", 0, 0, "", ""},
{"", "application/json", 0, 400, "request body is required", ""},
{" ", "", 0, 415, "content type must be application/json", ""},
{" ", "application/json", 0, 400, "request body is required", ""},
{strings.Repeat(" ", 70000), "application/json", 0, 413, "request body too large", ""},
{"{\"name\":\"\xff\"}", "application/json", 0, 400, "request body must be valid UTF-8", ""},
{`{"name":"a"}`, "text/plain", 0, 415, "content type must be application/json", ""},
{`{"name":"a"}`, "", 0, 415, "content type must be application/json", ""},
{`{"name":"a"}`, "application/jsonx", 0, 415, "content type must be application/json", ""},
{`{"name":"` + strings.Repeat("a", 70000) + `"}`, "application/json", 0, 413, "request body too large", ""},
{`{"name":"abcdef"}`, "application/json", 10, 413, "request body too large", ""},
{`{"name":"a"}`, "application/json", 12, 0, "", ""},
{`[1,2]`, "application/json", 0, 400, "request body must be a JSON object", ""},
{`"x"`, "application/json", 0, 400, "request body must be a JSON object", ""},
{`{"name":`, "application/json", 0, 400, "malformed JSON", ""},
{`{"name":"a",}`, "application/json", 0, 400, "malformed JSON", ""},
{`{"other":1}`, "application/json", 0, 400, "request body has an unknown field", ""},
{`{"name":"a"}{"name":"b"}`, "application/json", 0, 400, "request body has trailing data", ""},
{`{"name":"a"} x`, "application/json", 0, 400, "request body has trailing data", ""},
{`{"ttl":"3600"}`, "application/json", 0, 422, "invalid field type", "ttl"},
{`{"ttl":1.5}`, "application/json", 0, 422, "invalid field type", "ttl"},
{`{"ttl":99999999999999999999}`, "application/json", 0, 422, "invalid field type", "ttl"},
{`{"name":5}`, "application/json", 0, 422, "invalid field type", "name"},
{`{"flag":"yes"}`, "application/json", 0, 422, "invalid field type", "flag"},
{`{"items":{}}`, "application/json", 0, 422, "invalid field type", "items"},
}
for i, c := range cases {
var dst decodeTarget
err := decodeRequest(c.body, c.ctype, c.limit).decodeJSON(&dst)
if c.status == 0 {
if err != nil {
t.Errorf("case %d: %v", i, err)
}
continue
}
var ae *apiError
if !errors.As(err, &ae) || ae.Status != c.status || ae.Message != c.msg || (c.field != "" && ae.Fields[c.field] == "") {
t.Errorf("case %d: %#v", i, err)
}
}
var dst decodeTarget
if err := decodeRequest(`{"name":"x","ttl":7,"flag":true,"items":[1]}`, "application/json", 0).decodeJSON(&dst); err != nil || dst.Name != "x" || dst.TTL != 7 || !dst.Flag || dst.Items[0] != 1 {
t.Fatal(dst, err)
}
c := decodeRequest("{}", "application/json", 0)
c.Request.Body = errReadCloser{}
var ae *apiError
if err := c.decodeJSON(&dst); !errors.As(err, &ae) || ae.Status != 400 {
t.Fatal(err)
}
}
type errReadCloser struct{}
func (errReadCloser) Read([]byte) (int, error) { return 0, errors.New("broken body") }
func (errReadCloser) Close() error { return nil }
func TestJSONTypeMessages(t *testing.T) {
var s struct {
I int `json:"i"`
U uint8 `json:"u"`
F float64 `json:"f"`
S string `json:"s"`
B bool `json:"b"`
A []int `json:"a"`
M map[string]int
O struct{} `json:"o"`
P *int `json:"p"`
}
cases := map[string]string{
`{"i":"x"}`: "must be a number",
`{"i":1.5}`: "must be an integer in range",
`{"u":300}`: "must be an integer in range",
`{"f":"x"}`: "must be a number",
`{"s":1}`: "must be a string",
`{"b":1}`: "must be a boolean",
`{"a":1}`: "must be an array",
`{"M":1}`: "must be an object",
`{"o":1}`: "must be an object",
`{"p":"x"}`: "must be a number",
`{"o":[1]}`: "must be an object",
`{"a":["x"]}`: "must be a number",
}
for body, want := range cases {
err := json.Unmarshal([]byte(body), &s)
var te *json.UnmarshalTypeError
if !errors.As(err, &te) {
t.Fatalf("%s: %v", body, err)
}
if got := jsonTypeMessage(te); got != want {
t.Errorf("%s: %q", body, got)
}
}
if jsonTypeMessage(&json.UnmarshalTypeError{}) != "has the wrong type" {
t.Fatal("nil type")
}
var ch chan int
if jsonTypeMessage(&json.UnmarshalTypeError{Type: reflect.TypeOf(ch)}) != "has the wrong type" {
t.Fatal("other kind")
}
}
func TestClientOrigin(t *testing.T) {
trusted := []netip.Prefix{netip.MustParsePrefix("10.0.0.0/8"), netip.MustParsePrefix("fd00::/8")}
cases := []struct {
remote string
xff []string
trusted []netip.Prefix
want string
}{
{"192.0.2.1:1234", nil, nil, "192.0.2.1"},
{"192.0.2.1:1234", []string{"203.0.113.9"}, nil, "192.0.2.1"},
{"192.0.2.1:1234", []string{"203.0.113.9"}, trusted, "192.0.2.1"},
{"10.1.2.3:1234", []string{"203.0.113.9"}, trusted, "203.0.113.9"},
{"10.1.2.3:1234", []string{"198.51.100.1, 203.0.113.9, 10.9.9.9"}, trusted, "203.0.113.9"},
{"10.1.2.3:1234", []string{"198.51.100.1", "203.0.113.9, 10.9.9.9"}, trusted, "203.0.113.9"},
{"10.1.2.3:1234", []string{"10.5.5.5, 10.6.6.6"}, trusted, "10.5.5.5"},
{"10.1.2.3:1234", nil, trusted, "10.1.2.3"},
{"10.1.2.3:1234", []string{"garbage"}, trusted, "10.1.2.3"},
{"10.1.2.3:1234", []string{"203.0.113.7, garbage, 10.9.9.9"}, trusted, "10.9.9.9"},
{"10.1.2.3:1234", []string{"203.0.113.9:5555"}, trusted, "203.0.113.9"},
{"10.1.2.3:1234", []string{"[2001:db8::7]:443"}, trusted, "2001:db8::7"},
{"10.1.2.3:1234", []string{"[2001:db8::8]"}, trusted, "2001:db8::8"},
{"[2001:db8::1]:443", nil, nil, "2001:db8::1"},
{"[fd00::1]:443", []string{"2001:db8::5"}, trusted, "2001:db8::5"},
{"[fe80::1%eth0]:443", nil, nil, "fe80::1"},
{"[::ffff:192.0.2.4]:443", nil, nil, "192.0.2.4"},
{"[::ffff:10.0.0.4]:443", []string{"::ffff:203.0.113.4"}, trusted, "203.0.113.4"},
{"pipe", nil, nil, "pipe"},
{"bad\x00host", nil, nil, "bad host"},
}
for _, c := range cases {
r := httptest.NewRequest("GET", "/", nil)
r.RemoteAddr = c.remote
for _, v := range c.xff {
r.Header.Add("X-Forwarded-For", v)
}
if got := clientOrigin(r, c.trusted); got != c.want {
t.Errorf("%s %v: %q, want %q", c.remote, c.xff, got, c.want)
}
}
}
func TestSecurityHeadersEverywhere(t *testing.T) {
h := newWebHarness(t)
admin := h.user("admin", roleAdmin)
token := h.login(admin)
paths := []webRequest{
{method: "GET", path: "/login"},
{method: "GET", path: "/", token: token},
{method: "GET", path: "/"},
{method: "GET", path: "/version"},
{method: "GET", path: "/missing"},
{method: "GET", path: "/api/v1/account"},
{method: "GET", path: "/api/v1/account", token: token},
{method: "GET", path: "/api/v1/nothing"},
{method: "POST", path: "/api/v1/users", header: map[string]string{"Sec-Fetch-Site": "cross-site"}},
{method: "GET", path: h.s.pages.staticPrefix() + "css/app.css"},
{method: "GET", path: "/health"},
}
for _, p := range paths {
res := h.do(p)
hd := res.header
if hd.Get("Content-Security-Policy") != "default-src 'none'; script-src 'self'; style-src 'self'; img-src 'self' data:; connect-src 'self'; form-action 'self'; frame-ancestors 'none'; base-uri 'none'" ||
hd.Get("X-Content-Type-Options") != "nosniff" || hd.Get("Referrer-Policy") != "no-referrer" {
t.Errorf("%s %s: %v", p.method, p.path, hd)
}
wantCache := "no-store"
if strings.HasPrefix(p.path, "/static/") {
wantCache = "public, max-age=31536000, immutable"
}
if hd.Get("Cache-Control") != wantCache {
t.Errorf("%s: cache %q", p.path, hd.Get("Cache-Control"))
}
}
}
func TestCrossOriginProtection(t *testing.T) {
h := newWebHarness(t)
admin := h.user("admin", roleAdmin)
token := h.login(admin)
refused := []webRequest{
{method: "POST", path: "/api/v1/users", token: token, body: `{}`, header: map[string]string{"Sec-Fetch-Site": "cross-site"}},
{method: "PUT", path: "/api/v1/account/password", token: token, body: `{}`, header: map[string]string{"Sec-Fetch-Site": "same-site"}},
{method: "DELETE", path: "/api/v1/users/bob", token: token, header: map[string]string{"Origin": "https://evil.example"}},
{method: "POST", path: "/login", body: "username=admin&password=x", ctype: "application/x-www-form-urlencoded", header: map[string]string{"Sec-Fetch-Site": "cross-site"}},
{method: "POST", path: "/logout", token: token, header: map[string]string{"Origin": "https://evil.example"}},
}
for _, r := range refused {
res := h.do(r)
if res.status != http.StatusForbidden || len(res.audit) != 0 {
t.Fatalf("%s %s: %d %d", r.method, r.path, res.status, len(res.audit))
}
if strings.HasPrefix(r.path, "/api/") && res.body != `{"error":"cross-origin request refused"}` {
t.Fatalf("%s", res.body)
}
}
if h.store.sessionCount(admin.ID) != 1 {
t.Fatal("refused logout ended the session")
}
if !strings.Contains(h.logs.String(), "cross-origin request refused") {
t.Fatal("refusal not logged")
}
res := h.do(webRequest{method: "GET", path: "/api/v1/account", token: token, header: map[string]string{"Sec-Fetch-Site": "cross-site"}})
if res.status != 200 {
t.Fatalf("safe method refused: %d", res.status)
}
res = h.do(webRequest{method: "PUT", path: "/api/v1/users/admin/role", token: token, body: `{"role":"user"}`, header: map[string]string{"Sec-Fetch-Site": "same-origin"}})
if res.status != http.StatusForbidden || res.body != `{"error":"use the account page to change your own account"}` || len(res.audit) != 1 {
t.Fatalf("same-origin request: %d %s", res.status, res.body)
}
res = h.do(webRequest{method: "POST", path: "/api/v1/users", token: token, body: `{"username":"x1","role":"user","password":"long-enough-pw"}`, header: map[string]string{"Origin": "http://example.com"}})
if res.status != http.StatusCreated {
t.Fatalf("matching origin refused: %d %s", res.status, res.body)
}
}
func TestAPIRouterNotFoundAndMethods(t *testing.T) {
h := newWebHarness(t)
token := h.login(h.user("admin", roleAdmin))
for _, p := range []string{"/api/v1/nothing", "/api/v1/", "/api/v2/account", "/api/v1/zones/a/b/c/d/e", "/api/v1/account/password/x",
"/api/v1//account", "/api/v1/account/../users", "/api/v1/./account"} {
res := h.do(webRequest{method: "GET", path: p, token: token})
if res.status != 404 || res.body != `{"error":"not found"}` || res.header.Get("Content-Type") != "application/json" {
t.Errorf("%s: %d %s", p, res.status, res.body)
}
e := expectOneAudit(t, res, opAPIUnknown, 404)
if e.Error.String != msgNotFound || e.Actor != "admin" || e.UserID.Int64 != 1 || e.Zone.Valid || e.TargetUserID.Valid || e.Before != nil || e.After != nil {
t.Errorf("%s: audit %+v", p, e)
}
res = h.do(webRequest{method: "GET", path: p})
if res.status != 401 || res.body != `{"error":"authentication required"}` || len(res.audit) != 0 {
t.Errorf("%s without session: %d %s %d", p, res.status, res.body, len(res.audit))
}
}
cases := map[string]string{
"PATCH /api/v1/account": "GET",
"POST /api/v1/account": "GET",
"GET /api/v1/account/password": "PUT",
"PUT /api/v1/users": "GET, POST",
"POST /api/v1/zones/example.org.": "DELETE, GET",
"GET /api/v1/zones/example.org./records/delete": "POST",
"PATCH /api/v1/zones/example.org./records/1": "DELETE, PUT",
"POST /api/v1/zones/example.org./users/bob": "DELETE, PUT",
"HEAD /api/v1/audit": "GET",
}
for req, allow := range cases {
method, path, _ := strings.Cut(req, " ")
res := h.do(webRequest{method: method, path: path, token: token})
if res.status != 405 || res.header.Get("Allow") != allow {
t.Errorf("%s: %d %q", req, res.status, res.header.Get("Allow"))
}
if e := expectOneAudit(t, res, opAPIUnknown, 405); e.Error.String != msgMethodNotAllowed {
t.Errorf("%s: audit %+v", req, e)
}
if method != "HEAD" && res.body != `{"error":"method not allowed"}` {
t.Errorf("%s: %s", req, res.body)
}
res = h.do(webRequest{method: method, path: path})
if res.status != 401 || len(res.audit) != 0 {
t.Errorf("%s without session: %d %d", req, res.status, len(res.audit))
}
}
}
func TestAPIAuthentication(t *testing.T) {
h := newWebHarness(t)
alice := h.user("alice", roleUser)
gone := h.user("gone", roleUser)
goneToken := h.login(gone)
gone.DeletedAt = sql.NullTime{Time: webNow, Valid: true}
h.store.setUser(gone)
fresh := h.login(alice)
stale := h.store.addSession(alice, webNow.Add(-2*time.Hour), webNow.Add(-time.Hour))
old := h.store.addSession(alice, webNow.Add(-12*time.Hour), webNow.Add(-time.Minute))
unknown, _, _ := newSessionToken(strings.NewReader(strings.Repeat("u", 32)))
for name, token := range map[string]string{"none": "", "malformed": "abc", "unknown": unknown, "idle": stale, "max age": old, "deleted user": goneToken} {
res := h.api("GET", "/account", token, "")
if res.status != 401 || res.body != `{"error":"authentication required"}` || len(res.audit) != 0 {
t.Errorf("%s: %d %s %d", name, res.status, res.body, len(res.audit))
}
}
if res := h.api("GET", "/account", fresh, ""); res.status != 200 {
t.Fatal(res.status)
}
h.store.failOn["SessionByTokenHash"] = errDatabase
res := h.api("GET", "/account", fresh, "")
if res.status != 503 || res.body != `{"error":"database unavailable"}` || len(res.audit) != 0 {
t.Fatalf("%d %s", res.status, res.body)
}
h.store.failOn["SessionByTokenHash"] = errors.New("syntax error near SELECT")
res = h.api("GET", "/account", fresh, "")
if res.status != 500 || res.body != `{"error":"internal error"}` {
t.Fatalf("%d %s", res.status, res.body)
}
h.s.store = nil
if res := h.api("GET", "/account", fresh, ""); res.status != 503 {
t.Fatal(res.status)
}
if res := h.api("GET", "/account", "", ""); res.status != 401 {
t.Fatal(res.status)
}
}
func TestSessionTouchedAtMostOncePerMinute(t *testing.T) {
h := newWebHarness(t)
alice := h.user("alice", roleUser)
token := h.login(alice)
h.clock.advance(30 * time.Second)
h.api("GET", "/account", token, "")
if h.store.called("TouchSession") != 0 {
t.Fatal("touched within a minute")
}
h.clock.advance(31 * time.Second)
h.api("GET", "/account", token, "")
h.api("GET", "/account", token, "")
if h.store.called("TouchSession") != 1 {
t.Fatal(h.store.called("TouchSession"))
}
h.clock.advance(59 * time.Minute)
if res := h.api("GET", "/account", token, ""); res.status != 200 {
t.Fatal("touch did not extend the idle timeout")
}
h.clock.advance(time.Hour)
if res := h.api("GET", "/account", token, ""); res.status != 401 {
t.Fatal("idle session accepted")
}
token = h.login(alice)
h.clock.advance(2 * time.Minute)
h.store.failOn["TouchSession"] = errors.New("touch failed")
if res := h.api("GET", "/account", token, ""); res.status != 200 || !strings.Contains(h.logs.String(), "session touch failed") {
t.Fatal("touch failure must not fail the request")
}
}
func TestRoleReadOnEveryRequest(t *testing.T) {
h := newWebHarness(t)
h.user("root", roleAdmin)
bob := h.user("bob", roleUser)
token := h.login(bob)
if res := h.api("GET", "/users", token, ""); res.status != 403 {
t.Fatal(res.status)
}
bob.Role = roleAdmin
h.store.setUser(bob)
if res := h.api("GET", "/users", token, ""); res.status != 200 {
t.Fatal("promotion not applied on the next request")
}
bob.Role = roleUser
h.store.setUser(bob)
if res := h.api("GET", "/users", token, ""); res.status != 403 {
t.Fatal("demotion not applied on the next request")
}
}
func frameworkTestHandlers(extra map[string]apiHandler) map[string]apiHandler {
m := map[string]apiHandler{}
for _, r := range apiRoutes {
m[r.Operation] = func(ctx context.Context, c *apiContext) (apiResponse, error) {
return okJSON(map[string]string{"zone": c.Zone}), nil
}
}
for k, v := range extra {
m[k] = v
}
return m
}
func TestFrameworkErrorMapping(t *testing.T) {
var lastCtx *apiContext
handlers := frameworkTestHandlers(map[string]apiHandler{
opZoneList: func(ctx context.Context, c *apiContext) (apiResponse, error) {
lastCtx = c
switch c.Request.URL.Query().Get("case") {
case "fields":
return apiResponse{}, &apiError{Status: 422, Message: "invalid record", Fields: map[string]string{"ttl": "out of range"}}
case "extra":
return apiResponse{}, &apiError{Status: 422, Message: "the file has errors", Extra: map[string]any{"errors": []map[string]any{{"line": 3, "message": "bad"}}}}
case "conflict":
return apiResponse{}, fmt.Errorf("wrapped: %w", &apiError{Status: 409, Message: "zone already exists"})
case "lock":
return apiResponse{}, fmt.Errorf("write: %w", errLockTimeout)
case "db":
return apiResponse{}, fmt.Errorf("query: %w", errDatabase)
case "badconn":
return apiResponse{}, driver.ErrBadConn
case "invalidconn":
return apiResponse{}, mysql.ErrInvalidConn
case "connerr":
return apiResponse{}, &net.OpError{Op: "dial", Err: errors.New("refused")}
case "sql":
return apiResponse{}, errors.New("Error 1064: You have an error in your SQL syntax near 'SELECT password_hash'")
case "encode":
return apiResponse{Status: 200, Body: map[string]any{"x": func() {}}}, nil
case "raw":
return apiResponse{Status: 200, Raw: []byte("$ORIGIN example.org.\n"), ContentType: "text/plain; charset=utf-8",
Header: http.Header{"Content-Disposition": {`attachment; filename="example.org.zone"`}, "Etag": {`"abc"`}}}, nil
case "created":
return apiResponse{Status: 201, Body: map[string]int{"id": 1}, Header: http.Header{"ETag": {`"e1"`}}}, nil
case "nocontent":
return apiResponse{Status: 204, Body: map[string]int{"ignored": 1}}, nil
case "default":
return apiResponse{Body: []int{}}, nil
}
return okJSON(map[string]string{}), nil
},
})
h := newWebHarness(t)
h.withHandlers(handlers)
admin := h.user("admin", roleAdmin)
token := h.login(admin)
cases := []struct {
name string
status int
body string
}{
{"fields", 422, `{"error":"invalid record","fields":{"ttl":"out of range"}}`},
{"extra", 422, `{"error":"the file has errors","errors":[{"line":3,"message":"bad"}]}`},
{"conflict", 409, `{"error":"zone already exists"}`},
{"lock", 503, `{"error":"zone busy"}`},
{"db", 503, `{"error":"database unavailable"}`},
{"badconn", 503, `{"error":"database unavailable"}`},
{"invalidconn", 503, `{"error":"database unavailable"}`},
{"connerr", 503, `{"error":"database unavailable"}`},
{"sql", 500, `{"error":"internal error"}`},
{"encode", 500, `{"error":"internal error"}`},
{"created", 201, `{"id":1}`},
{"nocontent", 204, ``},
{"default", 200, `[]`},
}
for _, c := range cases {
res := h.api("GET", "/zones?case="+c.name, token, "")
if res.status != c.status || res.body != c.body {
t.Errorf("%s: %d %s", c.name, res.status, res.body)
continue
}
e := expectOneAudit(t, res, opZoneList, c.status)
if e.Before != nil || e.After != nil {
t.Errorf("%s: before/after on a read", c.name)
}
if c.status != 204 && res.header.Get("Content-Type") != "application/json" {
t.Errorf("%s: content type %q", c.name, res.header.Get("Content-Type"))
}
}
res := h.api("GET", "/zones?case=created", token, "")
if res.header.Get("ETag") != `"e1"` {
t.Fatal(res.header)
}
res = h.api("GET", "/zones?case=raw", token, "")
if res.status != 200 || res.body != "$ORIGIN example.org.\n" || res.header.Get("Content-Type") != "text/plain; charset=utf-8" ||
res.header.Get("Content-Disposition") != `attachment; filename="example.org.zone"` || res.header.Get("ETag") != `"abc"` {
t.Fatalf("%d %v %q", res.status, res.header, res.body)
}
logs := h.logs.String()
if !strings.Contains(logs, "password_hash'") || !strings.Contains(logs, "level=ERROR msg=\"request failed\"") {
t.Fatal("500 not logged at ERROR with its cause")
}
if !strings.Contains(logs, "level=WARN msg=\"zone lock timeout\"") || !strings.Contains(logs, "level=WARN msg=\"request refused\" operation=zone_list status=409") {
t.Fatal("warnings missing")
}
if lastCtx.Zone != "" || lastCtx.Server != h.s || lastCtx.Principal.User.ID != admin.ID || !lastCtx.Now.Equal(webNow) || lastCtx.Entry.Actor != "admin" {
t.Fatalf("%+v", lastCtx)
}
}
func TestZoneRouteNormalizationAndDelegation(t *testing.T) {
var seen []string
handlers := frameworkTestHandlers(map[string]apiHandler{
opZoneRead: func(ctx context.Context, c *apiContext) (apiResponse, error) {
seen = append(seen, c.Zone+"|"+c.Entry.Zone.String+"|"+c.Vars["zone"])
if c.Zone == otherZone {
return apiResponse{}, errZoneNotFound()
}
return okJSON(map[string]string{"zone": c.Zone}), nil
},
})
h := newWebHarness(t)
h.withHandlers(handlers)
admin := h.user("admin", roleAdmin)
alice := h.user("alice", roleUser)
h.store.delegate(testZone, alice)
at, ut := h.login(admin), h.login(alice)
res := h.api("GET", "/zones/Example.ORG", ut, "")
if res.status != 200 || res.body != `{"zone":"example.org."}` {
t.Fatalf("%d %s", res.status, res.body)
}
e := expectOneAudit(t, res, opZoneRead, 200)
if e.Zone.String != testZone || e.UserID.Int64 != alice.ID || e.Actor != "alice" || e.Origin != "192.0.2.10" || !e.Time.Equal(webNow) {
t.Fatalf("%+v", e)
}
if seen[0] != "example.org.|example.org.|Example.ORG" {
t.Fatal(seen)
}
notDelegated := h.api("GET", "/zones/secret.org", ut, "")
missing := h.api("GET", "/zones/other.org.", at, "")
invalid := h.api("GET", "/zones/bad_zone!", ut, "")
invalidAdmin := h.api("GET", "/zones/a..b", at, "")
for name, r := range map[string]webResult{"not delegated": notDelegated, "missing": missing, "invalid": invalid, "invalid admin": invalidAdmin} {
if r.status != 404 || r.body != `{"error":"zone not found"}` || r.header.Get("Content-Type") != "application/json" {
t.Errorf("%s: %d %s", name, r.status, r.body)
}
expectOneAudit(t, r, opZoneRead, 404)
}
if notDelegated.audit[0].entry.Zone.String != "secret.org." || invalid.audit[0].entry.Zone.Valid {
t.Fatal("audit zone")
}
if len(seen) != 2 {
t.Fatal("handler ran for a refused zone", seen)
}
if !strings.Contains(h.logs.String(), `level=WARN msg="zone not delegated" operation=zone_read zone=secret.org. user=alice`) {
t.Fatal(h.logs.String())
}
h.store.failOn["HasDelegation"] = errDatabase
if r := h.api("GET", "/zones/example.org", ut, ""); r.status != 503 {
t.Fatal(r.status)
}
if h.store.called("HasDelegation") != 3 {
t.Fatal("admins must not need a delegation lookup", h.store.called("HasDelegation"))
}
}
func TestAdminRouteRefusedBeforeZone(t *testing.T) {
h := newWebHarness(t)
h.withHandlers(frameworkTestHandlers(nil))
alice := h.user("alice", roleUser)
h.store.delegate(testZone, alice)
token := h.login(alice)
bob := h.user("bob", roleUser)
for _, r := range []struct {
method, path, op, zone string
target int64
}{
{"GET", "/zones/Example.ORG/users", opDelegationList, testZone, 0},
{"DELETE", "/zones/bad!/users/x", opDelegationRevoke, "", 0},
{"PUT", "/zones/example.org./users/bob", opDelegationGrant, testZone, bob.ID},
{"PUT", "/zones/missing.example/users/nobody", opDelegationGrant, "missing.example.", 0},
{"POST", "/zones", opZoneCreate, "", 0},
{"GET", "/users", opUserList, "", 0},
{"GET", "/users/bob", opUserRead, "", bob.ID},
{"GET", "/users/nobody", opUserRead, "", 0},
{"GET", "/users/Bad!", opUserRead, "", 0},
} {
res := h.api(r.method, r.path, token, "")
if res.status != 403 || res.body != `{"error":"admin role required"}` {
t.Fatalf("%s: %d %s", r.path, res.status, res.body)
}
e := expectOneAudit(t, res, r.op, 403)
if e.Zone.Valid != (r.zone != "") || e.Zone.String != r.zone || e.TargetUserID.Valid != (r.target != 0) || e.TargetUserID.Int64 != r.target {
t.Fatalf("%s: audit zone %+v target %+v", r.path, e.Zone, e.TargetUserID)
}
}
res := h.api("POST", "/zones", token, `{"name":"Unlisted.EXAMPLE","ns":"ns.example.com."}`)
expectError(t, res, 403, `{"error":"admin role required"}`)
if e := expectOneAudit(t, res, opZoneCreate, 403); !e.Zone.Valid || e.Zone.String != "unlisted.example." {
t.Fatalf("refused create zone: %+v", e.Zone)
}
missing := h.api("GET", "/users/nobody", token, "")
existing := h.api("GET", "/users/bob", token, "")
if missing.status != existing.status || missing.body != existing.body {
t.Fatal("refusal reveals whether the user exists")
}
h.store.failOn["UserByUsername"] = errDatabase
if res := h.api("GET", "/users/bob", token, ""); res.status != 403 || !expectOneAudit(t, res, opUserRead, 403).UserID.Valid {
t.Fatal("target lookup failure changed the refusal")
}
}
func TestBodyPrecheck(t *testing.T) {
h := newWebHarness(t)
h.withHandlers(frameworkTestHandlers(nil))
token := h.login(h.user("admin", roleAdmin))
res := h.do(webRequest{method: "PUT", path: "/api/v1/zones/example.org./users/bob", token: token, body: "x", ctype: "text/plain"})
if res.status != 415 || res.body != `{"error":"content type must be application/json"}` {
t.Fatalf("%d %s", res.status, res.body)
}
expectOneAudit(t, res, opDelegationGrant, 415)
res = h.do(webRequest{method: "PUT", path: "/api/v1/zones/example.org./users/bob", token: token})
if res.status != 200 {
t.Fatalf("body-less request refused: %d", res.status)
}
res = h.do(webRequest{method: "POST", path: "/api/v1/zones", token: token, body: `{"a":"` + strings.Repeat("x", 70000) + `"}`})
if res.status != 413 || res.body != `{"error":"request body too large"}` {
t.Fatalf("%d %s", res.status, res.body)
}
res = h.do(webRequest{method: "POST", path: "/api/v1/zones/example.org./import/preview", token: token, body: `{"a":"` + strings.Repeat("x", 70000) + `"}`})
if res.status != 200 {
t.Fatalf("import limit not applied: %d", res.status)
}
res = h.do(webRequest{method: "POST", path: "/api/v1/zones/example.org./import/apply", token: token, body: `{"a":"` + strings.Repeat("x", 2<<20) + `"}`})
if res.status != 413 {
t.Fatalf("%d", res.status)
}
}
func TestReadAuditFailureHidesData(t *testing.T) {
h := newWebHarness(t)
h.user("admin", roleAdmin)
token := h.login(h.store.user(1))
h.store.failOn["InsertAudit"] = errors.New("audit table full")
res := h.api("GET", "/users", token, "")
if res.status != 500 || res.body != `{"error":"internal error"}` || strings.Contains(res.body, "admin") {
t.Fatalf("%d %s", res.status, res.body)
}
if !strings.Contains(h.logs.String(), `level=ERROR msg="audit insert failed" operation=user_list status=200`) {
t.Fatal(h.logs.String())
}
res = h.api("GET", "/users/nobody", token, "")
if res.status != 500 || res.body != `{"error":"internal error"}` {
t.Fatalf("refusal with failing audit: %d %s", res.status, res.body)
}
}
func TestChangeAuditFailureRollsBack(t *testing.T) {
h := newWebHarness(t)
h.user("admin", roleAdmin)
token := h.login(h.store.user(1))
h.store.failOn["InsertAudit"] = errors.New("audit table full")
res := h.api("POST", "/users", token, `{"username":"newbie","role":"user","password":"long-enough-pw"}`)
if res.status != 500 || res.body != `{"error":"internal error"}` {
t.Fatalf("%d %s", res.status, res.body)
}
if _, err := h.store.UserByUsername(context.Background(), "newbie"); !errors.Is(err, errRowNotFound) {
t.Fatal("change survived a failed audit insert")
}
if h.store.rollbacks != 1 || h.store.commits != 0 {
t.Fatal(h.store.rollbacks, h.store.commits)
}
delete(h.store.failOn, "InsertAudit")
h.store.failOn["Commit"] = errors.New("commit failed")
res = h.api("POST", "/users", token, `{"username":"newbie","role":"user","password":"long-enough-pw"}`)
if res.status != 500 || len(res.audit) != 1 || res.audit[0].entry.Status.Int64 != 500 || res.audit[0].inTx || res.audit[0].entry.After != nil {
t.Fatalf("%d %+v", res.status, res.audit)
}
}
func TestNotImplementedRoute(t *testing.T) {
h := newWebHarness(t)
handlers := frameworkTestHandlers(nil)
delete(handlers, opAuditRead)
h.withHandlers(handlers)
if err := h.s.checkAPIHandlers(); err == nil || err.Error() != "API operations without a handler: audit_read" {
t.Fatal(err)
}
if !strings.Contains(h.logs.String(), `msg="API route has no handler" operation=audit_read`) {
t.Fatal("missing handler not logged")
}
token := h.login(h.user("admin", roleAdmin))
res := h.api("GET", "/audit", token, "")
if res.status != 501 || res.body != `{"error":"not implemented"}` {
t.Fatalf("%d %s", res.status, res.body)
}
expectOneAudit(t, res, opAuditRead, 501)
}
func TestEveryRouteHasHandler(t *testing.T) {
h := newWebHarness(t)
handlers := h.s.apiHandlers()
if missing := missingAPIHandlers(handlers); len(missing) != 0 {
t.Fatalf("routes without handler: %v", missing)
}
if err := h.s.checkAPIHandlers(); err != nil {
t.Fatal(err)
}
framework := frameworkAPIHandlers(h.s)
for _, r := range apiRoutes {
_, own := framework[r.Operation]
if own == slices.Contains(zoneOperations, r.Operation) {
t.Errorf("%s: framework handler %v", r.Operation, own)
}
}
}
func TestMergeAPIHandlers(t *testing.T) {
a := func(ctx context.Context, c *apiContext) (apiResponse, error) { return okJSON("a"), nil }
b := func(ctx context.Context, c *apiContext) (apiResponse, error) { return okJSON("b"), nil }
merged, dups := mergeAPIHandlers(map[string]apiHandler{"x": a, "y": a}, map[string]apiHandler{"y": b, "z": b})
if len(merged) != 3 || !slices.Equal(dups, []string{"y"}) {
t.Fatal(merged, dups)
}
resp, _ := merged["y"](context.Background(), nil)
if resp.Body != "a" {
t.Fatal("first handler must win")
}
}
func TestRequestLogging(t *testing.T) {
h := newWebHarness(t)
alice := h.user("alice", roleUser)
token := h.login(alice)
h.api("GET", "/account", token, "")
h.do(webRequest{method: "GET", path: "/health"})
h.do(webRequest{method: "GET", path: h.s.pages.staticPrefix() + "css/app.css"})
logs := h.logs.String()
if !strings.Contains(logs, `level=INFO msg=request method=GET path=/api/v1/account status=200`) || !strings.Contains(logs, "user=alice role=user origin=192.0.2.10") {
t.Fatal(logs)
}
if !strings.Contains(logs, `level=DEBUG msg=request method=GET path=/health status=503`) || !strings.Contains(logs, `level=DEBUG msg=request method=GET path=/static/`) {
t.Fatal(logs)
}
if strings.Contains(logs, token) {
t.Fatal("token logged")
}
}
func TestIsAPIPath(t *testing.T) {
if !isAPIPath("/api") || !isAPIPath("/api/v1/x") || isAPIPath("/apix") || isAPIPath("/") {
t.Fatal("isAPIPath")
}
if !isDatabaseUnavailable(sql.ErrConnDone) || isDatabaseUnavailable(errors.New("x")) || isDatabaseUnavailable(nil) {
t.Fatal("isDatabaseUnavailable")
}
}
func TestAPIBodyFraming(t *testing.T) {
h := newWebHarness(t)
alice := h.user("alice", roleUser)
token := h.login(alice)
for _, chunked := range []bool{false, true} {
for _, c := range []struct {
method, path, body, ctype, op, want string
status int
}{
{"GET", "/account", `{"x":1}`, "text/plain", opAccountRead, `{"error":"content type must be application/json"}`, 415},
{"GET", "/account", strings.Repeat(" ", 70000), "application/json", opAccountRead, `{"error":"request body too large"}`, 413},
{"GET", "/account", "{\"x\":\"\xff\"}", "application/json", opAccountRead, `{"error":"request body must be valid UTF-8"}`, 400},
{"PUT", "/account/password", strings.Repeat(" ", 70000), "application/json", opPasswordChange, `{"error":"request body too large"}`, 413},
{"PUT", "/account/password", " \n\t ", "application/json", opPasswordChange, `{"error":"request body is required"}`, 400},
{"PUT", "/account/password", "{\"current\":\"secret-password\",\"password\":\"\xffvalid-looking-pw\"}", "application/json", opPasswordChange, `{"error":"request body must be valid UTF-8"}`, 400},
} {
res := h.do(webRequest{method: c.method, path: apiPrefix + c.path, token: token, body: c.body, ctype: c.ctype, chunked: chunked})
if res.status != c.status || res.body != c.want {
t.Errorf("chunked %v %s %s: %d %s", chunked, c.method, c.path, res.status, res.body)
continue
}
expectOneAudit(t, res, c.op, c.status)
}
}
if h.store.user(alice.ID).PasswordHash != fakeHash(testPassword) {
t.Fatal("password changed")
}
srv := httptest.NewServer(h.handler)
defer srv.Close()
for _, c := range []struct {
body io.Reader
status int
}{
{io.MultiReader(strings.NewReader(`{"x":1}`)), 415},
{io.MultiReader(strings.NewReader(strings.Repeat(" ", 70000))), 413},
{strings.NewReader(`{"x":1}`), 415},
} {
req, err := http.NewRequest("GET", srv.URL+apiPrefix+"/account", c.body)
if err != nil {
t.Fatal(err)
}
req.Header.Set("Content-Type", "text/plain")
if c.status == 413 {
req.Header.Set("Content-Type", "application/json")
}
req.AddCookie(&http.Cookie{Name: sessionCookieName, Value: token})
resp, err := srv.Client().Do(req)
if err != nil {
t.Fatal(err)
}
resp.Body.Close()
if resp.StatusCode != c.status {
t.Errorf("server: %d, want %d", resp.StatusCode, c.status)
}
}
}
func TestUnknownAPIPathRefusedCrossOrigin(t *testing.T) {
h := newWebHarness(t)
token := h.login(h.user("admin", roleAdmin))
res := h.do(webRequest{method: "POST", path: "/api/v1/nothing", token: token, body: `{}`, header: map[string]string{"Sec-Fetch-Site": "cross-site"}})
if res.status != 403 || res.body != `{"error":"cross-origin request refused"}` || len(res.audit) != 0 {
t.Fatalf("%d %s %d", res.status, res.body, len(res.audit))
}
}
func TestPagePathCleaning(t *testing.T) {
h := newWebHarness(t)
res := h.do(webRequest{method: "GET", path: "/zones/../audit?x=1"})
if res.status != 301 || res.header.Get("Location") != "/audit?x=1" {
t.Fatalf("%d %v", res.status, res.header)
}
for in, want := range map[string]string{"": "/", "a": "/a", "/a/b/": "/a/b/", "/a/../": "/", "//a": "/a"} {
if got := cleanURLPath(in); got != want {
t.Errorf("%q: %q", in, got)
}
}
}
func TestDelegationGrantCommitsWithZoneLock(t *testing.T) {
token, tokenHash, err := newSessionToken(strings.NewReader(strings.Repeat("k", 32)))
if err != nil {
t.Fatal(err)
}
userValues := func(id int64, username, role string) []driver.Value {
return []driver.Value{id, username, role, fakeHash(testPassword), webNow, webNow, nil, nil}
}
session := append(userValues(1, "admin", roleAdmin), tokenHash, int64(1), webNow, webNow, webNow.Add(time.Hour), "192.0.2.1", "test")
db, st := newFakeDB(t, fdbRules(
fdbRule{"webui_locks", fdbResponse{rowsAffected: 1}},
fdbRule{"x.`token_hash` = ?", fdbResponse{rows: [][]driver.Value{session}}},
fdbRule{"ORDER BY u.`id` FOR UPDATE", fdbResponse{rows: [][]driver.Value{userValues(1, "admin", roleAdmin)}}},
fdbRule{"SELECT 1 FROM `coredns_records`", fdbResponse{rows: fdbRow(int64(1))}},
fdbRule{"u.`username` = CAST(? AS BINARY) FOR UPDATE", fdbResponse{rows: [][]driver.Value{userValues(2, "bob", roleUser)}}},
fdbRule{"INSERT INTO `coredns_webui_audit`", fdbResponse{lastInsertID: 1, rowsAffected: 1}},
))
var logs bytes.Buffer
s := newWebServer(Config{CookieSecure: true, SessionIdleTimeout: time.Hour, SessionMaxAge: 12 * time.Hour}, newLogger(&logs, slog.LevelDebug), db, fdbTables(t), func() time.Time { return webNow })
r := httptest.NewRequest("PUT", "/api/v1/zones/example.org./users/bob", nil)
r.RemoteAddr = "192.0.2.1:1234"
r.AddCookie(&http.Cookie{Name: sessionCookieName, Value: token})
w := httptest.NewRecorder()
s.Handler().ServeHTTP(w, r)
if w.Code != 204 {
t.Fatalf("%d %s", w.Code, w.Body.String())
}
var audits, grants int
for _, c := range st.Calls() {
switch {
case strings.HasPrefix(c.query, "INSERT INTO `coredns_webui_audit`"):
audits++
if c.args[4] != opDelegationGrant || c.args[5] != int64(204) || c.args[6] != nil {
t.Fatalf("audit row %v", c.args)
}
case strings.HasPrefix(c.query, "INSERT INTO `coredns_webui_zone_delegations`"):
grants++
}
}
if audits != 1 || grants != 1 || st.commits != 1 || st.rollbacks != 0 {
t.Fatalf("audits %d grants %d commits %d rollbacks %d", audits, grants, st.commits, st.rollbacks)
}
if !strings.Contains(logs.String(), "zone lock acquired") || !strings.Contains(logs.String(), `msg="change committed" operation=delegation_grant`) {
t.Fatal(logs.String())
}
}
func TestHandlerTraceHasNoSecrets(t *testing.T) {
h := newWebHarness(t)
alice := h.user("alice", roleUser)
res := h.postLogin(loginForm("alice", testPassword, ""), "")
token := responseCookie(t, res).Value
h.api("GET", "/account", token, "")
h.api("PUT", "/account/password", token, `{"current":"secret-password","password":"brand-new-password"}`)
h.do(webRequest{method: "GET", path: "/audit", token: token})
out := h.logs.String()
for _, want := range []string{
`level=TRACE msg="function entry" func=page.login.post`, `level=TRACE msg="function exit" func=page.login.post`,
`level=TRACE msg="function entry" func=api.account_read`, `level=TRACE msg="function exit" func=api.password_change`,
`level=TRACE msg="function entry" func=page.audit`,
} {
if !strings.Contains(out, want) {
t.Errorf("trace lacks %q", want)
}
}
for _, secret := range []string{testPassword, "brand-new-password", token, fakeHash(testPassword), h.store.user(alice.ID).PasswordHash} {
if strings.Contains(out, secret) {
t.Fatalf("logs contain a secret %q", secret)
}
}
}