Files
coredns-web-ui/handlers_session_test.go
T
bryanpedini 53444bec7a test(ui): avoid a literal em dash in the em dash check
- 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
2026-11-19 15:46:12 +01:00

447 lines
18 KiB
Go

// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright (C) 2026 Bryan Joshua Pedini
package main
import (
"bytes"
"database/sql"
"errors"
"net/http"
"net/url"
"strings"
"testing"
"time"
)
func loginForm(username, password, next string) string {
v := url.Values{"username": {username}, "password": {password}}
if next != "" {
v.Set("next", next)
}
return v.Encode()
}
func (h *webHarness) postLogin(form string, token string) webResult {
h.t.Helper()
return h.do(webRequest{method: "POST", path: "/login", body: form, ctype: "application/x-www-form-urlencoded", token: token, header: map[string]string{"User-Agent": "Browser/1.0"}})
}
func responseCookie(t *testing.T, res webResult) *http.Cookie {
t.Helper()
cookies := (&http.Response{Header: res.header}).Cookies()
if len(cookies) != 1 {
t.Fatalf("cookies %v", cookies)
}
return cookies[0]
}
func TestLoginSuccess(t *testing.T) {
h := newWebHarness(t)
alice := h.user("alice", roleUser)
old := h.login(alice)
h.clock.advance(time.Minute)
res := h.postLogin(loginForm("alice", testPassword, "/zones/example.org.?q=1"), old)
if res.status != 303 || res.header.Get("Location") != "/zones/example.org.?q=1" {
t.Fatalf("%d %v", res.status, res.header)
}
c := responseCookie(t, res)
if c.Name != sessionCookieName || !c.HttpOnly || !c.Secure || c.SameSite != http.SameSiteStrictMode || c.Path != "/" || !validSessionToken(c.Value) || c.Value == old {
t.Fatalf("%+v", c)
}
sw, err := h.store.SessionByTokenHash(t.Context(), sessionTokenHash(c.Value))
if err != nil || sw.Session.UserID != alice.ID || sw.Session.Origin != "192.0.2.10" || sw.Session.UserAgent != "Browser/1.0" ||
!sw.Session.CreatedAt.Equal(h.clock.Now()) || !sw.Session.ExpiresAt.Equal(h.clock.Now().Add(12*time.Hour)) {
t.Fatalf("%+v %v", sw, err)
}
if _, err := h.store.SessionByTokenHash(t.Context(), sessionTokenHash(old)); !errors.Is(err, errRowNotFound) {
t.Fatal("previous session of the browser kept")
}
if u := h.stored("alice"); !u.LastLoginAt.Valid || !u.LastLoginAt.Time.Equal(h.clock.Now()) {
t.Fatalf("%+v", u)
}
e := expectOneAudit(t, res, opLogin, 303)
if !res.audit[0].inTx || e.UserID.Int64 != alice.ID || e.Actor != "alice" || e.Origin != "192.0.2.10" || e.Zone.Valid || e.Before != nil || e.After != nil {
t.Fatalf("%+v", res.audit[0])
}
if !strings.Contains(h.logs.String(), `msg="change committed" operation=login actor=alice`) {
t.Fatal("login not logged")
}
second := h.postLogin(loginForm("alice", testPassword, ""), "")
if second.header.Get("Location") != "/" || responseCookie(t, second).Value == c.Value {
t.Fatal("token reused or default next wrong")
}
if h.api("GET", "/account", c.Value, "").status != 200 {
t.Fatal("new session unusable")
}
}
func TestLoginFailures(t *testing.T) {
h := newWebHarness(t)
alice := h.user("alice", roleUser)
gone := h.user("gone", roleUser)
gone.DeletedAt = sql.NullTime{Time: webNow, Valid: true}
h.store.setUser(gone)
var verified []string
h.s.verifyPassword = func(p, encoded string) bool {
verified = append(verified, encoded)
return fakeVerify(p, encoded)
}
cases := []struct {
username, password string
userID int64
actor, hash string
}{
{"alice", "wrong-password", alice.ID, "alice", fakeHash(testPassword)},
{"nobody", testPassword, 0, "nobody", dummyPasswordHash},
{"gone", testPassword, gone.ID, "gone", dummyPasswordHash},
{"Bad\x00User\n", testPassword, 0, "Bad User ", dummyPasswordHash},
{"", "", 0, "", dummyPasswordHash},
}
for _, c := range cases {
verified = nil
res := h.postLogin(loginForm(c.username, c.password, "/audit"), "")
if res.status != 401 || !strings.Contains(res.body, "invalid username or password") || len(res.header.Values("Set-Cookie")) != 0 {
t.Fatalf("%q: %d", c.username, res.status)
}
if !strings.Contains(res.body, `name="next" value="/audit"`) {
t.Fatal("next lost on the login page")
}
e := expectOneAudit(t, res, opLogin, 401)
if e.Error.String != "invalid username or password" || e.Actor != c.actor || e.UserID.Valid != (c.userID != 0) || e.UserID.Int64 != c.userID {
t.Fatalf("%q: %+v", c.username, e)
}
if len(verified) != 1 || verified[0] != c.hash {
t.Fatalf("%q: verified against %v", c.username, verified)
}
}
if strings.Count(h.logs.String(), `level=WARN msg="login failed"`) != len(cases) {
t.Fatal("failed logins not logged at WARN")
}
if strings.Contains(h.logs.String(), "wrong-password") {
t.Fatal("password logged")
}
}
func TestLoginRateLimit(t *testing.T) {
h := newWebHarness(t)
h.user("alice", roleUser)
h.user("bob", roleUser)
for i := range 4 {
res := h.do(webRequest{method: "POST", path: "/login", body: loginForm("alice", "bad", ""), ctype: "application/x-www-form-urlencoded", remote: "198.51.100." + string(rune('1'+i)) + ":1"})
if res.status != 401 {
t.Fatal(res.status)
}
}
if res := h.postLogin(loginForm("alice", testPassword, ""), ""); res.status != 303 {
t.Fatal("login refused before the limit", res.status)
}
for range 5 {
h.do(webRequest{method: "POST", path: "/login", body: loginForm("alice", "bad", ""), ctype: "application/x-www-form-urlencoded", remote: "203.0.113.50:1"})
}
res := h.do(webRequest{method: "POST", path: "/login", body: loginForm("alice", testPassword, ""), ctype: "application/x-www-form-urlencoded", remote: "203.0.113.51:1"})
if res.status != 429 || !strings.Contains(res.body, "too many failed login attempts, try again later") || len(res.header.Values("Set-Cookie")) != 0 {
t.Fatalf("%d", res.status)
}
e := expectOneAudit(t, res, opLogin, 429)
if e.UserID.Int64 != h.users["alice"].ID || e.Error.String != "too many failed login attempts, try again later" {
t.Fatalf("%+v", e)
}
if res := h.do(webRequest{method: "POST", path: "/login", body: loginForm("bob", testPassword, ""), ctype: "application/x-www-form-urlencoded", remote: "203.0.113.50:1"}); res.status != 429 {
t.Fatal("origin not limited", res.status)
}
if !strings.Contains(h.logs.String(), `level=WARN msg="login rate limited"`) {
t.Fatal("rate limit not logged")
}
h.clock.advance(loginBlockDuration)
if res := h.postLogin(loginForm("alice", testPassword, ""), ""); res.status != 303 {
t.Fatal("block not lifted", res.status)
}
h.store.failOn["InsertAudit"] = errors.New("x")
for range 5 {
h.do(webRequest{method: "POST", path: "/login", body: loginForm("bob", "bad", ""), ctype: "application/x-www-form-urlencoded", remote: "203.0.113.60:1"})
}
if res := h.do(webRequest{method: "POST", path: "/login", body: loginForm("bob", "bad", ""), ctype: "application/x-www-form-urlencoded", remote: "203.0.113.61:1"}); res.status != 500 {
t.Fatal("rate limited login without audit row", res.status)
}
}
func TestLoginInternalFailures(t *testing.T) {
h := newWebHarness(t)
h.user("alice", roleUser)
h.store.failOn["UserByUsername"] = errDatabase
res := h.postLogin(loginForm("alice", testPassword, ""), "")
if res.status != 503 || !strings.Contains(res.body, "login is temporarily unavailable") {
t.Fatal(res.status)
}
if e := expectOneAudit(t, res, opLogin, 503); e.UserID.Valid || e.Error.String != "database unavailable" {
t.Fatalf("%+v", e)
}
delete(h.store.failOn, "UserByUsername")
h.store.failOn["CreateSession"] = errors.New("duplicate token")
res = h.postLogin(loginForm("alice", testPassword, ""), "")
if res.status != 500 || len(res.header.Values("Set-Cookie")) != 0 {
t.Fatal(res.status)
}
if e := expectOneAudit(t, res, opLogin, 500); res.audit[0].inTx || e.Error.String != "internal error" {
t.Fatalf("%+v", res.audit[0])
}
if h.stored("alice").LastLoginAt.Valid {
t.Fatal("failed login touched last_login_at")
}
delete(h.store.failOn, "CreateSession")
h.s.random = bytes.NewReader(nil)
if res := h.postLogin(loginForm("alice", testPassword, ""), ""); res.status != 500 {
t.Fatal("token failure", res.status)
}
h.s.random = strings.NewReader(strings.Repeat("r", 64))
h.store.failOn["InsertAudit"] = errors.New("x")
if res := h.postLogin(loginForm("alice", "wrong", ""), ""); res.status != 500 {
t.Fatal("failed login without audit row", res.status)
}
delete(h.store.failOn, "InsertAudit")
res = h.do(webRequest{method: "POST", path: "/login", body: "username=%zz", ctype: "application/x-www-form-urlencoded"})
if res.status != 400 || !strings.Contains(res.body, "the login form is invalid") || len(res.audit) != 0 {
t.Fatal(res.status)
}
res = h.do(webRequest{method: "POST", path: "/login", body: "username=" + strings.Repeat("a", 70000), ctype: "application/x-www-form-urlencoded"})
if res.status != 400 {
t.Fatal("oversized form", res.status)
}
h.s.store = nil
if res := h.postLogin(loginForm("alice", testPassword, ""), ""); res.status != 503 {
t.Fatal("no store", res.status)
}
}
func TestLoginPage(t *testing.T) {
h := newWebHarness(t)
res := h.do(webRequest{method: "GET", path: "/login?next=/users"})
if res.status != 200 || !strings.Contains(res.body, "No administrator exists yet") || !strings.Contains(res.body, "docker exec -i <container> /app user add <username> admin") || !strings.Contains(res.body, `value="/users"`) {
t.Fatalf("%d %s", res.status, res.body)
}
if len(res.audit) != 0 {
t.Fatal("page audited")
}
h.user("admin", roleAdmin)
res = h.do(webRequest{method: "GET", path: "/login?next=//evil.example/x"})
if strings.Contains(res.body, "No administrator exists yet") || !strings.Contains(res.body, `name="next" value="/"`) {
t.Fatal(res.body)
}
admin := h.users["admin"]
admin.DeletedAt = sql.NullTime{Time: webNow, Valid: true}
h.store.setUser(admin)
h.user("demoted", roleUser)
if res := h.do(webRequest{method: "GET", path: "/login"}); !strings.Contains(res.body, "No administrator exists yet") {
t.Fatal("deleted admin counted as active")
}
h.store.failOn["HasActiveAdmin"] = errDatabase
res = h.do(webRequest{method: "GET", path: "/login"})
if res.status != 200 || strings.Contains(res.body, "No administrator exists yet") || !strings.Contains(h.logs.String(), "active admin lookup failed") {
t.Fatal(res.status)
}
}
func TestValidNextPath(t *testing.T) {
good := []string{"/", "/zones/example.org.", "/audit?zone=a.b.&kind=read", "/users/bob#x"}
bad := []string{"", "zones", "//evil.example", "/\\evil.example", "http://evil.example/", "/a\nb", "/a\x7fb", "\\\\evil", "/%zz"}
for _, n := range good {
if !validNextPath(n) || safeNext(n) != n {
t.Errorf("%q refused", n)
}
}
for _, n := range bad {
if validNextPath(n) || safeNext(n) != "/" {
t.Errorf("%q accepted", n)
}
}
}
func TestLogout(t *testing.T) {
h := newWebHarness(t)
alice := h.user("alice", roleUser)
token := h.login(alice)
other := h.login(alice)
res := h.do(webRequest{method: "POST", path: "/logout", token: token})
if res.status != 303 || res.header.Get("Location") != "/login" {
t.Fatal(res.status)
}
c := responseCookie(t, res)
if c.Value != "" || c.MaxAge != -1 {
t.Fatalf("%+v", c)
}
e := expectOneAudit(t, res, opLogout, 303)
if !res.audit[0].inTx || e.UserID.Int64 != alice.ID || e.Actor != "alice" {
t.Fatalf("%+v", e)
}
if h.api("GET", "/account", token, "").status != 401 || h.api("GET", "/account", other, "").status != 200 {
t.Fatal("logout must end only its own session")
}
res = h.do(webRequest{method: "POST", path: "/logout", token: token})
if res.status != 303 || res.header.Get("Location") != "/login" || len(res.audit) != 0 {
t.Fatal("logout without session", res.status)
}
h.store.failOn["DeleteSession"] = errors.New("x")
res = h.do(webRequest{method: "POST", path: "/logout", token: other})
if res.status != 500 {
t.Fatal(res.status)
}
if e := expectOneAudit(t, res, opLogout, 500); res.audit[0].inTx || e.Error.String != "internal error" {
t.Fatalf("%+v", e)
}
h.store.failOn = map[string]error{"SessionByTokenHash": errDatabase}
if res := h.do(webRequest{method: "POST", path: "/logout", token: other}); res.status != 503 {
t.Fatal(res.status)
}
if res := h.do(webRequest{method: "GET", path: "/logout", token: other}); res.status != 405 || res.header.Get("Allow") != "POST" {
t.Fatal(res.status)
}
}
type pageCase struct {
path string
access string
page string
}
var pageCases = []pageCase{
{"/", accessSession, "zones"},
{"/zones/example.org.", accessZone, "zone"},
{"/zones/Example.ORG/import", accessZone, "import"},
{"/audit", accessSession, "audit"},
{"/account", accessSession, "account"},
{"/users", accessAdmin, "users"},
{"/users/bob", accessAdmin, "user"},
}
func TestPageAuthorizationMatrix(t *testing.T) {
for _, c := range pageCases {
for i := range 7 {
h, personas := matrixHarness(t)
p := personas[i]
res := h.do(webRequest{method: "GET", path: c.path, token: p.token})
want, page := 200, c.page
switch {
case p.name == "deleted user" || p.name == "no session":
want = 303
case p.name == "admin" || p.name == "promoted user":
case c.access == accessAdmin:
want, page = 403, "forbidden"
case c.access == accessZone && p.name != "delegated user":
want, page = 404, "not_found"
}
if res.status != want || len(res.audit) != 0 {
t.Errorf("%s as %s: %d (audit %d), want %d", c.path, p.name, res.status, len(res.audit), want)
continue
}
if want == 303 {
if res.header.Get("Location") != "/login?next="+url.QueryEscape(c.path) {
t.Errorf("%s: %s", c.path, res.header.Get("Location"))
}
continue
}
if !strings.Contains(res.body, `data-page="`+page+`"`) || res.header.Get("Content-Type") != "text/html; charset=utf-8" {
t.Errorf("%s as %s: page %s missing", c.path, p.name, page)
}
if !strings.Contains(res.body, `data-username="`) || strings.Contains(res.body, `data-username=""`) {
t.Errorf("%s as %s: user missing in layout", c.path, p.name)
}
isAdmin := p.name == "admin" || p.name == "promoted user"
if strings.Contains(res.body, `href="/users"`) != isAdmin {
t.Errorf("%s as %s: users link visibility", c.path, p.name)
}
if page == "zone" && !strings.Contains(res.body, `data-zone="example.org."`) {
t.Errorf("zone missing: %s", res.body)
}
if page == "import" && !strings.Contains(res.body, `data-zone="example.org."`) {
t.Errorf("zone missing on import page")
}
if page == "user" && !strings.Contains(res.body, `data-target-user="bob"`) {
t.Errorf("target user missing")
}
}
}
}
func TestPagesCarryNoData(t *testing.T) {
h, personas := matrixHarness(t)
h.store.calls = nil
for _, c := range pageCases {
res := h.do(webRequest{method: "GET", path: c.path, token: personas[1].token})
if strings.Contains(res.body, "carol") || strings.Contains(res.body, "dave") {
t.Fatalf("%s carries user data", c.path)
}
}
for _, call := range h.store.calls {
if call != "SessionByTokenHash" && call != "HasDelegation" && call != "ZoneExists" {
t.Fatalf("page read %s", call)
}
}
}
func TestPageEdgeCases(t *testing.T) {
h, personas := matrixHarness(t)
admin := personas[0].token
res := h.do(webRequest{method: "GET", path: "/users/BAD", token: admin})
if res.status != 404 || !strings.Contains(res.body, `data-page="not_found"`) || !strings.Contains(res.body, `data-username="admin"`) {
t.Fatal(res.status)
}
if res := h.do(webRequest{method: "GET", path: "/zones/bad!zone", token: admin}); res.status != 404 {
t.Fatal(res.status)
}
res = h.do(webRequest{method: "GET", path: "/no/such/page", token: admin})
if res.status != 404 || !strings.Contains(res.body, `data-username="admin"`) {
t.Fatal(res.status)
}
res = h.do(webRequest{method: "GET", path: "/no/such/page"})
if res.status != 404 || !strings.Contains(res.body, `data-username=""`) {
t.Fatal(res.status)
}
res = h.do(webRequest{method: "GET", path: "/users", token: personas[1].token})
if res.status != 403 || !strings.Contains(res.body, `data-username="alice"`) || !strings.Contains(res.body, "Forbidden") || !strings.Contains(h.logs.String(), `level=WARN msg="admin page refused"`) {
t.Fatal(res.status)
}
if res := h.do(webRequest{method: "DELETE", path: "/", token: admin}); res.status != 405 || res.header.Get("Allow") != "GET" {
t.Fatal(res.status)
}
if res := h.do(webRequest{method: "PUT", path: "/login"}); res.status != 405 || res.header.Get("Allow") != "GET, POST" {
t.Fatal(res.status)
}
res = h.do(webRequest{method: "GET", path: "/audit?zone=x", header: map[string]string{}})
if res.status != 303 || res.header.Get("Location") != "/login?next=%2Faudit%3Fzone%3Dx" {
t.Fatal(res.header.Get("Location"))
}
h.store.failOn["HasDelegation"] = errDatabase
if res := h.do(webRequest{method: "GET", path: "/zones/example.org.", token: personas[1].token}); res.status != 503 {
t.Fatal(res.status)
}
h.store.failOn = map[string]error{"SessionByTokenHash": errors.New("x")}
if res := h.do(webRequest{method: "GET", path: "/", token: admin}); res.status != 500 || res.body != "internal server error\n" {
t.Fatal(res.status)
}
h.store.failOn = map[string]error{}
h.s.pages = nil
if res := h.do(webRequest{method: "GET", path: "/", token: admin}); res.status != 500 {
t.Fatal(res.status)
}
}
func TestStaticRoutes(t *testing.T) {
h := newWebHarness(t)
prefix := h.s.pages.staticPrefix()
if res := h.do(webRequest{method: "GET", path: prefix + "js/common.js"}); res.status != 200 || res.header.Get("Content-Type") != "text/javascript; charset=utf-8" {
t.Fatal(res.status)
}
for _, p := range []string{"/static/0000000000000000/css/app.css", prefix + "nope.css", prefix + "../templates/html/layout.html", "/static/"} {
if res := h.do(webRequest{method: "GET", path: p}); res.status != 404 && res.status != 301 {
t.Errorf("%s: %d", p, res.status)
}
}
if res := h.do(webRequest{method: "POST", path: prefix + "css/app.css"}); res.status != 405 {
t.Fatal(res.status)
}
if res := h.do(webRequest{method: "GET", path: "/version"}); res.status != 200 || len(res.audit) != 0 {
t.Fatal(res.status)
}
}