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
This commit is contained in:
1 parent
5f17aab6ca
commit
53444bec7a
40 files changed
+2332
-254
No files matched your search
+209
-11
@@ -4,12 +4,15 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"database/sql"
|
||||
"database/sql/driver"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"log/slog"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
@@ -51,7 +54,10 @@ func TestDecodeJSON(t *testing.T) {
|
||||
{`{"name":"a"}`, "application/json; charset=utf-8", 0, 0, "", ""},
|
||||
{" \n{} \n", "application/json", 0, 0, "", ""},
|
||||
{"", "application/json", 0, 400, "request body is required", ""},
|
||||
{" ", "", 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", ""},
|
||||
@@ -267,11 +273,20 @@ func TestCrossOriginProtection(t *testing.T) {
|
||||
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"} {
|
||||
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" || len(res.audit) != 0 {
|
||||
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",
|
||||
@@ -287,12 +302,19 @@ func TestAPIRouterNotFoundAndMethods(t *testing.T) {
|
||||
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 || len(res.audit) != 0 {
|
||||
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))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -558,20 +580,44 @@ func TestAdminRouteRefusedBeforeZone(t *testing.T) {
|
||||
alice := h.user("alice", roleUser)
|
||||
h.store.delegate(testZone, alice)
|
||||
token := h.login(alice)
|
||||
for _, r := range []struct{ method, path, op string }{
|
||||
{"GET", "/zones/example.org./users", opDelegationList},
|
||||
{"DELETE", "/zones/bad!/users/x", opDelegationRevoke},
|
||||
{"POST", "/zones", opZoneCreate},
|
||||
{"GET", "/users", opUserList},
|
||||
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)
|
||||
}
|
||||
if e := expectOneAudit(t, res, r.op, 403); e.Zone.Valid {
|
||||
t.Fatal("zone recorded for a refused admin route")
|
||||
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) {
|
||||
@@ -719,3 +765,155 @@ func TestIsAPIPath(t *testing.T) {
|
||||
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 TestZoneTxLockReleaseFailureKeepsTheCommittedChange(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{"SELECT GET_LOCK", fdbResponse{rows: fdbRow(int64(1))}},
|
||||
fdbRule{"SELECT RELEASE_LOCK", fdbResponse{err: errors.New("connection lost")}},
|
||||
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` = ? 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(), "named lock release failed, discarding the connection") || !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)
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user