// SPDX-License-Identifier: GPL-2.0-or-later // Copyright (C) 2026 Bryan Joshua Pedini package main import ( "database/sql" "encoding/json" "fmt" "net/http" "slices" "strconv" "strings" "testing" "time" ) type matrixCase struct { name string tag string op string method string path string persona string body string ctype string header map[string]string ifMatch int64 setup func(env *matrixEnv) status int msg string noAudit bool zone string record int64 target int64 before string after string resp string check func(t *testing.T, env *matrixEnv, res webResult) } func (c matrixCase) label() string { return fmt.Sprintf("%s/%d/%s", c.op, c.status, c.name) } func matrixRoutePath(r apiRoute, zone, id, username string) string { return strings.NewReplacer("{zone}", zone, "{id}", id, "{username}", username).Replace(r.Path) } func matrixPadded(limit int64) string { return `{"x":"` + strings.Repeat("a", int(limit)-7) + `"}` } func matrixGenericCases() []matrixCase { var out []matrixCase for _, r := range apiRoutes { path := matrixRoutePath(r, mxZone, "3", "dave") zone := "" if routeHasZone(r.Path) { zone = mxZone } base := matrixCase{op: r.Operation, method: r.Method, path: path, persona: "admin", zone: zone} add := func(c matrixCase) { out = append(out, c) } c := base c.name, c.persona, c.status, c.msg, c.noAudit = "no session", "", 401, msgAuthRequired, true add(c) c = base c.name, c.persona, c.status, c.msg, c.noAudit = "deleted user session", "gone", 401, msgAuthRequired, true add(c) c = base c.name, c.tag, c.status, c.msg, c.noAudit = "session lookup failure", "session lookup", 503, msgDatabaseDown, true c.setup = func(env *matrixEnv) { env.h.store.failOn["SessionByTokenHash"] = errDatabase } add(c) if r.Method != http.MethodGet { c = base c.name, c.status, c.msg, c.noAudit, c.body = "cross-origin", 403, msgCrossOrigin, true, "{}" c.header = map[string]string{"Sec-Fetch-Site": "cross-site"} add(c) } c = base c.name, c.status, c.msg, c.body = "oversized body", 413, "request body too large", matrixPadded(r.BodyLimit+1) add(c) c = base c.name, c.status, c.msg, c.body, c.ctype = "wrong content type", 415, "content type must be application/json", "{}", "text/plain" add(c) c = base c.name, c.tag, c.status, c.msg, c.body = "invalid UTF-8 body", "utf8", 400, "request body must be valid UTF-8", "{\"a\":\"\xff\"}" add(c) c = base c.name, c.tag, c.status, c.msg, c.body, c.ctype = "audit insert failure", "audit", 500, msgInternalError, "{}", "text/plain" c.setup = func(env *matrixEnv) { env.h.store.failTimes["InsertAudit"] = 1 env.h.store.failOn["InsertAudit"] = errMatrixInternal } add(c) if r.Access == accessAdmin { c = base c.name, c.persona, c.status, c.msg = "admin route as user", "alice", 403, msgAdminRequired if strings.Contains(r.Path, "{username}") { c.target = mxUserID("dave") } add(c) } if routeHasZone(r.Path) { c = base c.name, c.tag, c.path, c.status, c.msg, c.zone = "invalid zone name", "invalid zone", matrixRoutePath(r, "bad..zone", "3", "dave"), 404, msgZoneNotFound, "" add(c) } if r.Access == accessZone { c = base c.name, c.tag, c.persona, c.status, c.msg = "zone not delegated", "not delegated", "dave", 404, msgZoneNotFound add(c) c = base c.name, c.tag, c.persona, c.status, c.msg = "delegation lookup failure", "delegation lookup", "alice", 503, msgDatabaseDown c.setup = func(env *matrixEnv) { env.h.store.failOn["HasDelegation"] = errDatabase } add(c) c = base c.name, c.tag, c.persona, c.status, c.msg, c.zone = "stale delegation", "stale", "alice", 404, msgZoneNotFound, mxStale c.path = matrixRoutePath(r, mxStale, "3", "dave") if strings.Contains(r.Path, "{id}") { c.record = 3 } add(c) c = base c.name, c.tag, c.status, c.msg, c.zone = "missing zone", "missing", 404, msgZoneNotFound, mxMissing c.path = matrixRoutePath(r, mxMissing, "3", "dave") if strings.Contains(r.Path, "{id}") { c.record = 3 } add(c) } } for _, c := range []matrixCase{ {name: "unknown path", path: "/nothing", method: "GET", status: 404, msg: msgNotFound}, {name: "unknown path below a zone", path: "/zones/example.org./nothing", method: "GET", status: 404, msg: msgNotFound}, {name: "wrong method", path: "/account", method: "PATCH", status: 405, msg: msgMethodNotAllowed, check: matrixHeader("Allow", "GET")}, {name: "wrong method on a zone route", path: "/zones/example.org./records/1", method: "POST", body: "{}", status: 405, msg: msgMethodNotAllowed, check: matrixHeader("Allow", "DELETE, PUT")}, {name: "unknown path without session", path: "/nothing", method: "GET", persona: "", status: 401, msg: msgAuthRequired, noAudit: true}, {name: "wrong method without session", path: "/account", method: "PATCH", persona: "", status: 401, msg: msgAuthRequired, noAudit: true}, {name: "unknown path cross-origin", path: "/nothing", method: "POST", body: "{}", header: map[string]string{"Sec-Fetch-Site": "cross-site"}, status: 403, msg: msgCrossOrigin, noAudit: true}, {name: "unknown path audit failure", path: "/nothing", method: "GET", status: 500, msg: msgInternalError, setup: func(env *matrixEnv) { env.h.store.failTimes["InsertAudit"] = 1 env.h.store.failOn["InsertAudit"] = errMatrixInternal }}, {name: "unknown path as user", path: "/nothing", method: "GET", persona: "alice", status: 404, msg: msgNotFound}, } { c.op = opAPIUnknown if c.persona == "" && !c.noAudit { c.persona = "admin" } out = append(out, c) } return out } func matrixHeader(name, value string) func(t *testing.T, env *matrixEnv, res webResult) { return func(t *testing.T, env *matrixEnv, res webResult) { t.Helper() if got := res.header.Get(name); got != value { t.Fatalf("header %s = %q, want %q", name, got, value) } } } func matrixCases() []matrixCase { cases := matrixGenericCases() cases = append(cases, matrixAccountCases()...) cases = append(cases, matrixZoneCases()...) cases = append(cases, matrixRecordCases()...) cases = append(cases, matrixFileCases()...) cases = append(cases, matrixDelegationCases()...) cases = append(cases, matrixUserCases()...) return cases } func matrixRequiredOutcomes(r apiRoute) []string { need := []string{"401", "403 cross-origin", "413", "415", "400 utf8", "500 audit", "503 session lookup", "500", "503"} if r.Method == http.MethodGet { need = slices.DeleteFunc(need, func(s string) bool { return s == "403 cross-origin" }) } if r.Access == accessAdmin { need = append(need, "403") } if routeHasZone(r.Path) { need = append(need, "404 invalid zone") } if r.Access == accessZone { need = append(need, "404 not delegated", "404 stale", "404 missing", "503 delegation lookup") } return append(need, matrixSpecificOutcomes[r.Operation]...) } var matrixSpecificOutcomes = map[string][]string{ opAccountRead: {"200", "500", "503"}, opPasswordChange: {"204", "401 in handler", "409", "422", "400", "500", "503"}, opZoneList: {"200", "500", "503"}, opZoneCreate: {"201", "409", "422", "400", "500", "503"}, opZoneRead: {"200", "500", "503"}, opZoneDelete: {"204", "404 missing", "404 stale", "422", "400", "500", "503"}, opRecordList: {"200", "500", "503"}, opRecordCreate: {"201", "422", "400", "500", "503"}, opRecordUpdate: {"200", "404 record", "412", "422", "428", "400", "500", "503"}, opRecordDelete: {"200", "404 record", "412", "422", "428", "400", "500", "503"}, opRecordBulkDelete: {"200", "404 record", "412", "422", "400", "500", "503"}, opSOAUpdate: {"200", "412", "422", "428", "400", "500", "503"}, opZoneCheck: {"200", "500", "503"}, opCheckAll: {"200", "500", "503"}, opZoneExport: {"200", "500", "503"}, opZoneImportPreview: {"200", "422", "400", "500", "503"}, opZoneImport: {"200", "409", "422", "400", "500", "503"}, opDelegationList: {"200", "404 missing", "404 stale", "500", "503"}, opDelegationGrant: {"204", "404 missing", "404 stale", "404 user", "422", "500", "503"}, opDelegationRevoke: {"204", "404 delegation", "404 user", "500", "503"}, opUserList: {"200", "400", "500", "503"}, opUserCreate: {"201", "409", "422", "400", "500", "503"}, opUserRead: {"200", "404 user", "500", "503"}, opUserRole: {"204", "404 user", "422", "400", "500", "503"}, opUserPassword: {"204", "404 user", "422", "400", "500", "503"}, opUserDelete: {"204", "404 user", "422", "400", "500", "503"}, opAuditRead: {"200", "400", "500", "503"}, } func matrixOutcome(c matrixCase) string { switch { case c.status == 403 && c.msg == msgCrossOrigin: return "403 cross-origin" case c.tag != "": return strconv.Itoa(c.status) + " " + c.tag } return strconv.Itoa(c.status) } func TestAPIAuditMatrixCoversEveryRoute(t *testing.T) { covered := map[string]map[string]bool{} for _, c := range matrixCases() { if covered[c.op] == nil { covered[c.op] = map[string]bool{} } covered[c.op][matrixOutcome(c)] = true } if len(matrixSpecificOutcomes) != len(apiRoutes) { t.Errorf("specific outcomes list %d operations, the route table %d", len(matrixSpecificOutcomes), len(apiRoutes)) } for _, r := range apiRoutes { if _, ok := matrixSpecificOutcomes[r.Operation]; !ok { t.Errorf("route %s %s (%s) is missing from the matrix", r.Method, r.Path, r.Operation) } for _, need := range matrixRequiredOutcomes(r) { if !covered[r.Operation][need] { t.Errorf("route %s %s (%s) has no %q case", r.Method, r.Path, r.Operation, need) } } } for _, need := range []string{"401", "403 cross-origin", "404", "405", "500"} { if !covered[opAPIUnknown][need] { t.Errorf("unknown API requests have no %q case", need) } } for op := range covered { if op != opAPIUnknown && !slices.ContainsFunc(apiRoutes, func(r apiRoute) bool { return r.Operation == op }) { t.Errorf("matrix case for unknown operation %s", op) } } } func TestAPIAuditMatrix(t *testing.T) { seen := map[string]bool{} for _, c := range matrixCases() { if seen[c.label()] { t.Errorf("duplicate case %s", c.label()) } seen[c.label()] = true t.Run(c.label(), func(t *testing.T) { runMatrixCase(t, c) }) } } func runMatrixCase(t *testing.T, c matrixCase) { env := newMatrixEnv(t) if c.setup != nil { c.setup(env) } req := webRequest{method: c.method, path: apiPrefix + c.path, token: env.tokens[c.persona], body: c.body, ctype: c.ctype, header: map[string]string{}} for k, v := range c.header { req.header[k] = v } if c.ifMatch != 0 { req.header["If-Match"] = recordETag(matrixSeed(c.ifMatch)) } res := env.h.do(req) if len(env.sql.unknown) != 0 { t.Fatalf("unexpected SQL: %q", env.sql.unknown) } if res.status != c.status { t.Fatalf("status %d, want %d, body %s", res.status, c.status, res.body) } if c.status >= 400 && c.method != http.MethodHead { var body map[string]any if err := json.Unmarshal([]byte(res.body), &body); err != nil || body["error"] != c.msg { t.Fatalf("body %s, want error %q", res.body, c.msg) } } if c.resp != "" && res.body != c.resp { t.Fatalf("body %s\nwant %s", res.body, c.resp) } if c.check != nil { c.check(t, env, res) } if c.noAudit { if len(res.audit) != 0 { t.Fatalf("%d audit rows, want none: %+v", len(res.audit), res.audit) } return } if len(res.audit) != 1 { t.Fatalf("%d audit rows, want exactly one: %+v", len(res.audit), res.audit) } row := res.audit[0] e := row.entry u := env.users[c.persona] got := matrixAuditText(e) want := matrixAuditText(auditEntry{ Time: webNow, UserID: matrixInt(u.ID), Actor: u.Username, Origin: mxOrigin, Operation: c.op, Status: matrixInt(int64(c.status)), Error: matrixText(c.msg, c.status >= 400), Zone: matrixText(c.zone, c.zone != ""), RecordID: matrixInt(c.record), TargetUserID: matrixInt(c.target), Before: matrixJSONBytes(c.before), After: matrixJSONBytes(c.after), }) if got != want { t.Fatalf("audit row\n got %s\nwant %s", got, want) } if e.Time.Location() != time.UTC { t.Fatalf("audit time %v is not UTC", e.Time) } if change := c.before != "" || c.after != ""; row.inTx != change { t.Fatalf("audit row written in a transaction: %t, want %t", row.inTx, change) } } func matrixInt(v int64) sql.NullInt64 { return sql.NullInt64{Int64: v, Valid: v != 0} } func matrixText(s string, valid bool) sql.NullString { return sql.NullString{String: s, Valid: valid} } func matrixJSONBytes(s string) []byte { if s == "" { return nil } return []byte(s) } func matrixAuditText(e auditEntry) string { nullInt := func(v sql.NullInt64) string { if !v.Valid { return "NULL" } return strconv.FormatInt(v.Int64, 10) } nullText := func(v sql.NullString) string { if !v.Valid { return "NULL" } return strconv.Quote(v.String) } nullJSON := func(b []byte) string { if b == nil { return "NULL" } return string(b) } return fmt.Sprintf("time=%s user_id=%s actor=%q origin=%q operation=%q status=%s error=%s zone=%s record_id=%s target_user_id=%s\n before=%s\n after=%s", e.Time.Format(time.RFC3339Nano), nullInt(e.UserID), e.Actor, e.Origin, e.Operation, nullInt(e.Status), nullText(e.Error), nullText(e.Zone), nullInt(e.RecordID), nullInt(e.TargetUserID), nullJSON(e.Before), nullJSON(e.After)) }