// SPDX-License-Identifier: GPL-2.0-or-later // Copyright (C) 2026 Bryan Joshua Pedini package main import ( "context" "database/sql" "database/sql/driver" "encoding/json" "errors" "fmt" "net/http" "net/http/httptest" "net/url" "slices" "strconv" "strings" "testing" "time" ) func TestZoneAPIRecordViewErrorContent(t *testing.T) { for _, tc := range []struct { name string row recordRow wantRaw bool wantData bool codes []string }{ {"valid", modelRawRow(1, "www", "A", 3600, `{"ip":"192.0.2.1"}`), false, true, nil}, {"invalid address", modelRawRow(1, "www", "A", 3600, `{"ip":"invalid"}`), true, true, []string{"field_invalid"}}, {"malformed", modelRawRow(2, "www", "A", 3600, `{`), true, false, []string{"content_json"}}, {"null", recordRow{ID: 3, Zone: "example.org.", Name: "www", RecordType: "A", TTL: sql.NullInt64{Int64: 3600, Valid: true}}, false, false, []string{"content_null"}}, {"unknown", modelRawRow(4, "www", "UNKNOWN", 3600, `{}`), true, false, []string{"type_unknown"}}, {"warning only", modelRawRow(5, "www", "A", 0, `{"ip":"192.0.2.1"}`), false, true, []string{"ttl_zero"}}, } { t.Run(tc.name, func(t *testing.T) { view := zoneAPIRecordView(tc.row, checkRecord(tc.row, modelNow)) if (view.Raw != nil) != tc.wantRaw || (view.Data != nil) != tc.wantData { t.Fatalf("unexpected view: %+v", view) } if view.Raw != nil && *view.Raw != tc.row.Content.String { t.Fatalf("raw = %q, want the stored content", *view.Raw) } var codes []string for _, p := range view.Problems { codes = append(codes, p.Code) } if !slices.Equal(codes, tc.codes) { t.Fatalf("problems = %v, want %v", codes, tc.codes) } }) } rows := append(zoneAPITestRows(t), modelRawRow(9, "bad", "A", 60, `{"ip":"invalid"}`)) f := zoneAPITestDBFor(t, rows) server, _ := f.server() resp := zoneAPITestStatus(t, t.Context(), zoneAPITestRequest(server, f.actor, "record_list", zoneAPITestName, "", "", ""), 200) if body := zoneAPITestJSON(t, resp.Body); !strings.Contains(body, `"data":{"ip":"invalid"},"raw":"{\"ip\":\"invalid\"}"`) { t.Fatalf("record list = %s", body) } } func (h *webHarness) stored(username string) userRow { h.t.Helper() u, err := h.store.UserByUsername(context.Background(), username) if err != nil { h.t.Fatalf("%s: %v", username, err) } return u } func expectError(t *testing.T, res webResult, status int, body string) { t.Helper() if res.status != status || res.body != body { t.Fatalf("got %d %s, want %d %s", res.status, res.body, status, body) } } func expectChange(t *testing.T, res webResult, operation string, status int, target int64, before, after string) auditEntry { t.Helper() e := expectOneAudit(t, res, operation, status) if !res.audit[0].inTx { t.Fatalf("%s: change row not written in the change transaction", operation) } if target != 0 && (!e.TargetUserID.Valid || e.TargetUserID.Int64 != target) { t.Fatalf("%s: target %v", operation, e.TargetUserID) } if string(e.Before) != before || string(e.After) != after { t.Fatalf("%s: before %s after %s", operation, e.Before, e.After) } return e } func expectNoChange(t *testing.T, res webResult, operation string, status int) auditEntry { t.Helper() e := expectOneAudit(t, res, operation, status) if res.audit[0].inTx || e.Before != nil || e.After != nil { t.Fatalf("%s: unexpected change row %+v", operation, res.audit[0]) } return e } func userSnapshot(u userRow) string { return string(auditUserJSON(u)) } func TestAccountRead(t *testing.T) { h := newWebHarness(t) admin := h.user("admin", roleAdmin) alice := h.user("alice", roleUser) h.store.addZone(testZone) h.store.delegate(testZone, alice) h.store.delegate("gone.org.", alice) h.store.delegate(testZone, admin) res := h.api("GET", "/account", h.login(alice), "") if res.status != 200 || res.body != `{"username":"alice","role":"user","zones":["example.org."]}` { t.Fatalf("%d %s", res.status, res.body) } expectNoChange(t, res, opAccountRead, 200) res = h.api("GET", "/account", h.login(admin), "") if res.body != `{"username":"admin","role":"admin","zones":[]}` { t.Fatal(res.body) } h.store.failOn["UserZones"] = errDatabase expectError(t, h.api("GET", "/account", h.login(alice), ""), 503, `{"error":"database unavailable"}`) } func TestPasswordChange(t *testing.T) { h := newWebHarness(t) alice := h.user("alice", roleUser) token := h.login(alice) other := h.login(alice) path := "/account/password" res := h.api("PUT", path, token, `{"current":"wrong-password","password":"brand-new-password"}`) expectError(t, res, 422, `{"error":"invalid password change","fields":{"current":"current password is wrong"}}`) expectNoChange(t, res, opPasswordChange, 422) res = h.api("PUT", path, token, `{"current":"wrong","password":"short"}`) expectError(t, res, 422, `{"error":"invalid password change","fields":{"current":"current password is wrong","password":"password must be 12 to 256 bytes"}}`) res = h.api("PUT", path, token, `{"current":"`+testPassword+`","password":"short"}`) expectError(t, res, 422, `{"error":"invalid password change","fields":{"password":"password must be 12 to 256 bytes"}}`) res = h.api("PUT", path, token, `{"current":"`+testPassword+`"`) expectError(t, res, 400, `{"error":"malformed JSON"}`) expectNoChange(t, res, opPasswordChange, 400) res = h.do(webRequest{method: "PUT", path: apiPrefix + path, token: token, body: `{}`, ctype: "text/plain"}) expectError(t, res, 415, `{"error":"content type must be application/json"}`) expectError(t, h.api("PUT", path, token, ""), 400, `{"error":"request body is required"}`) h.s.hashPassword = func(string) (string, error) { return "", errors.New("argon2 broke") } expectError(t, h.api("PUT", path, token, `{"current":"`+testPassword+`","password":"brand-new-password"}`), 500, `{"error":"internal error"}`) h.s.hashPassword = func(p string) (string, error) { return fakeHash(p), nil } h.store.failOn["DeleteUserSessionsExcept"] = errors.New("boom") expectError(t, h.api("PUT", path, token, `{"current":"`+testPassword+`","password":"brand-new-password"}`), 500, `{"error":"internal error"}`) if h.stored("alice").PasswordHash != fakeHash(testPassword) { t.Fatal("failed change kept") } delete(h.store.failOn, "DeleteUserSessionsExcept") res = h.api("PUT", path, token, `{"current":"`+testPassword+`","password":"brand-new-password"}`) if res.status != 204 || res.body != "" { t.Fatalf("%d %s", res.status, res.body) } expectChange(t, res, opPasswordChange, 204, alice.ID, userSnapshot(alice), userSnapshot(alice)) if h.stored("alice").PasswordHash != fakeHash("brand-new-password") { t.Fatal("password not changed") } if h.api("GET", "/account", token, "").status != 200 || h.api("GET", "/account", other, "").status != 401 { t.Fatal("other sessions must end, the current one must stay") } gone := h.stored("alice") gone.DeletedAt = sql.NullTime{Time: webNow, Valid: true} h.store.onLock = nil h.store.failOn = map[string]error{} h.store.setUser(gone) h.s.store = &deletedDuringRequest{fakeWebStore: h.store, user: gone} res = h.api("PUT", path, token, `{"current":"brand-new-password","password":"another-password"}`) expectError(t, res, 401, `{"error":"authentication required"}`) } type deletedDuringRequest struct { *fakeWebStore user userRow } func (d *deletedDuringRequest) SessionByTokenHash(ctx context.Context, h []byte) (sessionWithUser, error) { s, err := d.fakeWebStore.SessionByTokenHash(ctx, h) s.User.DeletedAt = sql.NullTime{} return s, err } func delegationHarness(t *testing.T) (*webHarness, string) { h := newWebHarness(t) admin := h.user("admin", roleAdmin) h.user("root", roleAdmin) bob := h.user("bob", roleUser) carol := h.user("carol", roleUser) gone := h.user("gone", roleUser) gone.DeletedAt = sql.NullTime{Time: webNow.Add(-time.Hour), Valid: true} h.store.setUser(gone) h.store.addZone(testZone) h.store.addZone(otherZone) h.store.delegate(testZone, carol) h.store.delegate(testZone, gone) h.store.delegate(testZone, h.users["root"]) h.store.delegate("vanished.org.", bob) _ = bob return h, h.login(admin) } func TestDelegationList(t *testing.T) { h, token := delegationHarness(t) h.store.delegate(testZone, h.users["bob"]) res := h.api("GET", "/zones/EXAMPLE.org/users", token, "") if res.status != 200 || res.body != `{"users":[{"username":"bob","role":"user"},{"username":"carol","role":"user"}]}` { t.Fatalf("%d %s", res.status, res.body) } expectNoChange(t, res, opDelegationList, 200) res = h.api("GET", "/zones/"+otherZone+"/users", token, "") if res.body != `{"users":[]}` { t.Fatal(res.body) } res = h.api("GET", "/zones/missing.org/users", token, "") expectError(t, res, 404, `{"error":"zone not found"}`) expectNoChange(t, res, opDelegationList, 404) h.store.failOn["ZoneUsers"] = errDatabase expectError(t, h.api("GET", "/zones/example.org/users", token, ""), 503, `{"error":"database unavailable"}`) } func TestDelegationGrant(t *testing.T) { h, token := delegationHarness(t) bob := h.users["bob"] res := h.api("PUT", "/zones/Example.org/users/bob", token, "") if res.status != 204 || !h.store.hasDelegation(testZone, bob.ID) { t.Fatalf("%d %s", res.status, res.body) } if len(h.store.zoneLocks) != 1 || h.store.zoneLocks[0] != testZone { t.Fatalf("grant locks = %v", h.store.zoneLocks) } e := expectChange(t, res, opDelegationGrant, 204, bob.ID, "", `{"zone":"example.org.","username":"bob"}`) if e.Zone.String != testZone { t.Fatal(e.Zone) } res = h.api("PUT", "/zones/example.org./users/bob", token, "") if res.status != 204 { t.Fatal(res.status) } if e := expectNoChange(t, res, opDelegationGrant, 204); e.TargetUserID.Int64 != bob.ID { t.Fatal("target missing on an idempotent grant") } cases := []struct { path, body string status int }{ {"/zones/missing.org/users/bob", `{"error":"zone not found"}`, 404}, {"/zones/bad!zone/users/bob", `{"error":"zone not found"}`, 404}, {"/zones/example.org/users/nobody", `{"error":"user not found"}`, 404}, {"/zones/example.org/users/Bob", `{"error":"user not found"}`, 404}, {"/zones/example.org/users/gone", `{"error":"user not found"}`, 404}, {"/zones/example.org/users/root", `{"error":"zones cannot be delegated to admins","fields":{"username":"user is an admin and needs no delegation"}}`, 422}, {"/zones/example.org/users/admin", `{"error":"zones cannot be delegated to admins","fields":{"username":"user is an admin and needs no delegation"}}`, 422}, } for _, c := range cases { res := h.api("PUT", c.path, token, "") expectError(t, res, c.status, c.body) expectNoChange(t, res, opDelegationGrant, c.status) } if h.store.hasDelegation(otherZone, bob.ID) { t.Fatal("unexpected delegation") } h.store.failOn["GrantDelegation"] = errors.New("deadlock") expectError(t, h.api("PUT", "/zones/other.org/users/bob", token, ""), 500, `{"error":"internal error"}`) if h.store.hasDelegation(otherZone, bob.ID) { t.Fatal("failed grant kept") } } func TestDelegationRevoke(t *testing.T) { h, token := delegationHarness(t) carol, bob := h.users["carol"], h.users["bob"] res := h.api("DELETE", "/zones/example.org/users/carol", token, "") if res.status != 204 || h.store.hasDelegation(testZone, carol.ID) { t.Fatalf("%d %s", res.status, res.body) } if len(h.store.zoneLocks) != 1 || h.store.zoneLocks[0] != testZone { t.Fatalf("revoke locks = %v", h.store.zoneLocks) } expectChange(t, res, opDelegationRevoke, 204, carol.ID, `{"zone":"example.org.","username":"carol"}`, "") res = h.api("DELETE", "/zones/example.org/users/carol", token, "") expectError(t, res, 404, `{"error":"delegation not found"}`) expectNoChange(t, res, opDelegationRevoke, 404) res = h.api("DELETE", "/zones/vanished.org/users/bob", token, "") if res.status != 204 || h.store.hasDelegation("vanished.org.", bob.ID) { t.Fatal("delegation of a missing zone not revoked", res.status) } res = h.api("DELETE", "/zones/example.org/users/root", token, "") if res.status != 204 { t.Fatal("delegation kept by a promoted user not revocable", res.status) } for _, path := range []string{"/zones/example.org/users/gone", "/zones/example.org/users/nobody", "/zones/example.org/users/-x"} { res = h.api("DELETE", path, token, "") expectError(t, res, 404, `{"error":"user not found"}`) } if !h.store.hasDelegation(testZone, h.users["gone"].ID) { t.Fatal("deleted user's delegation changed") } expectError(t, h.api("DELETE", "/zones/bad!/users/bob", token, ""), 404, `{"error":"zone not found"}`) } func usersHarness(t *testing.T) (*webHarness, string) { h := newWebHarness(t) admin := h.user("admin", roleAdmin) h.user("root", roleAdmin) bob := h.user("bob", roleUser) gone := h.user("gone", roleUser) gone.DeletedAt = sql.NullTime{Time: webNow.Add(-time.Hour), Valid: true} gone.LastLoginAt = sql.NullTime{Time: webNow.Add(-2 * time.Hour), Valid: true} h.store.setUser(gone) h.users["gone"] = gone h.store.addZone(testZone) h.store.delegate(testZone, bob) h.store.delegate("vanished.org.", bob) return h, h.login(admin) } func TestAPIUserList(t *testing.T) { h, token := usersHarness(t) created := `"created_at":"2026-11-16T12:00:00Z"` res := h.api("GET", "/users", token, "") want := `{"users":[{"username":"admin","role":"admin","zone_count":0,` + created + `,"last_login_at":null,"deleted_at":null},` + `{"username":"bob","role":"user","zone_count":2,` + created + `,"last_login_at":null,"deleted_at":null},` + `{"username":"root","role":"admin","zone_count":0,` + created + `,"last_login_at":null,"deleted_at":null}]}` if res.status != 200 || res.body != want { t.Fatalf("%d %s", res.status, res.body) } expectNoChange(t, res, opUserList, 200) for _, q := range []string{"?deleted=false", "?deleted=", "?other=1"} { if r := h.api("GET", "/users"+q, token, ""); r.body != want { t.Fatal(q, r.body) } } res = h.api("GET", "/users?deleted=true", token, "") if !strings.Contains(res.body, `{"username":"gone","role":"user","zone_count":0,`+created+`,"last_login_at":"2026-11-18T10:00:00Z","deleted_at":"2026-11-18T11:00:00Z"}`) { t.Fatal(res.body) } res = h.api("GET", "/users?deleted=yes", token, "") expectError(t, res, 400, `{"error":"invalid parameter deleted"}`) expectNoChange(t, res, opUserList, 400) } func TestAPIUserCreate(t *testing.T) { h, token := usersHarness(t) h.clock.advance(1500 * time.Millisecond) res := h.api("POST", "/users", token, `{"username":"dora","role":"user","password":"dora-password-1"}`) if res.status != 201 || res.body != `{"username":"dora","role":"user","zone_count":0,"created_at":"2026-11-18T12:00:01.5Z","last_login_at":null,"deleted_at":null}` { t.Fatalf("%d %s", res.status, res.body) } dora := h.stored("dora") if dora.PasswordHash != fakeHash("dora-password-1") || dora.Role != roleUser { t.Fatalf("%+v", dora) } expectChange(t, res, opUserCreate, 201, dora.ID, "", userSnapshot(dora)) for _, name := range []string{"dora", "gone", "admin"} { res = h.api("POST", "/users", token, `{"username":"`+name+`","role":"admin","password":"long-enough-pw"}`) expectError(t, res, 409, `{"error":"username already used"}`) expectNoChange(t, res, opUserCreate, 409) } cases := map[string]string{ `{"username":"Bad Name","role":"user","password":"long-enough-pw"}`: `{"error":"invalid user","fields":{"username":"username must be 1 to 64 characters of lowercase letters, digits, dots, underscores and hyphens, starting with a letter or digit"}}`, `{"username":"cli","role":"user","password":"long-enough-pw"}`: `{"error":"invalid user","fields":{"username":"username is reserved"}}`, `{"username":"ed","role":"root","password":"long-enough-pw"}`: `{"error":"invalid user","fields":{"role":"must be admin or user"}}`, `{"username":"ed","role":"user","password":"short"}`: `{"error":"invalid user","fields":{"password":"password must be 12 to 256 bytes"}}`, `{}`: `{"error":"invalid user","fields":{"password":"password must be 12 to 256 bytes","role":"must be admin or user","username":"username must be 1 to 64 characters of lowercase letters, digits, dots, underscores and hyphens, starting with a letter or digit"}}`, `{"username":"ed","role":"user","password":12}`: `{"error":"invalid field type","fields":{"password":"must be a string"}}`, `{"username":"ed","role":"user","password":"x","a":1}`: `{"error":"request body has an unknown field"}`, } for body, want := range cases { res := h.api("POST", "/users", token, body) if res.status == 422 { expectError(t, res, 422, want) } else { expectError(t, res, 400, want) } } h.s.hashPassword = func(string) (string, error) { return "", errors.New("argon2 failure") } expectError(t, h.api("POST", "/users", token, `{"username":"ed","role":"user","password":"long-enough-pw"}`), 500, `{"error":"internal error"}`) } func TestAPIUserRead(t *testing.T) { h, token := usersHarness(t) bob := h.users["bob"] res := h.api("GET", "/users/bob", token, "") want := `{"username":"bob","role":"user","created_at":"2026-11-16T12:00:00Z","last_login_at":null,"deleted_at":null,"zones":[{"zone":"example.org.","exists":true},{"zone":"vanished.org.","exists":false}]}` if res.status != 200 || res.body != want { t.Fatalf("%d %s", res.status, res.body) } if e := expectNoChange(t, res, opUserRead, 200); e.TargetUserID.Int64 != bob.ID { t.Fatal("target") } res = h.api("GET", "/users/gone", token, "") if res.status != 200 || !strings.Contains(res.body, `"deleted_at":"2026-11-18T11:00:00Z","zones":[]`) { t.Fatal(res.body) } for _, name := range []string{"nobody", "UPPER", "a%20b"} { res = h.api("GET", "/users/"+name, token, "") expectError(t, res, 404, `{"error":"user not found"}`) if e := expectNoChange(t, res, opUserRead, 404); e.TargetUserID.Valid { t.Fatal("target on a missing user") } } h.store.failOn["UserByUsername"] = errDatabase expectError(t, h.api("GET", "/users/bob", token, ""), 503, `{"error":"database unavailable"}`) delete(h.store.failOn, "UserByUsername") h.store.failOn["UserZones"] = errors.New("x") expectError(t, h.api("GET", "/users/bob", token, ""), 500, `{"error":"internal error"}`) } func TestAPIUserRole(t *testing.T) { h, token := usersHarness(t) bob := h.users["bob"] res := h.api("PUT", "/users/bob/role", token, `{"role":"admin"}`) if res.status != 204 || h.stored("bob").Role != roleAdmin { t.Fatalf("%d %s", res.status, res.body) } promoted := bob promoted.Role = roleAdmin expectChange(t, res, opUserRole, 204, bob.ID, userSnapshot(bob), userSnapshot(promoted)) if !h.store.hasDelegation(testZone, bob.ID) { t.Fatal("promotion dropped delegations") } res = h.api("PUT", "/users/bob/role", token, `{"role":"admin"}`) if res.status != 204 { t.Fatal(res.status) } expectNoChange(t, res, opUserRole, 204) if h.store.called("LockActiveAdmins") != 2 { t.Fatal("active admins not locked in the change transaction") } res = h.api("PUT", "/users/admin/role", token, `{"role":"user"}`) expectError(t, res, 403, `{"error":"use the account page to change your own account"}`) if e := expectNoChange(t, res, opUserRole, 403); e.TargetUserID.Int64 != 1 { t.Fatal("target on own account refusal") } for _, c := range []struct { path, body, want string status int }{ {"/users/gone/role", `{"role":"admin"}`, `{"error":"user not found"}`, 404}, {"/users/nobody/role", `{"role":"admin"}`, `{"error":"user not found"}`, 404}, {"/users/bob/role", `{"role":"owner"}`, `{"error":"invalid role","fields":{"role":"must be admin or user"}}`, 422}, {"/users/bob/role", `{"role":5}`, `{"error":"invalid field type","fields":{"role":"must be a string"}}`, 422}, {"/users/bob/role", ``, `{"error":"request body is required"}`, 400}, } { res := h.api("PUT", c.path, token, c.body) expectError(t, res, c.status, c.want) expectNoChange(t, res, opUserRole, c.status) } if h.stored("gone").Role != roleUser { t.Fatal("deleted user changed") } h.store.onLock = func(st *fakeWebState) { for i := range st.users { if st.users[i].Username != "root" { st.users[i].Role = roleUser } } } res = h.api("PUT", "/users/root/role", token, `{"role":"user"}`) expectError(t, res, 403, `{"error":"admin role required"}`) expectNoChange(t, res, opUserRole, 403) if h.stored("root").Role != roleAdmin || h.stored("admin").Role != roleAdmin { t.Fatal("change by a demoted actor kept") } h.store.onLock = nil h.store.failOn["SetRole"] = errors.New("x") expectError(t, h.api("PUT", "/users/root/role", token, `{"role":"user"}`), 500, `{"error":"internal error"}`) delete(h.store.failOn, "SetRole") h.store.failOn["LockActiveAdmins"] = errLockTimeout expectError(t, h.api("PUT", "/users/root/role", token, `{"role":"user"}`), 503, `{"error":"zone busy"}`) } func TestAPIUserPassword(t *testing.T) { h, token := usersHarness(t) bob := h.users["bob"] t1, t2 := h.login(bob), h.login(bob) res := h.api("PUT", "/users/bob/password", token, `{"password":"reset-password-1"}`) if res.status != 204 || h.stored("bob").PasswordHash != fakeHash("reset-password-1") { t.Fatalf("%d %s", res.status, res.body) } expectChange(t, res, opUserPassword, 204, bob.ID, userSnapshot(bob), userSnapshot(bob)) if h.store.sessionCount(bob.ID) != 0 || h.api("GET", "/account", t1, "").status != 401 || h.api("GET", "/account", t2, "").status != 401 { t.Fatal("sessions not ended") } expectError(t, h.api("PUT", "/users/admin/password", token, `{"password":"reset-password-1"}`), 403, `{"error":"use the account page to change your own account"}`) expectError(t, h.api("PUT", "/users/gone/password", token, `{"password":"reset-password-1"}`), 404, `{"error":"user not found"}`) expectError(t, h.api("PUT", "/users/nobody/password", token, `{"password":"reset-password-1"}`), 404, `{"error":"user not found"}`) expectError(t, h.api("PUT", "/users/bob/password", token, `{"password":"tiny"}`), 422, `{"error":"invalid password","fields":{"password":"password must be 12 to 256 bytes"}}`) expectError(t, h.api("PUT", "/users/bob/password", token, `{"password":"bad\u0007-password-x"}`), 422, `{"error":"invalid password","fields":{"password":"password must not contain control characters"}}`) h.s.hashPassword = func(string) (string, error) { return "", errors.New("x") } expectError(t, h.api("PUT", "/users/bob/password", token, `{"password":"reset-password-2"}`), 500, `{"error":"internal error"}`) h.s.hashPassword = func(p string) (string, error) { return fakeHash(p), nil } h.store.failOn["DeleteUserSessions"] = errors.New("x") expectError(t, h.api("PUT", "/users/bob/password", token, `{"password":"reset-password-2"}`), 500, `{"error":"internal error"}`) if h.stored("bob").PasswordHash != fakeHash("reset-password-1") { t.Fatal("rolled back change kept") } } func TestAPIUserDelete(t *testing.T) { h, token := usersHarness(t) bob := h.users["bob"] bt := h.login(bob) res := h.api("DELETE", "/users/bob", token, `{"confirm":"bob "}`) expectError(t, res, 422, `{"error":"invalid confirm","fields":{"confirm":"confirmation does not match"}}`) expectNoChange(t, res, opUserDelete, 422) expectError(t, h.api("DELETE", "/users/bob", token, ""), 400, `{"error":"request body is required"}`) h.clock.advance(time.Second) res = h.api("DELETE", "/users/bob", token, `{"confirm":"bob"}`) stored := h.stored("bob") if res.status != 204 || !stored.DeletedAt.Valid || !stored.DeletedAt.Time.Equal(webNow.Add(time.Second)) { t.Fatalf("%d %s %+v", res.status, res.body, stored) } after := bob after.DeletedAt = sql.NullTime{Time: webNow.Add(time.Second), Valid: true} expectChange(t, res, opUserDelete, 204, bob.ID, userSnapshot(bob), userSnapshot(after)) if h.api("GET", "/account", bt, "").status != 401 || h.store.sessionCount(bob.ID) != 0 { t.Fatal("sessions survive deletion") } if !h.store.hasDelegation(testZone, bob.ID) { t.Fatal("delegations must stay") } expectError(t, h.api("DELETE", "/users/bob", token, `{"confirm":"bob"}`), 404, `{"error":"user not found"}`) expectError(t, h.api("DELETE", "/users/admin", token, `{"confirm":"admin"}`), 403, `{"error":"use the account page to change your own account"}`) h.store.onLock = func(st *fakeWebState) { st.users[0].DeletedAt = sql.NullTime{Time: webNow, Valid: true} } res = h.api("DELETE", "/users/root", token, `{"confirm":"root"}`) expectError(t, res, 403, `{"error":"admin role required"}`) expectNoChange(t, res, opUserDelete, 403) if h.stored("root").DeletedAt.Valid || h.stored("admin").DeletedAt.Valid { t.Fatal("rolled back state kept") } h.store.onLock = nil res = h.api("DELETE", "/users/root", token, `{"confirm":"root"}`) if res.status != 204 { t.Fatal("admin with another active admin not deletable", res.status) } h.store.failOn["MarkDeleted"] = errors.New("x") h.user("eve", roleUser) expectError(t, h.api("DELETE", "/users/eve", token, `{"confirm":"eve"}`), 500, `{"error":"internal error"}`) } func auditHarness(t *testing.T) (*webHarness, string, string) { h := newWebHarness(t) admin := h.user("admin", roleAdmin) alice := h.user("alice", roleUser) bob := h.user("bob", roleUser) h.store.addZone(testZone) h.store.delegate(testZone, alice) add := func(u userRow, op, zone string, status int64, before, after string) { e := auditEntry{Time: webNow, UserID: sql.NullInt64{Int64: u.ID, Valid: true}, Actor: u.Username, Origin: "192.0.2.1", Operation: op, Status: sql.NullInt64{Int64: status, Valid: true}} if zone != "" { e.Zone = sql.NullString{String: zone, Valid: true} } if before != "" { e.Before = []byte(before) } if after != "" { e.After = []byte(after) } if status >= 400 { e.Error = sql.NullString{String: "failed", Valid: true} } _, _ = h.store.InsertAudit(context.Background(), e) } add(admin, opZoneCreate, testZone, 201, "", `{"id":1}`) add(bob, opZoneRead, otherZone, 404, "", "") add(alice, opAccountRead, "", 200, "", "") add(bob, opRecordUpdate, testZone, 200, `{"ttl":1}`, `{"ttl":2}`) add(admin, opUserRole, "", 204, `{"role":"user"}`, `{"role":"admin"}`) _, _ = h.store.InsertAudit(context.Background(), auditEntry{Time: webNow, Actor: "cli", Origin: "local", Operation: opUserCreate, TargetUserID: sql.NullInt64{Int64: bob.ID, Valid: true}, After: []byte(`{"id":3}`)}) return h, h.login(admin), h.login(alice) } type auditPage struct { Entries []struct { ID int64 `json:"id"` Time string `json:"time"` Actor string `json:"actor"` Origin string `json:"origin"` Operation string `json:"operation"` Status *int64 `json:"status"` Error *string `json:"error"` Zone *string `json:"zone"` RecordID *int64 `json:"record_id"` TargetUser *string `json:"target_user"` Before json.RawMessage `json:"before"` After json.RawMessage `json:"after"` } `json:"entries"` NextBeforeID *int64 `json:"next_before_id"` } func (r webResult) auditPage(t *testing.T) auditPage { t.Helper() var p auditPage if err := json.Unmarshal([]byte(r.body), &p); err != nil { t.Fatal(r.body, err) } return p } func TestAuditRead(t *testing.T) { h, adminToken, aliceToken := auditHarness(t) res := h.api("GET", "/audit", adminToken, "") if res.status != 200 { t.Fatal(res.status, res.body) } expectNoChange(t, res, opAuditRead, 200) p := res.auditPage(t) if len(p.Entries) != 6 || p.NextBeforeID != nil || p.Entries[0].ID != 6 || p.Entries[5].ID != 1 { t.Fatalf("%s", res.body) } cli := p.Entries[0] if cli.Actor != "cli" || cli.Status != nil || cli.Error != nil || cli.Zone != nil || *cli.TargetUser != "bob" || string(cli.After) != `{"id":3}` || string(cli.Before) != "null" || cli.Time != "2026-11-18T12:00:00Z" { t.Fatalf("%+v", cli) } if !strings.Contains(res.body, `{"id":4,"time":"2026-11-18T12:00:00Z","actor":"bob","origin":"192.0.2.1","operation":"record_update","status":200,"error":null,"zone":"example.org.","record_id":null,"target_user":null,"before":{"ttl":1},"after":{"ttl":2}}`) { t.Fatal(res.body) } res = h.api("GET", "/audit?limit=2", adminToken, "") p = res.auditPage(t) if len(p.Entries) != 2 || p.NextBeforeID == nil || *p.NextBeforeID != 6 { t.Fatal(res.body) } res = h.api("GET", "/audit?limit=2&before_id=6", adminToken, "") p = res.auditPage(t) if len(p.Entries) != 2 || p.Entries[0].ID != 5 || *p.NextBeforeID != 4 { t.Fatal(res.body) } res = h.api("GET", "/audit", aliceToken, "") p = res.auditPage(t) var ids []int64 for _, e := range p.Entries { ids = append(ids, e.ID) } if fmt.Sprint(ids) != "[4 3 1]" { t.Fatalf("user sees %v", ids) } h.store.failOn["UserZones"] = errDatabase expectError(t, h.api("GET", "/audit", aliceToken, ""), 503, `{"error":"database unavailable"}`) delete(h.store.failOn, "UserZones") h.store.failOn["ListAudit"] = errors.New("x") expectError(t, h.api("GET", "/audit", adminToken, ""), 500, `{"error":"internal error"}`) } func TestAuditFilterParsing(t *testing.T) { h, adminToken, _ := auditHarness(t) res := h.api("GET", "/audit?operation=record_update", adminToken, "") if p := res.auditPage(t); len(p.Entries) != 1 || p.Entries[0].Operation != "record_update" { t.Fatal(res.body) } good := map[string]auditFilter{ "": {Limit: 50}, "zone=Example.ORG": {Zone: testZone, Limit: 50}, "actor=alice": {Actor: "alice", Limit: 50}, "operation=login": {Operation: "login", Limit: 50}, "kind=read&outcome=error": {Kind: "read", Outcome: "error", Limit: 50}, "kind=change&outcome=success": {Kind: "change", Outcome: "success", Limit: 50}, "before_id=9007199254740991&limit=200": {BeforeID: 9007199254740991, Limit: 200}, "limit=1": {Limit: 1}, } for q, want := range good { values, _ := url.ParseQuery(q) got, err := parseAuditFilter(values) if err != nil || got != want { t.Errorf("%q: %+v %v", q, got, err) } } bad := map[string]string{ "zone=bad!": "zone", "actor=" + strings.Repeat("a", 65): "actor", "operation=drop": "operation", "kind=all": "kind", "outcome=ok": "outcome", "before_id=0": "before_id", "before_id=-1": "before_id", "before_id=1e3": "before_id", "before_id=99999999999999999999": "before_id", "before_id=9007199254740992": "before_id", "limit=0": "limit", "limit=201": "limit", "limit=+5": "limit", "limit=5x": "limit", } for q, param := range bad { res := h.api("GET", "/audit?"+q, adminToken, "") expectError(t, res, 400, `{"error":"invalid parameter `+param+`"}`) expectNoChange(t, res, opAuditRead, 400) } } func TestAuditRawJSONFallback(t *testing.T) { if string(rawJSON(nil)) != "null" || string(rawJSON([]byte("{bad"))) != "null" || string(rawJSON([]byte(`[1]`))) != "[1]" { t.Fatal("rawJSON") } if nullInt(sql.NullInt64{}) != nil || *nullInt(sql.NullInt64{Int64: 4, Valid: true}) != 4 || nullString(sql.NullString{}) != nil { t.Fatal("null helpers") } } type matrixPersona struct { name string username string token string } type matrixRoute struct { method, path, body string ifMatch int64 op string access string allowed int } func matrixRoutes() []matrixRoute { return []matrixRoute{ {"GET", "/account", "", 0, opAccountRead, accessSession, 200}, {"PUT", "/account/password", `{"current":"` + testPassword + `","password":"another-password"}`, 0, opPasswordChange, accessSession, 204}, {"GET", "/zones", "", 0, opZoneList, accessSession, 200}, {"POST", "/zones", mxCreateNew, 0, opZoneCreate, accessAdmin, 201}, {"GET", "/zones/example.org.", "", 0, opZoneRead, accessZone, 200}, {"DELETE", "/zones/example.org.", `{"confirm":"example.org."}`, 0, opZoneDelete, accessAdmin, 204}, {"GET", "/zones/example.org./records", "", 0, opRecordList, accessZone, 200}, {"POST", "/zones/example.org./records", mxRecordBody, 0, opRecordCreate, accessZone, 201}, {"PUT", "/zones/example.org./records/3", mxUpdateBody, 3, opRecordUpdate, accessZone, 200}, {"DELETE", "/zones/example.org./records/4", "", 4, opRecordDelete, accessZone, 200}, {"POST", "/zones/example.org./records/delete", mxBulk(3, 4), 0, opRecordBulkDelete, accessZone, 200}, {"PUT", "/zones/example.org./soa", mxSOABody, 1, opSOAUpdate, accessZone, 200}, {"GET", "/zones/example.org./check", "", 0, opZoneCheck, accessZone, 200}, {"GET", "/check", "", 0, opCheckAll, accessSession, 200}, {"GET", "/zones/example.org./export", "", 0, opZoneExport, accessZone, 200}, {"POST", "/zones/example.org./import/preview", `{"mode":"merge","content":"new 60 A 192.0.2.10\n"}`, 0, opZoneImportPreview, accessZone, 200}, {"POST", "/zones/example.org./import/apply", `{"mode":"merge","content":"new 60 A 192.0.2.10\n","fingerprint":"` + zoneFingerprint(matrixSeedRecords()[:4]) + `"}`, 0, opZoneImport, accessZone, 200}, {"GET", "/zones/example.org./users", "", 0, opDelegationList, accessAdmin, 200}, {"PUT", "/zones/example.org./users/carol", "", 0, opDelegationGrant, accessAdmin, 204}, {"DELETE", "/zones/example.org./users/bob", "", 0, opDelegationRevoke, accessAdmin, 204}, {"GET", "/users", "", 0, opUserList, accessAdmin, 200}, {"POST", "/users", `{"username":"newbie","role":"user","password":"long-enough-pw"}`, 0, opUserCreate, accessAdmin, 201}, {"GET", "/users/bob", "", 0, opUserRead, accessAdmin, 200}, {"PUT", "/users/bob/role", `{"role":"admin"}`, 0, opUserRole, accessAdmin, 204}, {"PUT", "/users/bob/password", `{"password":"long-enough-pw"}`, 0, opUserPassword, accessAdmin, 204}, {"DELETE", "/users/bob", `{"confirm":"bob"}`, 0, opUserDelete, accessAdmin, 204}, {"GET", "/audit", "", 0, opAuditRead, accessSession, 200}, } } func matrixHarness(t *testing.T) (*webHarness, []matrixPersona) { env := newMatrixEnv(t) h := env.h promoted := h.user("pat", roleUser) demoted := h.user("dan", roleAdmin) h.store.delegate(testZone, promoted) personas := []matrixPersona{ {"admin", "admin", env.tokens["admin"]}, {"delegated user", "alice", env.tokens["alice"]}, {"user without delegation", "dave", env.tokens["dave"]}, {"promoted user", "pat", h.login(promoted)}, {"demoted admin", "dan", h.login(demoted)}, {"deleted user", "gone", env.tokens["gone"]}, {"no session", "", ""}, } promoted.Role = roleAdmin h.store.setUser(promoted) demoted.Role = roleUser h.store.setUser(demoted) return h, personas } func expectedMatrixStatus(persona string, r matrixRoute) (int, string) { switch persona { case "deleted user", "no session": return 401, `{"error":"authentication required"}` case "admin", "promoted user": return r.allowed, "" } switch r.access { case accessAdmin: return 403, `{"error":"admin role required"}` case accessZone: if persona == "delegated user" { return r.allowed, "" } return 404, `{"error":"zone not found"}` } return r.allowed, "" } func TestAPIAuthorizationMatrix(t *testing.T) { if len(matrixRoutes()) != len(apiRoutes) { t.Fatalf("authorization matrix has %d routes, the route table %d", len(matrixRoutes()), len(apiRoutes)) } for _, r := range matrixRoutes() { for i := range 7 { h, personas := matrixHarness(t) p := personas[i] req := webRequest{method: r.method, path: apiPrefix + r.path, token: p.token, body: r.body} if r.ifMatch != 0 { req.header = map[string]string{"If-Match": recordETag(matrixSeed(r.ifMatch))} } res := h.do(req) status, body := expectedMatrixStatus(p.name, r) if res.status != status || (body != "" && res.body != body) { t.Errorf("%s %s as %s: %d %s, want %d", r.method, r.path, p.name, res.status, res.body, status) continue } if status == 401 { if len(res.audit) != 0 { t.Errorf("%s %s as %s: audit row without session", r.method, r.path, p.name) } continue } e := expectOneAudit(t, res, r.op, status) if e.Actor != p.username || !e.UserID.Valid || e.UserID.Int64 != h.users[p.username].ID || e.Origin != "192.0.2.10" || !e.Time.Equal(webNow) { t.Errorf("%s as %s: %+v", r.op, p.name, e) } if strings.Contains(r.path, "example.org.") != (e.Zone.Valid && e.Zone.String == testZone) && r.op != opZoneCreate { t.Errorf("%s as %s: zone %v", r.op, p.name, e.Zone) } } } } func TestZoneNotFoundResponsesIdentical(t *testing.T) { h, personas := matrixHarness(t) admin, delegated, plain := personas[0].token, personas[1].token, personas[2].token results := []webResult{ h.api("GET", "/zones/example.org.", plain, ""), h.api("GET", "/zones/missing.org.", plain, ""), h.api("GET", "/zones/missing.org.", admin, ""), h.api("GET", "/zones/stale.org.", delegated, ""), h.api("GET", "/zones/stale.org./records", delegated, ""), h.api("POST", "/zones/stale.org./records", delegated, mxRecordBody), h.api("POST", "/zones/example.org./records", plain, mxRecordBody), h.api("PUT", "/zones/missing.org./soa", admin, mxSOABody), } a := results[0] for i, r := range results { if r.status != 404 || r.body != `{"error":"zone not found"}` || r.header.Get("Content-Type") != a.header.Get("Content-Type") || len(r.header) != len(a.header) { t.Fatalf("response %d: %d %s %v", i, r.status, r.body, r.header) } } } func TestNoSecretsInAuditOrLogs(t *testing.T) { h := newWebHarness(t) admin := h.user("admin", roleAdmin) h.user("bob", roleUser) h.store.addZone(testZone) token := h.login(admin) secrets := []string{"admin-new-password", "bob-new-password", "created-user-pw", testPassword, "wrong-password-xyz", token, "$fake$"} h.do(webRequest{method: "POST", path: "/login", body: "username=admin&password=wrong-password-xyz", ctype: "application/x-www-form-urlencoded"}) login := h.do(webRequest{method: "POST", path: "/login", body: "username=admin&password=" + testPassword, ctype: "application/x-www-form-urlencoded"}) for _, c := range login.header.Values("Set-Cookie") { v := strings.TrimPrefix(strings.Split(c, ";")[0], sessionCookieName+"=") secrets = append(secrets, v) } h.api("POST", "/users", token, `{"username":"carl","role":"user","password":"created-user-pw"}`) h.api("PUT", "/users/bob/password", token, `{"password":"bob-new-password"}`) h.api("PUT", "/account/password", token, `{"current":"`+testPassword+`","password":"admin-new-password"}`) h.api("POST", "/users", token, `{"username":"Bad","role":"user","password":"another-secret-1"}`) secrets = append(secrets, "another-secret-1") h.do(webRequest{method: "POST", path: "/logout", token: token}) rows := h.store.auditRows() if len(rows) < 7 { t.Fatal(len(rows)) } logs := h.logs.String() for _, row := range rows { e := row.entry text := strings.Join([]string{e.Actor, e.Origin, e.Operation, e.Error.String, e.Zone.String, string(e.Before), string(e.After)}, "|") for _, s := range secrets { if s != "" && strings.Contains(text, s) { t.Fatalf("secret %q in audit row %s", s, text) } } if strings.Contains(string(e.Before)+string(e.After), "password") { t.Fatalf("password field in audit row %s", text) } } for _, s := range secrets { if s != "" && strings.Contains(logs, s) { t.Fatalf("secret %q in logs", s) } } if strings.Contains(logs, "Cookie") || strings.Contains(logs, sessionCookieName) { t.Fatal("cookie in logs") } } func TestHandlersRequireStoredUserChanges(t *testing.T) { h, token := usersHarness(t) h.store.failOn["UserByUsernameForUpdate"] = errDatabase for _, r := range []struct{ method, path, body string }{ {"PUT", "/users/bob/role", `{"role":"admin"}`}, {"PUT", "/users/bob/password", `{"password":"long-enough-pw"}`}, {"DELETE", "/users/bob", `{"confirm":"bob"}`}, {"PUT", "/zones/example.org./users/bob", ""}, {"DELETE", "/zones/example.org./users/bob", ""}, } { expectError(t, h.api(r.method, r.path, token, r.body), http.StatusServiceUnavailable, `{"error":"database unavailable"}`) } delete(h.store.failOn, "UserByUsernameForUpdate") h.store.failOn["ZoneExists"] = errors.New("x") expectError(t, h.api("PUT", "/zones/example.org./users/bob", token, ""), 500, `{"error":"internal error"}`) expectError(t, h.api("GET", "/zones/example.org./users", token, ""), 500, `{"error":"internal error"}`) delete(h.store.failOn, "ZoneExists") h.store.failOn["RevokeDelegation"] = errors.New("x") expectError(t, h.api("DELETE", "/zones/example.org./users/bob", token, ""), 500, `{"error":"internal error"}`) delete(h.store.failOn, "RevokeDelegation") h.store.failOn["CreateUser"] = errors.New("x") expectError(t, h.api("POST", "/users", token, `{"username":"zed","role":"user","password":"long-enough-pw"}`), 500, `{"error":"internal error"}`) h.store.failOn["ListUsers"] = errors.New("x") expectError(t, h.api("GET", "/users", token, ""), 500, `{"error":"internal error"}`) h.store.failOn["UserByIDForUpdate"] = errors.New("x") h.store.failOn["InTx"] = errDatabase expectError(t, h.api("PUT", "/users/bob/role", token, `{"role":"admin"}`), 503, `{"error":"database unavailable"}`) } const zoneAPITestName = "example.org." const zoneAPITestSOA = `{"ns":"ns.example.net","mbox":"hostmaster@example.org","ttl":3600,"refresh":3600,"retry":600,"expire":604800,"minttl":300}` var zoneAPITestCreate = `{"name":"Example.ORG","extra_ns":["backup.example.net"],` + zoneAPITestSOA[1:] const zoneAPITestRecord = `{"name":"new","type":"A","ttl":60,"data":{"ip":"192.0.2.10"}}` func zoneAPITestRequest(server *WebServer, actor userRow, operation, zone, id, etag, body string) *apiContext { method := http.MethodGet switch operation { case "zone_create", "record_create", "record_bulk_delete", "zone_import_preview", "zone_import": method = http.MethodPost case "record_update", "soa_update": method = http.MethodPut case "zone_delete", "record_delete": method = http.MethodDelete } req := httptest.NewRequest(method, "/api/v1/test", strings.NewReader(body)) if body != "" { req.Header.Set("Content-Type", "application/json") } if etag != "" { req.Header.Set("If-Match", etag) } entry := &auditEntry{ Time: modelNow, UserID: sql.NullInt64{Int64: actor.ID, Valid: true}, Actor: actor.Username, Origin: "127.0.0.1", Operation: operation, Zone: sql.NullString{String: zone, Valid: zone != ""}, } return &apiContext{ Request: req, Principal: principal{User: actor}, Zone: zone, Vars: map[string]string{"id": id}, Now: modelNow, Entry: entry, Server: server, } } func zoneAPITestCall(ctx context.Context, c *apiContext) (apiResponse, error) { return zoneAPIHandlers(c.Server)[c.Entry.Operation](ctx, c) } func zoneAPITestStatus(t *testing.T, ctx context.Context, c *apiContext, status int) apiResponse { t.Helper() resp, err := zoneAPITestCall(ctx, c) if status >= 400 { var apiErr *apiError if !errors.As(err, &apiErr) || apiErr.Status != status { t.Fatalf("%s: got response %+v, error %v, want %d", c.Entry.Operation, resp, err, status) } return resp } if err != nil || resp.Status != status { t.Fatalf("%s: got response %+v, error %v, want %d", c.Entry.Operation, resp, err, status) } return resp } func zoneAPITestJSON(t *testing.T, value any) string { t.Helper() body, err := json.Marshal(value) if err != nil { t.Fatal(err) } return string(body) } func zoneAPITestRows(t *testing.T) []recordRow { t.Helper() rows, fields := newZoneRows(newZoneSpec{ Zone: zoneAPITestName, PrimaryNS: "ns.example.net", Mailbox: "hostmaster@example.org", TTL: 3600, Refresh: 3600, Retry: 600, Expire: 604800, MinTTL: 300, }, modelNow) if len(fields) != 0 { t.Fatal(fields) } for _, name := range []string{"first", "second"} { row, fields := validateRecord(zoneAPITestName, name, "A", 60, []byte(`{"ip":"192.0.2.1"}`), modelNow) if len(fields) != 0 { t.Fatal(fields) } rows = append(rows, row) } for i := range rows { rows[i].ID = int64(i + 1) } return rows } type zoneAPITestDB struct { t *testing.T rows []recordRow foreign recordRow actor userRow hasActor bool delegated bool stale bool locked bool auditError error writeError error lastID int64 fail func(query string) error hideInsert bool } func zoneAPITestDBFor(t *testing.T, rows []recordRow) *zoneAPITestDB { t.Helper() return &zoneAPITestDB{ t: t, rows: slices.Clone(rows), actor: userRow{ID: 17, Username: "alice", Role: "admin"}, hasActor: true, delegated: true, } } func zoneAPITestValues(row recordRow) []driver.Value { ttl, _ := row.TTL.Value() content, _ := row.Content.Value() return []driver.Value{row.ID, row.Zone, row.Name, ttl, content, row.RecordType} } func (f *zoneAPITestDB) server() (*WebServer, *fdbState) { for _, row := range f.rows { f.lastID = max(f.lastID, row.ID) } db, state := newFakeDB(f.t, f.query) return &WebServer{db: db, tables: fdbTables(f.t), log: discardLogger()}, state } func (f *zoneAPITestDB) query(query string, args []any) fdbResponse { has := func(value string) bool { return strings.Contains(query, value) } if f.fail != nil { if err := f.fail(query); err != nil { return fdbResponse{err: err} } } switch { case has("GET_LOCK"): if f.locked { return fdbResponse{rows: fdbRow(int64(0))} } return fdbResponse{rows: fdbRow(int64(1))} case has("RELEASE_LOCK"): return fdbResponse{rows: fdbRow(int64(1))} case has("SELECT u.") && has("LOCK IN SHARE MODE"): if !f.hasActor { return fdbResponse{} } deleted, _ := f.actor.DeletedAt.Value() return fdbResponse{rows: fdbRow(f.actor.ID, f.actor.Username, f.actor.Role, "hash", modelNow, modelNow, nil, deleted)} case has("SELECT 1 FROM") && has("zone_delegations") && has("LOCK IN SHARE MODE"): if f.delegated { return fdbResponse{rows: fdbRow(int64(1))} } return fdbResponse{} case has("COUNT(*)") && has("GROUP BY"): if len(f.rows) == 0 || has("d.`user_id`") && !f.delegated { return fdbResponse{} } var rows [][]driver.Value soa := zoneAPIFindSOA(f.rows) content, _ := soa.Content.Value() rows = append(rows, []driver.Value{f.rows[0].Zone, int64(len(f.rows)), content}) if !has("d.`user_id`") && f.foreign.ID != 0 { rows = append(rows, []driver.Value{f.foreign.Zone, int64(1), nil}) } return fdbResponse{rows: rows} case has("SELECT d.") && has("ORDER BY username FOR UPDATE"): if f.stale { return fdbResponse{rows: fdbRow(args[0], int64(18), "bob", modelNow, f.actor.ID)} } return fdbResponse{} case has("SELECT `id`") && has(zoneRowsWhere): var rows [][]driver.Value for _, row := range append(slices.Clone(f.rows), f.foreign) { if zoneAPITestKey(row.Zone) == args[0] { rows = append(rows, zoneAPITestValues(row)) } } return fdbResponse{rows: rows} case has("SELECT `id`") && has("WHERE `id`"): if f.foreign.ID == args[0] { return fdbResponse{rows: fdbRow(zoneAPITestValues(f.foreign)...)} } return fdbResponse{} case has("INSERT INTO `coredns_webui_audit`"): return fdbResponse{lastInsertID: 1, err: f.auditError} case has("INSERT INTO `coredns_records`"): f.lastID++ if f.hideInsert { return fdbResponse{lastInsertID: f.lastID} } f.rows = append(f.rows, recordRow{ ID: f.lastID, Zone: args[0].(string), Name: args[1].(string), TTL: sql.NullInt64{Int64: args[2].(int64), Valid: true}, Content: sql.NullString{String: args[3].(string), Valid: true}, RecordType: args[4].(string), }) return fdbResponse{lastInsertID: f.lastID, err: f.writeError} case has("UPDATE `coredns_records`"): if i := slices.IndexFunc(f.rows, func(row recordRow) bool { return row.ID == args[5] }); i >= 0 { f.rows[i] = recordRow{ ID: args[5].(int64), Zone: args[0].(string), Name: args[1].(string), RecordType: args[4].(string), TTL: sql.NullInt64{Int64: args[2].(int64), Valid: true}, Content: sql.NullString{String: args[3].(string), Valid: true}, } } return fdbResponse{rowsAffected: 1, err: f.writeError} case has("DELETE FROM `coredns_records`"): f.rows = slices.DeleteFunc(f.rows, func(row recordRow) bool { return row.ID == args[0] || has(zoneRowsWhere) && zoneAPITestKey(row.Zone) == args[0] }) return fdbResponse{rowsAffected: 1, err: f.writeError} case has("DELETE FROM"): return fdbResponse{rowsAffected: 1, err: f.writeError} default: f.t.Errorf("unexpected SQL: %s", query) return fdbResponse{err: errors.New("unexpected SQL")} } } func zoneAPITestKey(zone string) string { zone = strings.ToLower(zone) if !strings.HasSuffix(zone, ".") { zone += "." } return zone } func zoneAPITestingSQL(state *fdbState, contains string) []fdbCall { var result []fdbCall for _, call := range state.Calls() { if strings.Contains(call.query, contains) { result = append(result, call) } } return result } func TestZoneAPIReadHandlers(t *testing.T) { rows := zoneAPITestRows(t) broken := recordRow{ID: 5, Zone: zoneAPITestName, Name: "bad", RecordType: "A", Content: sql.NullString{String: "{", Valid: true}} f := zoneAPITestDBFor(t, append(rows, broken)) f.foreign = recordRow{ID: 90, Zone: "private.example.", RecordType: "unknown"} server, state := f.server() for _, tc := range []struct { operation string fragment string }{ {"zone_list", `"records":5`}, {"zone_read", `"mbox":"hostmaster.example.org."`}, {"record_list", `"data":null,"raw":"{"`}, {"zone_check", `"zone":"example.org.","id":5,"name":"bad","type":"A"`}, {"check_all", `"zone":"private.example.","id":null,"name":null,"type":null`}, {"zone_export", ""}, } { t.Run(tc.operation, func(t *testing.T) { c := zoneAPITestRequest(server, f.actor, tc.operation, zoneAPITestName, "", "", "") resp := zoneAPITestStatus(t, t.Context(), c, http.StatusOK) if !strings.Contains(zoneAPITestJSON(t, resp.Body), tc.fragment) { t.Fatalf("body = %s", zoneAPITestJSON(t, resp.Body)) } if tc.operation == "zone_read" && resp.Header.Get("ETag") != recordETag(rows[0]) { t.Fatalf("ETag = %q", resp.Header.Get("ETag")) } if tc.operation == "zone_export" && (resp.ContentType != "text/plain" || resp.Header.Get("Content-Disposition") != `attachment; filename="example.org.zone"` || !strings.HasPrefix(string(resp.Raw), "$ORIGIN example.org.\n") || !strings.Contains(string(resp.Raw), "; skipped id=5: ttl_null")) { t.Fatalf("response = %+v, file %s", resp, resp.Raw) } if c.auditDone || c.Entry.Before != nil || c.Entry.After != nil { t.Fatalf("read wrote change audit: %+v", c.Entry) } }) } if len(zoneAPITestingSQL(state, "INSERT INTO")) != 0 { t.Fatal("read wrote to the database") } user := userRow{ID: 17, Role: "user", Username: "alice"} for _, operation := range []string{"zone_list", "check_all"} { c := zoneAPITestRequest(server, user, operation, "", "", "", "") resp := zoneAPITestStatus(t, t.Context(), c, http.StatusOK) if encoded := zoneAPITestJSON(t, resp.Body); strings.Contains(encoded, "private.example.") || !strings.Contains(encoded, zoneAPITestName) { t.Fatalf("visibility: %s", encoded) } } f.delegated = false for _, operation := range []string{"zone_list", "check_all"} { c := zoneAPITestRequest(server, user, operation, "", "", "", "") resp := zoneAPITestStatus(t, t.Context(), c, http.StatusOK) if encoded := zoneAPITestJSON(t, resp.Body); !strings.HasSuffix(encoded, "[]}") { t.Fatalf("empty visibility: %s", encoded) } } for _, zone := range []string{"missing.example.", zoneAPITestName} { f.rows = nil c := zoneAPITestRequest(server, f.actor, "zone_read", zone, "", "", "") _, err := zoneAPITestCall(t.Context(), c) if e, ok := err.(*apiError); !ok || e.Status != 404 || e.Message != "zone not found" { t.Fatalf("absent zone: %v", err) } } } func TestZoneAPIWriteHandlers(t *testing.T) { rows := zoneAPITestRows(t) bulk := zoneAPITestJSON(t, map[string]any{"records": []map[string]any{ {"id": 3, "etag": recordETag(rows[2])}, {"id": 4, "etag": recordETag(rows[3])}, }}) for _, tc := range []struct { operation string id string etag string body string status int before, after []int64 recordID int64 serial bool }{ {"zone_create", "", "", zoneAPITestCreate, 201, []int64{}, []int64{1, 2, 3}, 0, false}, {"zone_delete", "", "", `{"confirm":"EXAMPLE.ORG"}`, 204, []int64{1, 2, 3, 4}, nil, 0, false}, {"record_create", "", "", zoneAPITestRecord, 201, []int64{1}, []int64{1, 5}, 5, true}, {"record_update", "3", recordETag(rows[2]), zoneAPITestRecord, 200, []int64{1, 3}, []int64{1, 3}, 3, true}, {"record_delete", "3", recordETag(rows[2]), "", 200, []int64{1, 3}, []int64{1}, 3, true}, {"record_bulk_delete", "", "", bulk, 200, []int64{1, 3, 4}, []int64{1}, 0, true}, {"soa_update", "", recordETag(rows[0]), strings.Replace(zoneAPITestSOA, "3600", "1500", 1), 200, []int64{1}, []int64{1}, 1, true}, } { t.Run(tc.operation, func(t *testing.T) { f := zoneAPITestDBFor(t, slices.Clone(rows)) f.stale = tc.operation == "zone_create" || tc.operation == "zone_delete" zone := zoneAPITestName if tc.operation == "zone_create" { f.rows, zone = nil, "" } server, state := f.server() c := zoneAPITestRequest(server, f.actor, tc.operation, zone, tc.id, tc.etag, tc.body) resp := zoneAPITestStatus(t, t.Context(), c, tc.status) audits := zoneAPITestingSQL(state, "INSERT INTO `coredns_webui_audit`") if len(audits) != 1 || state.commits != 1 || state.rollbacks != 0 || !c.auditDone || c.Entry.RecordID.Int64 != tc.recordID || c.Entry.RecordID.Valid != (tc.recordID != 0) || audits[0].args[5] != int64(tc.status) || audits[0].args[7] != zoneAPITestName { t.Fatalf("change audit = %+v, record ID %+v, commits %d, rollbacks %d", audits, c.Entry.RecordID, state.commits, state.rollbacks) } zoneAPITestAuditIDs(t, c.Entry.Before, tc.before) zoneAPITestAuditIDs(t, c.Entry.After, tc.after) if f.stale && (!strings.Contains(string(c.Entry.Before)+string(c.Entry.After), `{"zone":"example.org.","username":"bob"}`) || len(zoneAPITestingSQL(state, "DELETE FROM `coredns_webui_zone_delegations`")) != 1) { t.Fatal("delegation cleanup is missing") } if tc.serial { var serials []uint32 for _, update := range zoneAPITestingSQL(state, "UPDATE `coredns_records`") { if update.args[4] == "SOA" { row := recordRow{Content: sql.NullString{String: update.args[3].(string), Valid: true}} serial, _ := storedSOASerial(row) serials = append(serials, serial) } } if !slices.Equal(serials, []uint32{newSOASerial(modelNow) + 1}) { t.Fatalf("serials = %v", serials) } } if tc.status != 204 && tc.operation != "record_bulk_delete" && tc.operation != "record_delete" && resp.Header.Get("ETag") == "" { t.Fatal("missing response ETag") } if body := zoneAPITestJSON(t, resp.Body); tc.status != 204 && !strings.Contains(body, `"warnings":[`) { t.Fatalf("response without warnings: %s", body) } if f.stale && strings.Contains(string(c.Entry.After), `"username"`) { t.Fatalf("delegations in the after snapshot: %s", c.Entry.After) } calls := state.Queries() if !strings.Contains(calls[0], "GET_LOCK") || !strings.HasSuffix(calls[1], "LOCK IN SHARE MODE") || !strings.HasSuffix(calls[2], "FOR UPDATE") || !strings.Contains(calls[len(calls)-2], "INSERT INTO `coredns_webui_audit`") || !strings.Contains(calls[len(calls)-1], "RELEASE_LOCK") { t.Fatalf("write query order: %v", calls) } }) } } func zoneAPITestAuditIDs(t *testing.T, body []byte, want []int64) { t.Helper() if want == nil { if body != nil { t.Fatalf("audit = %s, want SQL NULL", body) } return } var objects []map[string]json.RawMessage if len(body) > 0 && body[0] == '{' { body = append(append([]byte{'['}, body...), ']') } if err := json.Unmarshal(body, &objects); err != nil { t.Fatalf("audit %s: %v", body, err) } var ids []int64 for _, object := range objects { id, record := object["id"] if !record { continue } var idValue int64 if err := json.Unmarshal(id, &idValue); err != nil { t.Fatal(err) } if _, ok := object["record_type"]; !ok || len(object) != 6 || object["ttl"] == nil || object["content"] == nil || object["zone"] == nil || object["name"] == nil { t.Fatalf("unexpected record audit fields: %v", object) } ids = append(ids, idValue) } if !slices.Equal(ids, want) { t.Fatalf("audit ids = %v, want %v; values %s", ids, want, body) } } func TestZoneAPIWriteRefusals(t *testing.T) { rows := zoneAPITestRows(t) padded := `{"content":"` + strings.Repeat("x", zoneFileMaxBytes) + `","mode":"merge"}` for _, tc := range []struct { operation string id string etag string body string status int field string setup func(*zoneAPITestDB, *apiContext) }{ {operation: "zone_create", status: 409, body: zoneAPITestCreate}, {operation: "zone_create", status: 403, body: zoneAPITestCreate, setup: func(_ *zoneAPITestDB, c *apiContext) { c.Principal.User.Role = "user" }}, {operation: "zone_delete", status: 403, body: `{"confirm":"example.org"}`, setup: func(_ *zoneAPITestDB, c *apiContext) { c.Principal.User.Role = "user" }}, {operation: "zone_create", status: 422, field: "name", body: `{"name":".."}`}, {operation: "zone_create", status: 422, field: "extra_ns", body: strings.Replace(zoneAPITestCreate, "backup.example.net", "ns.example.net.", 1), setup: func(f *zoneAPITestDB, _ *apiContext) { f.rows = nil }}, {operation: "zone_create", status: 422, field: "mbox", body: strings.Replace(zoneAPITestCreate, "hostmaster@example.org", "bad mailbox", 1), setup: func(f *zoneAPITestDB, _ *apiContext) { f.rows = nil }}, {operation: "zone_create", status: 422, field: "ttl", body: strings.Replace(zoneAPITestCreate, `"ttl":3600`, `"ttl":"3600"`, 1), setup: func(f *zoneAPITestDB, _ *apiContext) { f.rows = nil }}, {operation: "zone_delete", status: 422, field: "confirm", body: `{"confirm":"different.example"}`}, {operation: "zone_delete", status: 404, body: `{"confirm":"example.org"}`, setup: func(f *zoneAPITestDB, _ *apiContext) { f.rows = nil }}, {operation: "record_create", status: 422, field: "data.ip", body: `{"name":"new","type":"A","ttl":60,"data":{"ip":"::1"}}`}, {operation: "record_create", status: 422, field: "name", body: `{"name":"elsewhere.example.","type":"A","ttl":60,"data":{"ip":"192.0.2.1"}}`}, {operation: "record_create", status: 422, field: "type", body: `{"name":"new","type":"NONE","ttl":60,"data":{}}`}, {operation: "record_create", status: 422, field: "name", body: `{"name":"first","type":"A","ttl":61,"data":{"ip":"192.0.2.1"}}`}, {operation: "record_create", status: 422, field: "data.preference", body: `{"name":"new","type":"MX","ttl":60,"data":{"host":"mx.example","preference":"10"}}`}, {operation: "record_create", status: 422, field: "ttl", body: `{"name":"new","type":"A","ttl":"60","data":{"ip":"192.0.2.1"}}`}, {operation: "record_create", status: 400, body: `{"unknown":true}`}, {operation: "record_create", status: 400, body: zoneAPITestRecord + "{}"}, {operation: "record_create", status: 415, body: zoneAPITestRecord, setup: func(_ *zoneAPITestDB, c *apiContext) { c.Request.Header.Del("Content-Type") }}, {operation: "record_create", status: 413, body: `{"data":"` + strings.Repeat("x", 64<<10) + `"}`}, {operation: "record_create", status: 503, body: zoneAPITestRecord, setup: func(f *zoneAPITestDB, _ *apiContext) { f.locked = true }}, {operation: "record_create", status: 404, body: zoneAPITestRecord, setup: func(f *zoneAPITestDB, c *apiContext) { f.actor.Role, c.Principal.User.Role, f.delegated = "user", "user", false }}, {operation: "record_create", status: 404, body: zoneAPITestRecord, setup: func(f *zoneAPITestDB, _ *apiContext) { f.hasActor = false }}, {operation: "record_create", status: 404, body: zoneAPITestRecord, setup: func(f *zoneAPITestDB, _ *apiContext) { f.actor.DeletedAt = sql.NullTime{Time: modelNow, Valid: true} }}, {operation: "record_create", status: 404, body: zoneAPITestRecord, setup: func(f *zoneAPITestDB, _ *apiContext) { f.actor.Role = "user" }}, {operation: "record_update", id: "3", status: 428, body: zoneAPITestRecord}, {operation: "record_update", id: "3", status: 412, etag: `"old"`, body: zoneAPITestRecord}, {operation: "record_update", id: "99", status: 412, etag: `"old"`, body: zoneAPITestRecord}, {operation: "record_update", id: "wrong", status: 400, etag: `"old"`, body: zoneAPITestRecord}, {operation: "record_update", id: "4294967296", status: 400, etag: `"old"`, body: zoneAPITestRecord}, {operation: "record_update", id: "90", status: 404, etag: `"old"`, body: zoneAPITestRecord}, {operation: "record_delete", id: "3", status: 428}, {operation: "record_delete", id: "3", status: 412, etag: "*"}, {operation: "record_delete", id: "90", status: 404, etag: `"old"`}, {operation: "record_delete", id: "1", status: 422, field: "type", etag: recordETag(rows[0])}, {operation: "record_delete", id: "2", status: 422, field: "type", etag: recordETag(rows[1])}, {operation: "record_bulk_delete", status: 412, body: `{"records":[{"id":3,"etag":` + zoneAPITestJSON(t, recordETag(rows[2])) + `},{"id":4,"etag":"old"}]}`}, {operation: "record_bulk_delete", status: 422, field: "records", body: `{"records":[]}`}, {operation: "record_bulk_delete", status: 422, field: "records", body: `{"records":[{"id":"3","etag":"old"}]}`}, {operation: "record_bulk_delete", status: 422, field: "records", body: `{"records":[{"id":4294967296,"etag":"old"}]}`}, {operation: "record_bulk_delete", status: 404, body: `{"records":[{"id":90,"etag":"old"}]}`}, {operation: "soa_update", status: 428, body: zoneAPITestSOA}, {operation: "soa_update", status: 412, etag: `"old"`, body: zoneAPITestSOA}, {operation: "soa_update", status: 412, etag: recordETag(rows[0]), body: zoneAPITestSOA, setup: func(f *zoneAPITestDB, _ *apiContext) { f.rows = f.rows[1:] }}, {operation: "soa_update", status: 422, field: "refresh", etag: recordETag(rows[0]), body: strings.Replace(zoneAPITestSOA, `"refresh":3600`, `"refresh":"3600"`, 1)}, {operation: "soa_update", status: 422, field: "mbox", etag: recordETag(rows[0]), body: strings.Replace(zoneAPITestSOA, "hostmaster@example.org", "@example.org", 1)}, {operation: "zone_import_preview", status: 413, body: padded}, {operation: "zone_import", status: 413, body: padded}, {operation: "zone_import", status: 409, body: `{"mode":"merge","content":"","fingerprint":"stale"}`}, {operation: "zone_import_preview", status: 422, field: "mode", body: `{"mode":"invalid","content":""}`}, } { t.Run(tc.operation+"/"+strconv.Itoa(tc.status)+"/"+tc.field, func(t *testing.T) { f := zoneAPITestDBFor(t, slices.Clone(rows)) f.foreign = recordRow{ID: 90, Zone: "private.example.", RecordType: "TXT"} server, state := f.server() c := zoneAPITestRequest(server, f.actor, tc.operation, zoneAPITestName, tc.id, tc.etag, tc.body) if tc.setup != nil { tc.setup(f, c) } _, err := zoneAPITestCall(t.Context(), c) var apiErr *apiError if !errors.As(err, &apiErr) || apiErr.Status != tc.status || tc.field != "" && apiErr.Fields[tc.field] == "" { t.Fatalf("error = %#v, want status %d, field %q", err, tc.status, tc.field) } if tc.status == 503 && apiErr.Message != "zone busy" { t.Fatalf("busy error = %q", apiErr.Message) } if c.auditDone || c.Entry.Before != nil || c.Entry.After != nil || len(zoneAPITestingSQL(state, "INSERT INTO"))+len(zoneAPITestingSQL(state, "UPDATE `"))+len(zoneAPITestingSQL(state, "DELETE FROM")) != 0 { t.Fatalf("refusal wrote data: %+v, queries %v", c.Entry, state.Queries()) } }) } } func TestZoneAPIWarningsAndSerialModes(t *testing.T) { rows := zoneAPITestRows(t) var err error rows[0], err = withSOASerial(rows[0], 0, false) if err != nil { t.Fatal(err) } f := zoneAPITestDBFor(t, rows) f.actor.Role = "user" server, state := f.server() body := `{"name":"new","type":"MX","ttl":60,"data":{"host":"missing.example.org.","preference":10}}` c := zoneAPITestRequest(server, f.actor, "record_create", zoneAPITestName, "", "", body) resp := zoneAPITestStatus(t, t.Context(), c, 201) if !strings.Contains(zoneAPITestJSON(t, resp.Body), "target_no_address") || len(zoneAPITestingSQL(state, "UPDATE `coredns_records`")) != 0 || len(zoneAPITestingSQL(state, "zone_delegations` WHERE `zone` = CAST(? AS BINARY) AND `user_id` = ? LOCK IN SHARE MODE")) != 1 { t.Fatalf("response = %+v, SQL = %v", resp, state.Queries()) } c = zoneAPITestRequest(server, f.actor, "soa_update", zoneAPITestName, "", recordETag(rows[0]), zoneAPITestSOA) resp = zoneAPITestStatus(t, t.Context(), c, 200) if c.auditDone || c.Entry.Before != nil || c.Entry.After != nil || resp.Header.Get("ETag") != recordETag(rows[0]) || !strings.Contains(zoneAPITestJSON(t, resp.Body), `"serial":null`) { t.Fatalf("unexpected SOA no-op: %+v, %s", c.Entry, zoneAPITestJSON(t, resp.Body)) } c = zoneAPITestRequest(server, f.actor, "soa_update", zoneAPITestName, "", recordETag(rows[0]), `{"managed_serial":true,`+zoneAPITestSOA[1:]) resp = zoneAPITestStatus(t, t.Context(), c, 200) if !c.auditDone || !strings.Contains(zoneAPITestJSON(t, resp.Body), `"serial":`+strconv.FormatUint(uint64(newSOASerial(modelNow)), 10)) || len(zoneAPITestingSQL(state, "UPDATE `coredns_records`")) != 1 { t.Fatalf("SOA managed update: %+v, %s, SQL = %v", c.Entry, zoneAPITestJSON(t, resp.Body), state.Queries()) } } func TestZoneAPISOAFieldNames(t *testing.T) { for _, field := range []string{"ns", "mbox", "ttl", "refresh", "retry", "expire", "minttl"} { for _, operation := range []string{"zone_create", "soa_update"} { t.Run(operation+"/"+field, func(t *testing.T) { rows := zoneAPITestRows(t) f := zoneAPITestDBFor(t, rows) var body map[string]any input, zone, etag := zoneAPITestSOA, zoneAPITestName, recordETag(rows[0]) if operation == "zone_create" { f.rows, input, zone, etag = nil, zoneAPITestCreate, "", "" } if err := json.Unmarshal([]byte(input), &body); err != nil { t.Fatal(err) } body[field] = "invalid field" server, state := f.server() c := zoneAPITestRequest(server, f.actor, operation, zone, "", etag, zoneAPITestJSON(t, body)) _, err := zoneAPITestCall(t.Context(), c) var invalid *apiError if !errors.As(err, &invalid) || invalid.Status != 422 || len(invalid.Fields) != 1 || invalid.Fields[field] == "" { t.Fatalf("field %q: error %+v", field, err) } if c.auditDone || len(zoneAPITestingSQL(state, "INSERT INTO")) != 0 || len(zoneAPITestingSQL(state, "UPDATE `")) != 0 { t.Fatalf("invalid field wrote data: %v", state.Queries()) } }) } } } func TestZoneAPIRollback(t *testing.T) { for _, failAt := range []string{"write", "audit", "commit"} { t.Run(failAt, func(t *testing.T) { f := zoneAPITestDBFor(t, zoneAPITestRows(t)) failure := errors.New(failAt + " failed") server, state := f.server() switch failAt { case "write": f.writeError = failure case "audit": f.auditError = failure case "commit": state.commitErr = failure } c := zoneAPITestRequest(server, f.actor, "record_create", zoneAPITestName, "", "", zoneAPITestRecord) resp, err := zoneAPITestCall(t.Context(), c) if !errors.Is(err, failure) || resp.Status != 0 || c.auditDone || c.Entry.Before != nil || c.Entry.After != nil || state.commits != 0 || (failAt != "commit" && state.rollbacks != 1) || !strings.Contains(state.Queries()[len(state.Queries())-1], "RELEASE_LOCK") { t.Fatalf("response %+v, err %v, audit %+v, SQL %v", resp, err, c.Entry, state.Queries()) } }) } } func TestZoneAPIImport(t *testing.T) { rows := zoneAPITestRows(t) f := zoneAPITestDBFor(t, rows) server, state := f.server() content := "$ORIGIN example.org.\nfirst 180 A 192.0.2.1\nlast TXT \"one\" \"two\"\nother PTR ptr.example.net.\n" + "@ SOA ns.example.net. hostmaster.example.org. 99 3600 600 604800 600\n" + "@ 3600 NS ns.example.net.\n" makeBody := func(content string, apply bool) string { body := map[string]any{"mode": "replace", "content": content} if apply { body["fingerprint"] = zoneFingerprint(f.rows) } return zoneAPITestJSON(t, body) } c := zoneAPITestRequest(server, f.actor, "zone_import_preview", zoneAPITestName, "", "", makeBody(content, false)) resp := zoneAPITestStatus(t, t.Context(), c, 200) for _, fragment := range []string{`"fingerprint":"` + zoneFingerprint(rows), `"old_ttl":60`, `"name":"last","type":"TXT","ttl":3600,"value":"onetwo"`, `"minttl":600`, `"line":4,"text":`, `"line":3,"message":"TXT strings`} { if encoded := zoneAPITestJSON(t, resp.Body); !strings.Contains(encoded, fragment) { t.Fatalf("missing %q in %s", fragment, encoded) } } c = zoneAPITestRequest(server, f.actor, "zone_import", zoneAPITestName, "", "", makeBody(content, true)) resp = zoneAPITestStatus(t, t.Context(), c, 200) if zoneAPITestJSON(t, resp.Body) != `{"added":1,"deleted":1,"updated":2,"warnings":[{"line":3,"message":"TXT strings were joined and the plugin will re-split them at 255 bytes"}]}` { t.Fatalf("apply response = %s", zoneAPITestJSON(t, resp.Body)) } zoneAPITestAuditIDs(t, c.Entry.Before, []int64{1, 3, 4}) zoneAPITestAuditIDs(t, c.Entry.After, []int64{1, 3, 5}) updates := zoneAPITestingSQL(state, "UPDATE `coredns_records`") if len(updates) != 2 || updates[0].args[4] != "SOA" || !strings.Contains(updates[0].args[3].(string), strconv.FormatUint(uint64(newSOASerial(modelNow)+1), 10)) || len(zoneAPITestingSQL(state, "INSERT INTO `coredns_webui_audit`")) != 1 { t.Fatalf("incorrect import SQL: %v", state.Calls()) } for _, tc := range []struct { content string fragment string }{ {"\n; comment\nother.example. A 192.0.2.1\n", `"line":3,"message":"record has an owner outside the zone"`}, {"\n; comment\nwww A not-an-address\n", `"line":3,"message":`}, {"\n; comment\nwww AAAA ::ffff:192.0.2.1\n", `"line":3,"message":"ip:`}, {"$INCLUDE ignored\n", `"line":1,"message":`}, {"", "last apex NS"}, } { for _, operation := range []string{"zone_import_preview", "zone_import"} { c := zoneAPITestRequest(server, f.actor, operation, zoneAPITestName, "", "", makeBody(tc.content, operation == "zone_import")) _, err := zoneAPITestCall(t.Context(), c) var apiErr *apiError if !errors.As(err, &apiErr) || apiErr.Status != 422 || apiErr.Message != "the file has errors" || !strings.Contains(zoneAPITestJSON(t, apiErr.Extra["errors"]), tc.fragment) { t.Fatalf("%q yielded %#v, expected %q", tc.content, err, tc.fragment) } } } } func TestZoneAPIAbsence(t *testing.T) { for _, operation := range []string{ "zone_read", "zone_delete", "record_list", "record_create", "record_update", "record_delete", "record_bulk_delete", "soa_update", "zone_check", "zone_export", "zone_import_preview", "zone_import", } { t.Run(operation, func(t *testing.T) { f := zoneAPITestDBFor(t, nil) server, _ := f.server() c := zoneAPITestRequest(server, f.actor, operation, zoneAPITestName, "1", "", "") _, err := zoneAPITestCall(t.Context(), c) if e, ok := err.(*apiError); !ok || e.Status != 404 || e.Message != "zone not found" { t.Fatalf("absent zone: %v", err) } }) } } func TestZoneAPIUnreadableSOA(t *testing.T) { rows := zoneAPITestRows(t) rows[0].Content = sql.NullString{String: "{", Valid: true} f := zoneAPITestDBFor(t, rows) server, _ := f.server() c := zoneAPITestRequest(server, f.actor, "zone_read", zoneAPITestName, "", "", "") resp := zoneAPITestStatus(t, t.Context(), c, 200) if resp.Header.Get("ETag") != "" || !strings.Contains(zoneAPITestJSON(t, resp.Body), `"serial":null,"soa":null`) { t.Fatalf("broken SOA summary = %+v", resp) } c = zoneAPITestRequest(server, f.actor, "soa_update", zoneAPITestName, "", recordETag(rows[0]), zoneAPITestSOA) resp = zoneAPITestStatus(t, t.Context(), c, 200) if resp.Header.Get("ETag") == "" || resp.Header.Get("ETag") == recordETag(rows[0]) || !c.auditDone { t.Fatalf("SOA was not repaired: %+v", resp) } } func TestZoneAPIReadErrors(t *testing.T) { failure := errors.New("database read failed") db, _ := newFakeDB(t, func(string, []any) fdbResponse { return fdbResponse{err: failure} }) server := &WebServer{db: db, tables: fdbTables(t), log: discardLogger()} for _, operation := range []string{"zone_list", "zone_read", "record_list", "zone_check", "check_all", "zone_export", "zone_import_preview", "record_create"} { c := zoneAPITestRequest(server, userRow{ID: 17, Role: "admin"}, operation, zoneAPITestName, "", "", "") _, err := zoneAPITestCall(t.Context(), c) if !errors.Is(err, failure) { t.Errorf("%s = %v", operation, err) } } } func zoneAPITestSOARecord(name string) string { return `{"name":"` + name + `","type":"SOA","ttl":3600,"data":{"ns":"ns.example.net","MBox":"hostmaster.example.org","refresh":3600,"retry":600,"expire":604800,"minttl":300}}` } func zoneAPITestRepair(t *testing.T, f *zoneAPITestDB, operation, id, etag, body string, status int) apiResponse { t.Helper() server, _ := f.server() return zoneAPITestStatus(t, t.Context(), zoneAPITestRequest(server, f.actor, operation, zoneAPITestName, id, etag, body), status) } func zoneAPITestPreserved(t *testing.T, f *zoneAPITestDB, original []recordRow, ids ...int64) { t.Helper() byID := zoneAPIRowsByID(f.rows) for _, row := range original { if slices.Contains(ids, row.ID) && byID[row.ID] != row { t.Fatalf("record %d changed: %+v, want %+v", row.ID, byID[row.ID], row) } } } func zoneAPITestSerialOf(t *testing.T, row recordRow, want uint32) { t.Helper() if serial, _ := storedSOASerial(row); serial != want { t.Fatalf("serial of %d = %d, want %d", row.ID, serial, want) } } func TestZoneAPIRepairNonCanonicalZone(t *testing.T) { serial := newSOASerial(modelNow) for _, stored := range []string{"example.org", "EXAMPLE.ORG.", "Example.Org"} { t.Run(stored, func(t *testing.T) { rows := zoneAPITestRows(t) rows[3].Zone = stored f := zoneAPITestDBFor(t, rows) f.foreign = recordRow{ID: 90, Zone: "example.org.example.", Name: "x", RecordType: "A"} list := zoneAPITestJSON(t, zoneAPITestRepair(t, f, "record_list", "", "", "", 200).Body) if !strings.Contains(list, `"id":4,"name":"second"`) || strings.Contains(list, `"id":90`) { t.Fatalf("record list = %s", list) } check := zoneAPITestJSON(t, zoneAPITestRepair(t, f, "zone_check", "", "", "", 200).Body) code := "zone_case" if !strings.HasSuffix(stored, ".") { code = "zone_not_fqdn" } if !strings.Contains(check, `"code":"`+code+`","severity":"error"`) || !strings.Contains(check, `"id":4`) { t.Fatalf("check = %s", check) } body := `{"name":"second","type":"A","ttl":60,"data":{"ip":"192.0.2.1"}}` zoneAPITestRepair(t, f, "record_update", "4", recordETag(rows[3]), body, 200) if f.rows[3].Zone != zoneAPITestName || f.rows[3].Content != rows[3].Content || f.rows[3].Name != "second" { t.Fatalf("row was not repaired: %+v", f.rows[3]) } zoneAPITestPreserved(t, f, rows, 2, 3) zoneAPITestSerialOf(t, f.rows[0], serial+1) after := zoneAPITestJSON(t, zoneAPITestRepair(t, f, "zone_check", "", "", "", 200).Body) if after != `{"problems":[]}` { t.Fatalf("problems after the repair: %s", after) } }) } t.Run("every row", func(t *testing.T) { rows := zoneAPITestRows(t) for i := range rows { rows[i].Zone = "Example.ORG" } f := zoneAPITestDBFor(t, rows) summary := zoneAPITestRepair(t, f, "zone_read", "", "", "", 200) if body := zoneAPITestJSON(t, summary.Body); !strings.Contains(body, `"name":"example.org.","records":4`) { t.Fatalf("summary = %s", body) } zoneAPITestRepair(t, f, "record_delete", "4", recordETag(rows[3]), "", 200) if len(f.rows) != 3 || slices.ContainsFunc(f.rows, func(r recordRow) bool { return r.ID == 4 }) { t.Fatalf("rows after delete: %+v", f.rows) } zoneAPITestRepair(t, f, "zone_delete", "", "", `{"confirm":"example.org"}`, 204) if len(f.rows) != 0 { t.Fatalf("zone delete left %+v", f.rows) } }) } func TestZoneAPIRepairSOASet(t *testing.T) { serial := newSOASerial(modelNow) t.Run("non-apex SOA through soa_update", func(t *testing.T) { rows := zoneAPITestRows(t) rows[0].Name = "below" f := zoneAPITestDBFor(t, rows) summary := zoneAPITestJSON(t, zoneAPITestRepair(t, f, "zone_read", "", "", "", 200).Body) if !strings.Contains(summary, `"soa":null`) { t.Fatalf("summary = %s", summary) } resp := zoneAPITestRepair(t, f, "soa_update", "", recordETag(rows[0]), zoneAPITestSOA, 200) if f.rows[0].Name != "" || f.rows[0].ID != 1 || resp.Header.Get("ETag") != recordETag(f.rows[0]) || !strings.Contains(zoneAPITestJSON(t, resp.Body), `"soa":{"ns":"ns.example.net."`) { t.Fatalf("SOA not moved: %+v, %+v", f.rows[0], resp) } zoneAPITestSerialOf(t, f.rows[0], serial+1) zoneAPITestPreserved(t, f, rows, 2, 3, 4) }) t.Run("non-apex SOA through record_update", func(t *testing.T) { rows := zoneAPITestRows(t) rows[0].Name = "below" f := zoneAPITestDBFor(t, rows) zoneAPITestRepair(t, f, "record_update", "1", recordETag(rows[0]), zoneAPITestSOARecord("below"), 422) zoneAPITestRepair(t, f, "record_update", "1", recordETag(rows[0]), zoneAPITestSOARecord("@"), 200) if f.rows[0].Name != "" { t.Fatalf("SOA not moved: %+v", f.rows[0]) } zoneAPITestSerialOf(t, f.rows[0], serial+1) zoneAPITestPreserved(t, f, rows, 2, 3, 4) }) t.Run("duplicate apex SOA", func(t *testing.T) { rows := zoneAPITestRows(t) extra := rows[0] extra.ID = 5 extra.Content.String = strings.Replace(extra.Content.String, "ns.example.net.", "other.example.net.", 1) rows = append(rows, extra) f := zoneAPITestDBFor(t, rows) for _, tc := range []struct{ operation, id, etag, body string }{ {"record_create", "", "", zoneAPITestRecord}, {"record_delete", "3", recordETag(rows[2]), ""}, {"soa_update", "", recordETag(rows[0]), strings.Replace(zoneAPITestSOA, "3600", "1500", 1)}, {"record_bulk_delete", "", "", `{"records":[{"id":1,"etag":` + zoneAPITestJSON(t, recordETag(rows[0])) + `},{"id":5,"etag":` + zoneAPITestJSON(t, recordETag(extra)) + `}]}`}, } { server, _ := f.server() c := zoneAPITestRequest(server, f.actor, tc.operation, zoneAPITestName, tc.id, tc.etag, tc.body) if _, err := zoneAPITestCall(t.Context(), c); err == nil || err.(*apiError).Status != 422 { t.Fatalf("%s in a zone with two SOA records: %v", tc.operation, err) } } resp := zoneAPITestRepair(t, f, "record_delete", "5", recordETag(extra), "", 200) if len(f.rows) != 4 || zoneAPITestJSON(t, resp.Body) != `{"warnings":[]}` { t.Fatalf("duplicate SOA not deleted: %+v, %+v", f.rows, resp) } zoneAPITestSerialOf(t, f.rows[0], serial+1) zoneAPITestPreserved(t, f, rows, 2, 3, 4) zoneAPITestRepair(t, f, "record_delete", "1", recordETag(f.rows[0]), "", 422) }) t.Run("two non-apex SOA", func(t *testing.T) { rows := zoneAPITestRows(t) rows[0].Name = "one" extra := rows[0] extra.ID, extra.Name = 5, "two" rows = append(rows, extra) f := zoneAPITestDBFor(t, rows) zoneAPITestRepair(t, f, "record_delete", "5", recordETag(extra), "", 200) zoneAPITestSerialOf(t, f.rows[0], serial+1) zoneAPITestRepair(t, f, "record_delete", "1", recordETag(f.rows[0]), "", 422) zoneAPITestRepair(t, f, "soa_update", "", recordETag(f.rows[0]), zoneAPITestSOA, 200) if f.rows[0].Name != "" || len(f.rows) != 4 { t.Fatalf("SOA set not repaired: %+v", f.rows) } zoneAPITestSerialOf(t, f.rows[0], serial+2) zoneAPITestPreserved(t, f, rows, 2, 3, 4) }) t.Run("apex and non-apex SOA selected by ETag", func(t *testing.T) { rows := zoneAPITestRows(t) extra := rows[0] extra.ID, extra.Name = 5, "below" rows = append(rows, extra) f := zoneAPITestDBFor(t, rows) server, _ := f.server() body := strings.NewReplacer(`"ttl":3600`, `"ttl":1200`, "ns.example.net", "other.example.net").Replace(zoneAPITestSOA) c := zoneAPITestRequest(server, f.actor, "soa_update", zoneAPITestName, "", recordETag(extra), body) resp := zoneAPITestStatus(t, t.Context(), c, 200) if c.Entry.RecordID.Int64 != 5 || f.rows[4].Name != "" || f.rows[4].TTL.Int64 != 1200 || f.rows[0] != rows[0] { t.Fatalf("selected SOA not updated: %+v, %+v", f.rows, resp) } zoneAPITestSerialOf(t, f.rows[4], serial) zoneAPITestRepair(t, f, "record_delete", "1", recordETag(rows[0]), "", 200) zoneAPITestSerialOf(t, f.rows[3], serial+1) zoneAPITestPreserved(t, f, rows, 2, 3, 4) }) }