diff --git a/apimatrix_backend_test.go b/apimatrix_backend_test.go new file mode 100644 index 0000000..14bce4d --- /dev/null +++ b/apimatrix_backend_test.go @@ -0,0 +1,322 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright (C) 2026 Bryan Joshua Pedini + +package main + +import ( + "database/sql" + "database/sql/driver" + "errors" + "maps" + "slices" + "strings" + "sync" + "testing" + "time" +) + +type matrixFault struct { + match []string + err error + result *fdbResponse + times int +} + +type matrixWorld struct { + state fakeWebState + records []recordRow + nextID int64 +} + +type matrixSQL struct { + t *testing.T + store *fakeWebStore + mu sync.Mutex + records []recordRow + nextID int64 + working *matrixWorld + fdb *fdbState + faults []*matrixFault + unknown []string +} + +func newMatrixSQL(t *testing.T, store *fakeWebStore) *matrixSQL { + return &matrixSQL{t: t, store: store} +} + +func (m *matrixSQL) open(t *testing.T) *sql.DB { + db, state := newFakeDB(t, m.query) + m.fdb = state + state.onBegin = m.begin + state.onCommit = m.commit + state.onEnd = m.end + return db +} + +func (m *matrixSQL) fail(err error, times int, match ...string) { + m.mu.Lock() + defer m.mu.Unlock() + m.faults = append(m.faults, &matrixFault{match: match, err: err, times: times}) +} + +func (m *matrixSQL) answer(result fdbResponse, match ...string) { + m.mu.Lock() + defer m.mu.Unlock() + m.faults = append(m.faults, &matrixFault{match: match, result: &result, times: -1}) +} + +func (m *matrixSQL) addRecord(r recordRow) recordRow { + m.mu.Lock() + defer m.mu.Unlock() + if r.ID == 0 { + m.nextID++ + r.ID = m.nextID + } + m.nextID = max(m.nextID, r.ID) + m.records = append(m.records, r) + m.store.mu.Lock() + defer m.store.mu.Unlock() + matrixSyncZones(&m.store.state, m.records) + return r +} + +func (m *matrixSQL) rows() []recordRow { + m.mu.Lock() + defer m.mu.Unlock() + return slices.Clone(m.records) +} + +func (m *matrixSQL) begin() { + m.mu.Lock() + defer m.mu.Unlock() + m.store.mu.Lock() + defer m.store.mu.Unlock() + m.working = &matrixWorld{state: m.store.state.clone(), records: slices.Clone(m.records), nextID: m.nextID} +} + +func (m *matrixSQL) commit() error { + m.mu.Lock() + defer m.mu.Unlock() + if m.working == nil { + return errors.New("commit without transaction") + } + m.store.mu.Lock() + defer m.store.mu.Unlock() + m.records, m.nextID = m.working.records, m.working.nextID + m.store.state = m.working.state + matrixSyncZones(&m.store.state, m.records) + m.store.commits++ + return nil +} + +func (m *matrixSQL) end() { + m.mu.Lock() + defer m.mu.Unlock() + m.working = nil +} + +func matrixSyncZones(state *fakeWebState, records []recordRow) { + state.zones = map[string]bool{} + for _, r := range records { + state.zones[zoneAPITestKey(r.Zone)] = true + } +} + +func matrixMatches(query string, parts []string) bool { + for _, p := range parts { + if !strings.Contains(query, p) { + return false + } + } + return true +} + +func (m *matrixSQL) query(query string, args []any) fdbResponse { + m.mu.Lock() + defer m.mu.Unlock() + for _, f := range m.faults { + if f.times != 0 && matrixMatches(query, f.match) { + if f.times > 0 { + f.times-- + } + if f.result != nil { + return *f.result + } + return fdbResponse{err: f.err} + } + } + m.store.mu.Lock() + defer m.store.mu.Unlock() + w := m.working + if w == nil { + w = &matrixWorld{state: m.store.state, records: m.records, nextID: m.nextID} + defer func() { + if m.working == nil { + m.records, m.nextID = w.records, w.nextID + m.store.state = w.state + } + }() + } + return m.exec(w, query, args) +} + +func (m *matrixSQL) userValues(u userRow) []driver.Value { + var lastLogin, deleted driver.Value + if u.LastLoginAt.Valid { + lastLogin = u.LastLoginAt.Time + } + if u.DeletedAt.Valid { + deleted = u.DeletedAt.Time + } + return []driver.Value{u.ID, u.Username, u.Role, u.PasswordHash, u.CreatedAt, u.UpdatedAt, lastLogin, deleted} +} + +func (m *matrixSQL) exec(w *matrixWorld, query string, args []any) fdbResponse { + has := func(v string) bool { return strings.Contains(query, v) } + switch { + case has("GET_LOCK"), has("RELEASE_LOCK"): + return fdbResponse{rows: fdbRow(int64(1))} + case has("FROM `coredns_webui_users` u WHERE u.`id` = ?"): + id := args[0].(int64) + for _, u := range w.state.users { + if u.ID == id { + return fdbResponse{rows: fdbRow(m.userValues(u)...)} + } + } + return fdbResponse{} + case has("SELECT 1 FROM `coredns_webui_zone_delegations` WHERE `zone` = ? AND `user_id` = ?"): + if _, ok := w.state.delegations[delegationKey{args[0].(string), args[1].(int64)}]; ok { + return fdbResponse{rows: fdbRow(int64(1))} + } + return fdbResponse{} + case has("GROUP BY `zone_key`"): + return m.zoneSummaries(w, has("d.`user_id` = ?"), args) + case has("SELECT `id`") && has(zoneRowsWhere): + var rows [][]driver.Value + for _, r := range w.records { + if zoneAPITestKey(r.Zone) == args[0] { + rows = append(rows, zoneAPITestValues(r)) + } + } + return fdbResponse{rows: rows} + case has("SELECT `id`") && has("WHERE `id` = ?"): + for _, r := range w.records { + if r.ID == args[0] { + return fdbResponse{rows: fdbRow(zoneAPITestValues(r)...)} + } + } + return fdbResponse{} + case has("FOR UPDATE OF d"): + var out []delegationRow + for k, d := range w.state.delegations { + if k.zone == args[0] { + d.Username = w.state.users[k.userID-1].Username + out = append(out, d) + } + } + slices.SortFunc(out, func(a, b delegationRow) int { return strings.Compare(a.Username, b.Username) }) + var rows [][]driver.Value + for _, d := range out { + rows = append(rows, []driver.Value{d.Zone, d.UserID, d.Username, d.CreatedAt, d.CreatedBy}) + } + return fdbResponse{rows: rows} + case has("DELETE FROM `coredns_webui_zone_delegations` WHERE `zone` = ?"): + var n int64 + for k := range w.state.delegations { + if k.zone == args[0] { + delete(w.state.delegations, k) + n++ + } + } + return fdbResponse{rowsAffected: n} + case has("INSERT INTO `coredns_records`"): + w.nextID++ + w.records = append(w.records, recordRow{ + ID: w.nextID, Zone: args[0].(string), Name: args[1].(string), TTL: matrixNullInt(args[2]), + Content: matrixNullString(args[3]), RecordType: args[4].(string), + }) + return fdbResponse{lastInsertID: w.nextID, rowsAffected: 1} + case has("UPDATE `coredns_records`"): + i := slices.IndexFunc(w.records, func(r recordRow) bool { return r.ID == args[5] }) + if i < 0 { + return fdbResponse{} + } + w.records[i] = recordRow{ + ID: args[5].(int64), Zone: args[0].(string), Name: args[1].(string), TTL: matrixNullInt(args[2]), + Content: matrixNullString(args[3]), RecordType: args[4].(string), + } + return fdbResponse{rowsAffected: 1} + case has("DELETE FROM `coredns_records` WHERE `id` = ?"): + n := len(w.records) + w.records = slices.DeleteFunc(w.records, func(r recordRow) bool { return r.ID == args[0] }) + return fdbResponse{rowsAffected: int64(n - len(w.records))} + case has("DELETE FROM `coredns_records`" + zoneRowsWhere): + n := len(w.records) + w.records = slices.DeleteFunc(w.records, func(r recordRow) bool { return zoneAPITestKey(r.Zone) == args[0] }) + return fdbResponse{rowsAffected: int64(n - len(w.records))} + case has("INSERT INTO `coredns_webui_audit`"): + e := auditEntry{ + Time: args[0].(time.Time), UserID: matrixNullInt(args[1]), Actor: args[2].(string), Origin: args[3].(string), + Operation: args[4].(string), Status: matrixNullInt(args[5]), Error: matrixNullString(args[6]), + Zone: matrixNullString(args[7]), RecordID: matrixNullInt(args[8]), TargetUserID: matrixNullInt(args[9]), + Before: matrixBytes(args[10]), After: matrixBytes(args[11]), + } + e.ID = int64(len(w.state.audit) + 1) + w.state.audit = append(w.state.audit, fakeAuditInsert{entry: e, inTx: m.working != nil}) + return fdbResponse{lastInsertID: e.ID, rowsAffected: 1} + } + m.unknown = append(m.unknown, query) + return fdbResponse{err: errors.New("matrix backend: unexpected SQL")} +} + +func (m *matrixSQL) zoneSummaries(w *matrixWorld, ofUser bool, args []any) fdbResponse { + counts := map[string]int64{} + soa := map[string]recordRow{} + for _, r := range w.records { + key := zoneAPITestKey(r.Zone) + if ofUser { + if _, ok := w.state.delegations[delegationKey{key, args[0].(int64)}]; !ok { + continue + } + } + counts[key]++ + if r.RecordType == "SOA" { + if cur, ok := soa[key]; !ok || (cur.Name != "" && r.Name == "") { + soa[key] = r + } + } + } + var rows [][]driver.Value + for _, key := range slices.Sorted(maps.Keys(counts)) { + var content driver.Value + if r, ok := soa[key]; ok && r.Content.Valid { + content = r.Content.String + } + rows = append(rows, []driver.Value{key, counts[key], content}) + } + return fdbResponse{rows: rows} +} + +func matrixNullInt(v any) sql.NullInt64 { + if n, ok := v.(int64); ok { + return sql.NullInt64{Int64: n, Valid: true} + } + return sql.NullInt64{} +} + +func matrixNullString(v any) sql.NullString { + if s, ok := v.(string); ok { + return sql.NullString{String: s, Valid: true} + } + return sql.NullString{} +} + +func matrixBytes(v any) []byte { + switch x := v.(type) { + case string: + return []byte(x) + case []byte: + return x + } + return nil +} diff --git a/apimatrix_cases_test.go b/apimatrix_cases_test.go new file mode 100644 index 0000000..ad261c9 --- /dev/null +++ b/apimatrix_cases_test.go @@ -0,0 +1,622 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright (C) 2026 Bryan Joshua Pedini + +package main + +import ( + "errors" + "strconv" + "strings" + "testing" +) + +func mxSQLFail(err error, match ...string) func(*matrixEnv) { + return func(env *matrixEnv) { env.sql.fail(err, -1, match...) } +} + +func mxStoreFail(method string, err error) func(*matrixEnv) { + return func(env *matrixEnv) { env.h.store.failOn[method] = err } +} + +func mxBusy(env *matrixEnv) { + env.sql.answer(fdbResponse{rows: fdbRow(int64(0))}, "GET_LOCK") +} + +func mxCommitFails(env *matrixEnv) { + env.sql.fdb.commitErr = errMatrixInternal +} + +func mxUnchanged(t *testing.T, env *matrixEnv, _ webResult) { + t.Helper() + if got, want := env.sql.rows(), matrixSeedRecords(); len(got) != len(want) { + t.Fatalf("records changed: %d rows", len(got)) + } else { + for i := range got { + if got[i] != want[i] { + t.Fatalf("record %d changed: %+v", want[i].ID, got[i]) + } + } + } +} + +const ( + mxRecordBody = `{"name":"new","type":"A","ttl":60,"data":{"ip":"192.0.2.10"}}` + mxUpdateBody = `{"name":"www","type":"A","ttl":300,"data":{"ip":"192.0.2.9"}}` + mxSOABody = `{"ns":"ns.example.net","mbox":"hostmaster@example.org","ttl":3600,"refresh":3600,"retry":700,"expire":604800,"minttl":300}` + mxCreateStale = `{"name":"Stale.ORG","ns":"ns.example.net","mbox":"hostmaster@stale.org","extra_ns":["backup.example.net"],"refresh":3600,"retry":600,"expire":604800,"minttl":300,"ttl":3600}` + mxCreateNew = `{"name":"new.org","ns":"ns.example.net","mbox":"hostmaster@new.org","refresh":3600,"retry":600,"expire":604800,"minttl":300,"ttl":3600}` +) + +func mxNewRecord(id int64) string { + return `{"id":` + itoa(id) + `,"zone":"example.org.","name":"new","ttl":60,"record_type":"A","content":"{\"ip\":\"192.0.2.10\"}"}` +} + +func itoa(n int64) string { + return strconv.FormatInt(n, 10) +} + +func mxBulk(ids ...int64) string { + var items []string + for _, id := range ids { + items = append(items, `{"id":`+itoa(id)+`,"etag":`+mxJSON(recordETag(matrixSeed(id)))+`}`) + } + return `{"records":[` + strings.Join(items, ",") + `]}` +} + +func matrixAccountCases() []matrixCase { + alice := mxUserID("alice") + pw := `{"current":"` + testPassword + `","password":"brand-new-password"}` + return []matrixCase{ + {name: "admin", op: opAccountRead, method: "GET", path: "/account", persona: "admin", status: 200, + resp: `{"username":"admin","role":"admin","zones":[]}`}, + {name: "user without stale zones", op: opAccountRead, method: "GET", path: "/account", persona: "alice", status: 200, + resp: `{"username":"alice","role":"user","zones":["example.org."]}`}, + {name: "zones failure", op: opAccountRead, method: "GET", path: "/account", persona: "alice", status: 500, msg: msgInternalError, + setup: mxStoreFail("UserZones", errMatrixInternal)}, + {name: "zones unavailable", op: opAccountRead, method: "GET", path: "/account", persona: "alice", status: 503, msg: msgDatabaseDown, + setup: mxStoreFail("UserZones", errDatabase)}, + + {name: "changed", op: opPasswordChange, method: "PUT", path: "/account/password", persona: "alice", body: pw, status: 204, + target: alice, before: mxSeedUser("alice"), after: mxSeedUser("alice"), + check: func(t *testing.T, env *matrixEnv, _ webResult) { + if env.h.store.user(alice).PasswordHash != fakeHash("brand-new-password") { + t.Fatal("password not changed") + } + }}, + {name: "malformed", op: opPasswordChange, method: "PUT", path: "/account/password", persona: "alice", body: `{"current":`, status: 400, msg: "malformed JSON"}, + {name: "unknown field", op: opPasswordChange, method: "PUT", path: "/account/password", persona: "alice", body: `{"x":1}`, status: 400, msg: "request body has an unknown field"}, + {name: "missing body", op: opPasswordChange, method: "PUT", path: "/account/password", persona: "alice", status: 400, msg: "request body is required"}, + {name: "wrong current", op: opPasswordChange, method: "PUT", path: "/account/password", persona: "alice", + body: `{"current":"wrong-password-1","password":"brand-new-password"}`, status: 422, msg: "invalid password change"}, + {name: "short new", op: opPasswordChange, method: "PUT", path: "/account/password", persona: "alice", + body: `{"current":"` + testPassword + `","password":"short"}`, status: 422, msg: "invalid password change"}, + {name: "changed meanwhile", op: opPasswordChange, method: "PUT", path: "/account/password", persona: "alice", body: pw, + status: 409, msg: msgPasswordChanged, target: alice, + setup: func(env *matrixEnv) { + env.h.store.onTx = func(s *fakeWebState) { s.users[alice-1].PasswordHash = fakeHash("reset-by-admin") } + }}, + {name: "deleted meanwhile", tag: "in handler", op: opPasswordChange, method: "PUT", path: "/account/password", persona: "alice", body: pw, + status: 401, msg: msgAuthRequired, target: alice, + setup: func(env *matrixEnv) { + env.h.store.onTx = func(s *fakeWebState) { s.users[alice-1].DeletedAt.Valid = true } + }}, + {name: "hash failure", op: opPasswordChange, method: "PUT", path: "/account/password", persona: "alice", body: pw, status: 500, msg: msgInternalError, + setup: func(env *matrixEnv) { + env.h.s.hashPassword = func(string) (string, error) { return "", errMatrixInternal } + }}, + {name: "change audit failure", op: opPasswordChange, method: "PUT", path: "/account/password", persona: "alice", body: pw, + status: 500, msg: msgInternalError, target: alice, + setup: func(env *matrixEnv) { + env.h.store.failTimes["InsertAudit"] = 1 + env.h.store.failOn["InsertAudit"] = errMatrixInternal + }, + check: func(t *testing.T, env *matrixEnv, _ webResult) { + if env.h.store.user(alice).PasswordHash != fakeHash(testPassword) { + t.Fatal("password changed without audit") + } + }}, + {name: "unavailable", op: opPasswordChange, method: "PUT", path: "/account/password", persona: "alice", body: pw, + status: 503, msg: msgDatabaseDown, target: alice, setup: mxStoreFail("InTx", errDatabase)}, + + {name: "admin", op: opAuditRead, method: "GET", path: "/audit?limit=1", persona: "admin", status: 200, + resp: `{"entries":[],"next_before_id":null}`}, + {name: "user", op: opAuditRead, method: "GET", path: "/audit", persona: "alice", status: 200, + resp: `{"entries":[],"next_before_id":null}`}, + {name: "bad kind", op: opAuditRead, method: "GET", path: "/audit?kind=other", persona: "alice", status: 400, msg: "invalid parameter kind"}, + {name: "bad before id", op: opAuditRead, method: "GET", path: "/audit?before_id=9007199254740992", persona: "admin", status: 400, msg: "invalid parameter before_id"}, + {name: "list failure", op: opAuditRead, method: "GET", path: "/audit", persona: "admin", status: 500, msg: msgInternalError, + setup: mxStoreFail("ListAudit", errMatrixInternal)}, + {name: "zones unavailable", op: opAuditRead, method: "GET", path: "/audit", persona: "alice", status: 503, msg: msgDatabaseDown, + setup: mxStoreFail("UserZones", errDatabase)}, + } +} + +func matrixZoneCases() []matrixCase { + zoneRows := []string{"SELECT `id`", zoneRowsWhere} + newSOA := func(id int64, zone, mbox string) string { + return `{"id":` + itoa(id) + `,"zone":"` + zone + `","name":"","ttl":3600,"record_type":"SOA","content":"{\"ns\":\"ns.example.net.\",\"MBox\":\"` + + mbox + `\",\"refresh\":3600,\"retry\":600,\"expire\":604800,\"minttl\":300,\"serial\":2026111800}"}` + } + newNS := func(id int64, zone, host string) string { + return `{"id":` + itoa(id) + `,"zone":"` + zone + `","name":"","ttl":3600,"record_type":"NS","content":"{\"host\":\"` + host + `\"}"}` + } + all := []string{mxRecord(matrixSeed(1)), mxRecord(matrixSeed(2)), mxRecord(matrixSeed(3)), mxRecord(matrixSeed(4))} + return []matrixCase{ + {name: "admin", op: opZoneList, method: "GET", path: "/zones", persona: "admin", status: 200, + resp: `{"zones":[{"name":"example.org.","records":4,"serial":2026111700},{"name":"other.org.","records":2,"serial":2026111700}]}`}, + {name: "user", op: opZoneList, method: "GET", path: "/zones", persona: "alice", status: 200, + resp: `{"zones":[{"name":"example.org.","records":4,"serial":2026111700}]}`}, + {name: "user without zones", op: opZoneList, method: "GET", path: "/zones", persona: "dave", status: 200, resp: `{"zones":[]}`}, + {name: "query failure", op: opZoneList, method: "GET", path: "/zones", persona: "admin", status: 500, msg: msgInternalError, + setup: mxSQLFail(errMatrixInternal, "GROUP BY")}, + {name: "connection failure", op: opZoneList, method: "GET", path: "/zones", persona: "alice", status: 503, msg: msgDatabaseDown, + setup: mxSQLFail(errMatrixNet, "GROUP BY")}, + + {name: "over stale delegations", op: opZoneCreate, method: "POST", path: "/zones", persona: "admin", body: mxCreateStale, status: 201, + zone: mxStale, before: mxArray(mxDelegation(mxStale, "alice")), + after: mxArray(newSOA(7, mxStale, "hostmaster.stale.org."), newNS(8, mxStale, "ns.example.net."), newNS(9, mxStale, "backup.example.net.")), + check: func(t *testing.T, env *matrixEnv, _ webResult) { + if env.h.store.hasDelegation(mxStale, mxUserID("alice")) || len(env.sql.rows()) != 9 { + t.Fatal("stale delegation kept or rows missing") + } + }}, + {name: "fresh", op: opZoneCreate, method: "POST", path: "/zones", persona: "admin", body: mxCreateNew, status: 201, + zone: "new.org.", after: mxArray(newSOA(7, "new.org.", "hostmaster.new.org."), newNS(8, "new.org.", "ns.example.net."))}, + {name: "malformed", op: opZoneCreate, method: "POST", path: "/zones", persona: "admin", body: `{"name":`, status: 400, msg: "malformed JSON"}, + {name: "exists", op: opZoneCreate, method: "POST", path: "/zones", persona: "admin", body: strings.Replace(mxCreateNew, "new.org", "EXAMPLE.org", 1), + status: 409, msg: "zone already exists", zone: mxZone, check: mxUnchanged}, + {name: "invalid name", op: opZoneCreate, method: "POST", path: "/zones", persona: "admin", body: strings.Replace(mxCreateNew, `"new.org"`, `"bad..name"`, 1), + status: 422, msg: "validation failed"}, + {name: "invalid mailbox", op: opZoneCreate, method: "POST", path: "/zones", persona: "admin", body: strings.Replace(mxCreateNew, "hostmaster@new.org", "bad mailbox", 1), + status: 422, msg: "validation failed", zone: "new.org."}, + {name: "addressed zone of a refusal", op: opZoneCreate, method: "POST", path: "/zones", persona: "alice", body: mxCreateNew, + status: 403, msg: msgAdminRequired, zone: "new.org."}, + {name: "record insert failure", op: opZoneCreate, method: "POST", path: "/zones", persona: "admin", body: mxCreateStale, + status: 500, msg: msgInternalError, zone: mxStale, setup: mxSQLFail(errMatrixInternal, "INSERT INTO `coredns_records`"), + check: func(t *testing.T, env *matrixEnv, res webResult) { + mxUnchanged(t, env, res) + if !env.h.store.hasDelegation(mxStale, mxUserID("alice")) { + t.Fatal("rolled back creation removed the stale delegation") + } + }}, + {name: "change audit failure", op: opZoneCreate, method: "POST", path: "/zones", persona: "admin", body: mxCreateNew, + status: 500, msg: msgInternalError, zone: "new.org.", setup: mxSQLFail(errMatrixInternal, "INSERT INTO `coredns_webui_audit`"), check: mxUnchanged}, + {name: "zone busy", op: opZoneCreate, method: "POST", path: "/zones", persona: "admin", body: mxCreateNew, + status: 503, msg: msgZoneBusy, zone: "new.org.", setup: mxBusy}, + {name: "connection failure", op: opZoneCreate, method: "POST", path: "/zones", persona: "admin", body: mxCreateNew, + status: 503, msg: msgDatabaseDown, zone: "new.org.", setup: mxSQLFail(errMatrixNet, "FOR UPDATE")}, + + {name: "admin", op: opZoneRead, method: "GET", path: "/zones/EXAMPLE.org", persona: "admin", status: 200, zone: mxZone, + check: matrixHeader("Etag", recordETag(matrixSeed(1)))}, + {name: "user", op: opZoneRead, method: "GET", path: "/zones/example.org.", persona: "alice", status: 200, zone: mxZone}, + {name: "query failure", op: opZoneRead, method: "GET", path: "/zones/example.org.", persona: "admin", status: 500, msg: msgInternalError, + zone: mxZone, setup: mxSQLFail(errMatrixInternal, zoneRows...)}, + {name: "connection failure", op: opZoneRead, method: "GET", path: "/zones/example.org.", persona: "alice", status: 503, msg: msgDatabaseDown, + zone: mxZone, setup: mxSQLFail(errMatrixNet, zoneRows...)}, + + {name: "deleted", op: opZoneDelete, method: "DELETE", path: "/zones/example.org", persona: "admin", body: `{"confirm":"EXAMPLE.ORG"}`, status: 204, + zone: mxZone, before: mxArray(append(all, mxDelegation(mxZone, "alice"), mxDelegation(mxZone, "bob"), mxDelegation(mxZone, "gone"))...), + check: func(t *testing.T, env *matrixEnv, _ webResult) { + if len(env.sql.rows()) != 2 || env.h.store.hasDelegation(mxZone, mxUserID("alice")) { + t.Fatal("zone rows or delegations remain") + } + }}, + {name: "malformed", op: opZoneDelete, method: "DELETE", path: "/zones/example.org.", persona: "admin", body: `{"confirm"`, status: 400, + msg: "malformed JSON", zone: mxZone, check: mxUnchanged}, + {name: "missing body", op: opZoneDelete, method: "DELETE", path: "/zones/example.org.", persona: "admin", status: 400, + msg: "request body is required", zone: mxZone, check: mxUnchanged}, + {name: "missing zone", tag: "missing", op: opZoneDelete, method: "DELETE", path: "/zones/missing.org.", persona: "admin", body: `{"confirm":"missing.org"}`, + status: 404, msg: msgZoneNotFound, zone: mxMissing}, + {name: "stale zone", tag: "stale", op: opZoneDelete, method: "DELETE", path: "/zones/stale.org.", persona: "admin", body: `{"confirm":"stale.org"}`, + status: 404, msg: msgZoneNotFound, zone: mxStale, + check: func(t *testing.T, env *matrixEnv, _ webResult) { + if !env.h.store.hasDelegation(mxStale, mxUserID("alice")) { + t.Fatal("refused deletion removed the stale delegation") + } + }}, + {name: "confirmation mismatch", op: opZoneDelete, method: "DELETE", path: "/zones/example.org.", persona: "admin", body: `{"confirm":"other.org"}`, + status: 422, msg: "validation failed", zone: mxZone, check: mxUnchanged}, + {name: "change audit failure", op: opZoneDelete, method: "DELETE", path: "/zones/example.org.", persona: "admin", body: `{"confirm":"example.org"}`, + status: 500, msg: msgInternalError, zone: mxZone, setup: mxSQLFail(errMatrixInternal, "INSERT INTO `coredns_webui_audit`"), + check: func(t *testing.T, env *matrixEnv, res webResult) { + mxUnchanged(t, env, res) + if !env.h.store.hasDelegation(mxZone, mxUserID("alice")) { + t.Fatal("rolled back deletion removed the delegations") + } + }}, + {name: "zone busy", op: opZoneDelete, method: "DELETE", path: "/zones/example.org.", persona: "admin", body: `{"confirm":"example.org"}`, + status: 503, msg: msgZoneBusy, zone: mxZone, setup: mxBusy, check: mxUnchanged}, + {name: "connection failure", op: opZoneDelete, method: "DELETE", path: "/zones/example.org.", persona: "admin", body: `{"confirm":"example.org"}`, + status: 503, msg: msgDatabaseDown, zone: mxZone, setup: mxSQLFail(errMatrixNet, "DELETE FROM `coredns_records`"), check: mxUnchanged}, + + {name: "admin", op: opZoneCheck, method: "GET", path: "/zones/example.org./check", persona: "admin", status: 200, zone: mxZone}, + {name: "user", op: opZoneCheck, method: "GET", path: "/zones/example.org./check", persona: "alice", status: 200, zone: mxZone}, + {name: "query failure", op: opZoneCheck, method: "GET", path: "/zones/example.org./check", persona: "admin", status: 500, msg: msgInternalError, + zone: mxZone, setup: mxSQLFail(errMatrixInternal, zoneRows...)}, + {name: "connection failure", op: opZoneCheck, method: "GET", path: "/zones/example.org./check", persona: "alice", status: 503, msg: msgDatabaseDown, + zone: mxZone, setup: mxSQLFail(errMatrixNet, zoneRows...)}, + + {name: "admin", op: opCheckAll, method: "GET", path: "/check", persona: "admin", status: 200, + check: func(t *testing.T, _ *matrixEnv, res webResult) { + if !strings.HasPrefix(res.body, `{"problems":[`) { + t.Fatal(res.body) + } + }}, + {name: "user", op: opCheckAll, method: "GET", path: "/check", persona: "alice", status: 200, + check: func(t *testing.T, _ *matrixEnv, res webResult) { + if strings.Contains(res.body, mxOther) { + t.Fatalf("check of all zones shows a foreign zone: %s", res.body) + } + }}, + {name: "query failure", op: opCheckAll, method: "GET", path: "/check", persona: "admin", status: 500, msg: msgInternalError, + setup: mxSQLFail(errMatrixInternal, zoneRows...)}, + {name: "connection failure", op: opCheckAll, method: "GET", path: "/check", persona: "alice", status: 503, msg: msgDatabaseDown, + setup: mxSQLFail(errMatrixNet, "GROUP BY")}, + } +} + +func matrixRecordCases() []matrixCase { + soa := mxRecord(matrixSeed(1)) + soaNext := mxRecordWith(1, mxSOANext) + rec := func(id int64) string { return mxRecord(matrixSeed(id)) } + updated := mxRecordWith(3, `{"ip":"192.0.2.9"}`) + bulk := mxBulk + writeFail := func(op, method, path, body string, ifMatch, changed, record int64) []matrixCase { + return []matrixCase{ + {name: "change audit failure", op: op, method: method, path: path, persona: "admin", body: body, ifMatch: ifMatch, + status: 500, msg: msgInternalError, zone: mxZone, record: changed, + setup: mxSQLFail(errMatrixInternal, "INSERT INTO `coredns_webui_audit`"), check: mxUnchanged}, + {name: "zone busy", op: op, method: method, path: path, persona: "alice", body: body, ifMatch: ifMatch, + status: 503, msg: msgZoneBusy, zone: mxZone, record: record, setup: mxBusy, check: mxUnchanged}, + {name: "connection failure", op: op, method: method, path: path, persona: "admin", body: body, ifMatch: ifMatch, + status: 503, msg: msgDatabaseDown, zone: mxZone, record: record, setup: mxSQLFail(errMatrixNet, "FOR UPDATE"), check: mxUnchanged}, + {name: "store failure", op: op, method: method, path: path, persona: "admin", body: body, ifMatch: ifMatch, + status: 500, msg: msgInternalError, zone: mxZone, record: record, setup: mxSQLFail(errMatrixInternal, "FOR SHARE"), check: mxUnchanged}, + } + } + zoneRows := []string{"SELECT `id`", zoneRowsWhere} + cases := []matrixCase{ + {name: "admin", op: opRecordList, method: "GET", path: "/zones/example.org./records", persona: "admin", status: 200, zone: mxZone}, + {name: "user", op: opRecordList, method: "GET", path: "/zones/example.org/records", persona: "alice", status: 200, zone: mxZone}, + {name: "query failure", op: opRecordList, method: "GET", path: "/zones/example.org./records", persona: "admin", status: 500, msg: msgInternalError, + zone: mxZone, setup: mxSQLFail(errMatrixInternal, zoneRows...)}, + {name: "connection failure", op: opRecordList, method: "GET", path: "/zones/example.org./records", persona: "alice", status: 503, msg: msgDatabaseDown, + zone: mxZone, setup: mxSQLFail(errMatrixNet, zoneRows...)}, + + {name: "admin", op: opRecordCreate, method: "POST", path: "/zones/example.org./records", persona: "admin", body: mxRecordBody, status: 201, + zone: mxZone, record: 7, before: mxArray(soa), after: mxArray(soaNext, mxNewRecord(7))}, + {name: "delegated user", op: opRecordCreate, method: "POST", path: "/zones/Example.Org/records", persona: "alice", body: mxRecordBody, status: 201, + zone: mxZone, record: 7, before: mxArray(soa), after: mxArray(soaNext, mxNewRecord(7))}, + {name: "malformed", op: opRecordCreate, method: "POST", path: "/zones/example.org./records", persona: "alice", body: `{"name":`, status: 400, + msg: "malformed JSON", zone: mxZone, check: mxUnchanged}, + {name: "invalid address", op: opRecordCreate, method: "POST", path: "/zones/example.org./records", persona: "alice", + body: strings.Replace(mxRecordBody, "192.0.2.10", "2001:db8::1", 1), status: 422, msg: "validation failed", zone: mxZone, check: mxUnchanged}, + {name: "string ttl", op: opRecordCreate, method: "POST", path: "/zones/example.org./records", persona: "alice", + body: strings.Replace(mxRecordBody, "60", `"60"`, 1), status: 422, msg: "validation failed", zone: mxZone, check: mxUnchanged}, + {name: "CNAME next to an address", op: opRecordCreate, method: "POST", path: "/zones/example.org./records", persona: "admin", + body: `{"name":"www","type":"CNAME","ttl":60,"data":{"host":"target.example.net."}}`, status: 422, msg: "validation failed", zone: mxZone, check: mxUnchanged}, + {name: "commit failure", op: opRecordCreate, method: "POST", path: "/zones/example.org./records", persona: "admin", body: mxRecordBody, + status: 500, msg: msgInternalError, zone: mxZone, + setup: mxCommitFails, check: mxUnchanged}, + + {name: "replaced", op: opRecordUpdate, method: "PUT", path: "/zones/example.org./records/3", persona: "alice", body: mxUpdateBody, ifMatch: 3, + status: 200, zone: mxZone, record: 3, before: mxArray(soa, rec(3)), after: mxArray(soaNext, updated), + check: matrixHeader("Etag", recordETag(recordRow{ID: 3, Zone: mxZone, Name: "www", TTL: matrixSeed(3).TTL, RecordType: "A", + Content: matrixText(`{"ip":"192.0.2.9"}`, true)}))}, + {name: "unchanged", op: opRecordUpdate, method: "PUT", path: "/zones/example.org./records/3", persona: "admin", + body: `{"name":"www","type":"A","ttl":300,"data":{"ip":"192.0.2.1"}}`, ifMatch: 3, status: 200, zone: mxZone, record: 3, check: mxUnchanged}, + {name: "invalid id", op: opRecordUpdate, method: "PUT", path: "/zones/example.org./records/x", persona: "admin", body: mxUpdateBody, ifMatch: 3, + status: 400, msg: "invalid record id", zone: mxZone, check: mxUnchanged}, + {name: "id out of range", op: opRecordUpdate, method: "PUT", path: "/zones/example.org./records/2147483648", persona: "admin", body: mxUpdateBody, ifMatch: 3, + status: 400, msg: "invalid record id", zone: mxZone, check: mxUnchanged}, + {name: "malformed", op: opRecordUpdate, method: "PUT", path: "/zones/example.org./records/3", persona: "admin", body: `{"name"`, ifMatch: 3, + status: 400, msg: "malformed JSON", zone: mxZone, record: 3, check: mxUnchanged}, + {name: "record of another zone", tag: "record", op: opRecordUpdate, method: "PUT", path: "/zones/example.org./records/6", persona: "admin", body: mxUpdateBody, ifMatch: 6, + status: 404, msg: "record not found", zone: mxZone, record: 6, check: mxUnchanged}, + {name: "record gone", op: opRecordUpdate, method: "PUT", path: "/zones/example.org./records/99", persona: "admin", body: mxUpdateBody, ifMatch: 3, + status: 412, msg: "record changed", zone: mxZone, record: 99, check: mxUnchanged}, + {name: "stale ETag", op: opRecordUpdate, method: "PUT", path: "/zones/example.org./records/3", persona: "alice", body: mxUpdateBody, ifMatch: 4, + status: 412, msg: "record changed", zone: mxZone, record: 3, check: mxUnchanged}, + {name: "no If-Match", op: opRecordUpdate, method: "PUT", path: "/zones/example.org./records/3", persona: "alice", body: mxUpdateBody, + status: 428, msg: "If-Match is required", zone: mxZone, record: 3, check: mxUnchanged}, + {name: "invalid value", op: opRecordUpdate, method: "PUT", path: "/zones/example.org./records/3", persona: "alice", + body: strings.Replace(mxUpdateBody, "192.0.2.9", "999.0.2.9", 1), ifMatch: 3, status: 422, msg: "validation failed", zone: mxZone, record: 3, check: mxUnchanged}, + + {name: "deleted", op: opRecordDelete, method: "DELETE", path: "/zones/example.org./records/4", persona: "alice", ifMatch: 4, + status: 200, zone: mxZone, record: 4, before: mxArray(soa, rec(4)), after: mxArray(soaNext)}, + {name: "invalid id", op: opRecordDelete, method: "DELETE", path: "/zones/example.org./records/0", persona: "admin", ifMatch: 4, + status: 400, msg: "invalid record id", zone: mxZone, check: mxUnchanged}, + {name: "record of another zone", tag: "record", op: opRecordDelete, method: "DELETE", path: "/zones/example.org./records/5", persona: "admin", ifMatch: 5, + status: 404, msg: "record not found", zone: mxZone, record: 5, check: mxUnchanged}, + {name: "stale ETag", op: opRecordDelete, method: "DELETE", path: "/zones/example.org./records/4", persona: "admin", ifMatch: 3, + status: 412, msg: "record changed", zone: mxZone, record: 4, check: mxUnchanged}, + {name: "no If-Match", op: opRecordDelete, method: "DELETE", path: "/zones/example.org./records/4", persona: "admin", + status: 428, msg: "If-Match is required", zone: mxZone, record: 4, check: mxUnchanged}, + {name: "last SOA", op: opRecordDelete, method: "DELETE", path: "/zones/example.org./records/1", persona: "admin", ifMatch: 1, + status: 422, msg: "validation failed", zone: mxZone, record: 1, check: mxUnchanged}, + + {name: "deleted", op: opRecordBulkDelete, method: "POST", path: "/zones/example.org./records/delete", persona: "alice", body: bulk(3, 4), + status: 200, zone: mxZone, before: mxArray(soa, rec(3), rec(4)), after: mxArray(soaNext), resp: `{"deleted":2,"warnings":[]}`}, + {name: "malformed", op: opRecordBulkDelete, method: "POST", path: "/zones/example.org./records/delete", persona: "alice", body: `{"records":[`, + status: 400, msg: "malformed JSON", zone: mxZone, check: mxUnchanged}, + {name: "record of another zone", tag: "record", op: opRecordBulkDelete, method: "POST", path: "/zones/example.org./records/delete", persona: "alice", + body: bulk(3, 6), status: 404, msg: "record not found", zone: mxZone, check: mxUnchanged}, + {name: "stale ETag", op: opRecordBulkDelete, method: "POST", path: "/zones/example.org./records/delete", persona: "alice", + body: `{"records":[{"id":4,"etag":` + mxJSON(recordETag(matrixSeed(3))) + `}]}`, status: 412, msg: "record changed", zone: mxZone, check: mxUnchanged}, + {name: "empty", op: opRecordBulkDelete, method: "POST", path: "/zones/example.org./records/delete", persona: "alice", body: `{"records":[]}`, + status: 422, msg: "validation failed", zone: mxZone, check: mxUnchanged}, + {name: "last apex NS", op: opRecordBulkDelete, method: "POST", path: "/zones/example.org./records/delete", persona: "admin", body: bulk(2), + status: 422, msg: "validation failed", zone: mxZone, check: mxUnchanged}, + + {name: "updated", op: opSOAUpdate, method: "PUT", path: "/zones/example.org./soa", persona: "alice", body: mxSOABody, ifMatch: 1, + status: 200, zone: mxZone, record: 1, before: soa, after: mxRecordWith(1, strings.Replace(mxSOANext, `"retry":600`, `"retry":700`, 1))}, + {name: "unchanged", op: opSOAUpdate, method: "PUT", path: "/zones/example.org./soa", persona: "admin", + body: strings.Replace(mxSOABody, "700", "600", 1), ifMatch: 1, status: 200, zone: mxZone, record: 1, check: mxUnchanged}, + {name: "malformed", op: opSOAUpdate, method: "PUT", path: "/zones/example.org./soa", persona: "admin", body: `[`, ifMatch: 1, + status: 400, msg: "request body must be a JSON object", zone: mxZone, record: 1, check: mxUnchanged}, + {name: "stale ETag", op: opSOAUpdate, method: "PUT", path: "/zones/example.org./soa", persona: "admin", body: mxSOABody, ifMatch: 2, + status: 412, msg: "record changed", zone: mxZone, record: 1, check: mxUnchanged}, + {name: "no If-Match", op: opSOAUpdate, method: "PUT", path: "/zones/example.org./soa", persona: "admin", body: mxSOABody, + status: 428, msg: "If-Match is required", zone: mxZone, record: 1, check: mxUnchanged}, + {name: "invalid timer", op: opSOAUpdate, method: "PUT", path: "/zones/example.org./soa", persona: "admin", + body: strings.Replace(mxSOABody, "700", "2147483648", 1), ifMatch: 1, status: 422, msg: "validation failed", zone: mxZone, record: 1, check: mxUnchanged}, + } + cases = append(cases, writeFail(opRecordCreate, "POST", "/zones/example.org./records", mxRecordBody, 0, 0, 0)...) + cases = append(cases, writeFail(opRecordUpdate, "PUT", "/zones/example.org./records/3", mxUpdateBody, 3, 3, 3)...) + cases = append(cases, writeFail(opRecordDelete, "DELETE", "/zones/example.org./records/4", "", 4, 4, 4)...) + cases = append(cases, writeFail(opRecordBulkDelete, "POST", "/zones/example.org./records/delete", bulk(3, 4), 0, 0, 0)...) + cases = append(cases, writeFail(opSOAUpdate, "PUT", "/zones/example.org./soa", mxSOABody, 1, 1, 0)...) + return cases +} + +func matrixFileCases() []matrixCase { + fingerprint := zoneFingerprint(matrixSeedRecords()[:4]) + merge := `{"mode":"merge","content":"new 60 A 192.0.2.10\n"}` + apply := `{"mode":"merge","content":"new 60 A 192.0.2.10\n","fingerprint":"` + fingerprint + `"}` + zoneRows := []string{"SELECT `id`", zoneRowsWhere} + cases := []matrixCase{ + {name: "admin", op: opZoneExport, method: "GET", path: "/zones/example.org./export", persona: "admin", status: 200, zone: mxZone, + check: matrixHeader("Content-Disposition", `attachment; filename="example.org.zone"`)}, + {name: "user", op: opZoneExport, method: "GET", path: "/zones/example.org./export", persona: "alice", status: 200, zone: mxZone, + check: matrixHeader("Content-Type", "text/plain")}, + {name: "query failure", op: opZoneExport, method: "GET", path: "/zones/example.org./export", persona: "admin", status: 500, msg: msgInternalError, + zone: mxZone, setup: mxSQLFail(errMatrixInternal, zoneRows...)}, + {name: "connection failure", op: opZoneExport, method: "GET", path: "/zones/example.org./export", persona: "alice", status: 503, msg: msgDatabaseDown, + zone: mxZone, setup: mxSQLFail(errMatrixNet, zoneRows...)}, + + {name: "merge", op: opZoneImportPreview, method: "POST", path: "/zones/example.org./import/preview", persona: "alice", body: merge, + status: 200, zone: mxZone, check: func(t *testing.T, env *matrixEnv, res webResult) { + mxUnchanged(t, env, res) + if !strings.Contains(res.body, `"fingerprint":"`+fingerprint+`"`) { + t.Fatal(res.body) + } + }}, + {name: "malformed", op: opZoneImportPreview, method: "POST", path: "/zones/example.org./import/preview", persona: "alice", body: `{"mode":`, + status: 400, msg: "malformed JSON", zone: mxZone}, + {name: "missing content", op: opZoneImportPreview, method: "POST", path: "/zones/example.org./import/preview", persona: "alice", body: `{"mode":"merge"}`, + status: 422, msg: "validation failed", zone: mxZone}, + {name: "parse error", op: opZoneImportPreview, method: "POST", path: "/zones/example.org./import/preview", persona: "alice", + body: `{"mode":"merge","content":"new 60 A not-an-address\n"}`, status: 422, msg: "the file has errors", zone: mxZone}, + {name: "query failure", op: opZoneImportPreview, method: "POST", path: "/zones/example.org./import/preview", persona: "admin", body: merge, + status: 500, msg: msgInternalError, zone: mxZone, setup: mxSQLFail(errMatrixInternal, zoneRows...)}, + {name: "connection failure", op: opZoneImportPreview, method: "POST", path: "/zones/example.org./import/preview", persona: "admin", body: merge, + status: 503, msg: msgDatabaseDown, zone: mxZone, setup: mxSQLFail(errMatrixNet, zoneRows...)}, + + {name: "merge", op: opZoneImport, method: "POST", path: "/zones/example.org./import/apply", persona: "alice", body: apply, + status: 200, zone: mxZone, before: mxArray(mxRecord(matrixSeed(1))), after: mxArray(mxRecordWith(1, mxSOANext), mxNewRecord(7)), + resp: `{"added":1,"deleted":0,"updated":0,"warnings":[]}`}, + {name: "malformed", op: opZoneImport, method: "POST", path: "/zones/example.org./import/apply", persona: "alice", body: `{"mode":`, + status: 400, msg: "malformed JSON", zone: mxZone, check: mxUnchanged}, + {name: "fingerprint changed", op: opZoneImport, method: "POST", path: "/zones/example.org./import/apply", persona: "alice", + body: strings.Replace(apply, fingerprint, strings.Repeat("0", len(fingerprint)), 1), status: 409, msg: "zone changed since preview", zone: mxZone, check: mxUnchanged}, + {name: "invalid mode", op: opZoneImport, method: "POST", path: "/zones/example.org./import/apply", persona: "alice", + body: strings.Replace(apply, "merge", "append", 1), status: 422, msg: "validation failed", zone: mxZone, check: mxUnchanged}, + {name: "parse error", op: opZoneImport, method: "POST", path: "/zones/example.org./import/apply", persona: "alice", + body: strings.Replace(apply, "192.0.2.10", "not-an-address", 1), status: 422, msg: "the file has errors", zone: mxZone, check: mxUnchanged}, + } + for _, c := range []matrixCase{ + {name: "change audit failure", persona: "admin", status: 500, msg: msgInternalError, setup: mxSQLFail(errMatrixInternal, "INSERT INTO `coredns_webui_audit`")}, + {name: "zone busy", persona: "alice", status: 503, msg: msgZoneBusy, setup: mxBusy}, + {name: "connection failure", persona: "admin", status: 503, msg: msgDatabaseDown, setup: mxSQLFail(errMatrixNet, "INSERT INTO `coredns_records`")}, + } { + c.op, c.method, c.path, c.body, c.zone, c.check = opZoneImport, "POST", "/zones/example.org./import/apply", apply, mxZone, mxUnchanged + cases = append(cases, c) + } + return cases +} + +func matrixDelegationCases() []matrixCase { + carol, alice, bob, gone, root, dave := mxUserID("carol"), mxUserID("alice"), mxUserID("bob"), mxUserID("gone"), mxUserID("root"), mxUserID("dave") + demoteActor := func(env *matrixEnv) { + env.h.store.onLock = func(s *fakeWebState) { s.users[0].Role = roleUser } + } + return []matrixCase{ + {name: "listed", op: opDelegationList, method: "GET", path: "/zones/example.org./users", persona: "admin", status: 200, zone: mxZone, + resp: `{"users":[{"username":"alice","role":"user"},{"username":"bob","role":"user"}]}`}, + {name: "missing zone", tag: "missing", op: opDelegationList, method: "GET", path: "/zones/missing.org./users", persona: "admin", status: 404, + msg: msgZoneNotFound, zone: mxMissing}, + {name: "stale zone", tag: "stale", op: opDelegationList, method: "GET", path: "/zones/stale.org./users", persona: "admin", status: 404, + msg: msgZoneNotFound, zone: mxStale}, + {name: "list failure", op: opDelegationList, method: "GET", path: "/zones/example.org./users", persona: "admin", status: 500, + msg: msgInternalError, zone: mxZone, setup: mxStoreFail("ZoneUsers", errMatrixInternal)}, + {name: "unavailable", op: opDelegationList, method: "GET", path: "/zones/example.org./users", persona: "admin", status: 503, + msg: msgDatabaseDown, zone: mxZone, setup: mxStoreFail("ZoneExists", errDatabase)}, + + {name: "granted", op: opDelegationGrant, method: "PUT", path: "/zones/Example.org/users/carol", persona: "admin", status: 204, + zone: mxZone, target: carol, after: mxDelegation(mxZone, "carol"), + check: func(t *testing.T, env *matrixEnv, _ webResult) { + if !env.h.store.hasDelegation(mxZone, carol) { + t.Fatal("delegation missing") + } + }}, + {name: "already granted", op: opDelegationGrant, method: "PUT", path: "/zones/example.org./users/alice", persona: "admin", status: 204, + zone: mxZone, target: alice}, + {name: "missing zone", tag: "missing", op: opDelegationGrant, method: "PUT", path: "/zones/missing.org./users/carol", persona: "admin", status: 404, + msg: msgZoneNotFound, zone: mxMissing}, + {name: "stale zone", tag: "stale", op: opDelegationGrant, method: "PUT", path: "/zones/stale.org./users/carol", persona: "admin", status: 404, + msg: msgZoneNotFound, zone: mxStale}, + {name: "unknown user", tag: "user", op: opDelegationGrant, method: "PUT", path: "/zones/example.org./users/nobody", persona: "admin", status: 404, + msg: msgUserNotFound, zone: mxZone}, + {name: "invalid username", tag: "user", op: opDelegationGrant, method: "PUT", path: "/zones/example.org./users/Bad%21", persona: "admin", status: 404, + msg: msgUserNotFound, zone: mxZone}, + {name: "deleted user", tag: "user", op: opDelegationGrant, method: "PUT", path: "/zones/example.org./users/gone", persona: "admin", status: 404, + msg: msgUserNotFound, zone: mxZone, target: gone}, + {name: "admin target", op: opDelegationGrant, method: "PUT", path: "/zones/example.org./users/root", persona: "admin", status: 422, + msg: "zones cannot be delegated to admins", zone: mxZone, target: root}, + {name: "actor demoted meanwhile", op: opDelegationGrant, method: "PUT", path: "/zones/example.org./users/carol", persona: "admin", status: 403, + msg: msgAdminRequired, zone: mxZone, target: carol, setup: demoteActor}, + {name: "change audit failure", op: opDelegationGrant, method: "PUT", path: "/zones/example.org./users/carol", persona: "admin", status: 500, + msg: msgInternalError, zone: mxZone, target: carol, + setup: func(env *matrixEnv) { + env.h.store.failTimes["InsertAudit"] = 1 + env.h.store.failOn["InsertAudit"] = errMatrixInternal + }, + check: func(t *testing.T, env *matrixEnv, _ webResult) { + if env.h.store.hasDelegation(mxZone, carol) { + t.Fatal("delegation kept without audit") + } + }}, + {name: "zone busy", op: opDelegationGrant, method: "PUT", path: "/zones/example.org./users/carol", persona: "admin", status: 503, + msg: msgZoneBusy, zone: mxZone, setup: mxStoreFail("InTx", errLockTimeout)}, + {name: "unavailable", op: opDelegationGrant, method: "PUT", path: "/zones/example.org./users/carol", persona: "admin", status: 503, + msg: msgDatabaseDown, zone: mxZone, setup: mxStoreFail("UserByUsernameForUpdate", errDatabase)}, + + {name: "revoked", op: opDelegationRevoke, method: "DELETE", path: "/zones/example.org./users/bob", persona: "admin", status: 204, + zone: mxZone, target: bob, before: mxDelegation(mxZone, "bob")}, + {name: "stale delegation revoked", op: opDelegationRevoke, method: "DELETE", path: "/zones/stale.org./users/alice", persona: "admin", status: 204, + zone: mxStale, target: alice, before: mxDelegation(mxStale, "alice")}, + {name: "no delegation", tag: "delegation", op: opDelegationRevoke, method: "DELETE", path: "/zones/example.org./users/carol", persona: "admin", status: 404, + msg: msgDelegationAbsent, zone: mxZone, target: carol}, + {name: "no delegation in a missing zone", tag: "delegation", op: opDelegationRevoke, method: "DELETE", path: "/zones/missing.org./users/dave", + persona: "admin", status: 404, msg: msgDelegationAbsent, zone: mxMissing, target: dave}, + {name: "unknown user", tag: "user", op: opDelegationRevoke, method: "DELETE", path: "/zones/example.org./users/nobody", persona: "admin", status: 404, + msg: msgUserNotFound, zone: mxZone}, + {name: "deleted user", tag: "user", op: opDelegationRevoke, method: "DELETE", path: "/zones/example.org./users/gone", persona: "admin", status: 404, + msg: msgUserNotFound, zone: mxZone, target: gone}, + {name: "actor demoted meanwhile", op: opDelegationRevoke, method: "DELETE", path: "/zones/example.org./users/bob", persona: "admin", status: 403, + msg: msgAdminRequired, zone: mxZone, target: bob, setup: demoteActor}, + {name: "revoke failure", op: opDelegationRevoke, method: "DELETE", path: "/zones/example.org./users/bob", persona: "admin", status: 500, + msg: msgInternalError, zone: mxZone, target: bob, setup: mxStoreFail("RevokeDelegation", errMatrixInternal)}, + {name: "unavailable", op: opDelegationRevoke, method: "DELETE", path: "/zones/example.org./users/bob", persona: "admin", status: 503, + msg: msgDatabaseDown, zone: mxZone, setup: mxStoreFail("InTx", errDatabase)}, + } +} + +func matrixUserCases() []matrixCase { + dave, gone, admin := mxUserID("dave"), mxUserID("gone"), mxUserID("admin") + daveAdmin := mxUser(dave, "dave", roleAdmin, mxCreated, "") + daveDeleted := mxUser(dave, "dave", roleUser, mxCreated, mxNow) + newbie := `{"username":"newbie","role":"user","password":"long-enough-password"}` + auditFails := func(env *matrixEnv) { + env.h.store.failTimes["InsertAudit"] = 1 + env.h.store.failOn["InsertAudit"] = errMatrixInternal + } + demoteActor := func(env *matrixEnv) { + env.h.store.onLock = func(s *fakeWebState) { s.users[0].Role = roleUser } + } + unchanged := func(name string) func(t *testing.T, env *matrixEnv, _ webResult) { + return func(t *testing.T, env *matrixEnv, _ webResult) { + t.Helper() + if env.h.store.user(mxUserID(name)) != env.users[name] { + t.Fatalf("user %s changed", name) + } + } + } + var cases []matrixCase + cases = append(cases, []matrixCase{ + {name: "active", op: opUserList, method: "GET", path: "/users", persona: "admin", status: 200, + check: func(t *testing.T, _ *matrixEnv, res webResult) { + if strings.Contains(res.body, `"gone"`) || !strings.Contains(res.body, `{"username":"alice","role":"user","zone_count":2,`) { + t.Fatal(res.body) + } + }}, + {name: "with deleted", op: opUserList, method: "GET", path: "/users?deleted=true", persona: "admin", status: 200, + check: func(t *testing.T, _ *matrixEnv, res webResult) { + if !strings.Contains(res.body, `"username":"gone"`) { + t.Fatal(res.body) + } + }}, + {name: "bad flag", op: opUserList, method: "GET", path: "/users?deleted=maybe", persona: "admin", status: 400, msg: "invalid parameter deleted"}, + {name: "list failure", op: opUserList, method: "GET", path: "/users", persona: "admin", status: 500, msg: msgInternalError, + setup: mxStoreFail("ListUsers", errMatrixInternal)}, + {name: "unavailable", op: opUserList, method: "GET", path: "/users", persona: "admin", status: 503, msg: msgDatabaseDown, + setup: mxStoreFail("ListUsers", errDatabase)}, + + {name: "created", op: opUserCreate, method: "POST", path: "/users", persona: "admin", body: newbie, status: 201, + target: 8, after: mxUser(8, "newbie", roleUser, mxNow, "")}, + {name: "malformed", op: opUserCreate, method: "POST", path: "/users", persona: "admin", body: `{"username"`, status: 400, msg: "malformed JSON"}, + {name: "username taken", op: opUserCreate, method: "POST", path: "/users", persona: "admin", body: strings.Replace(newbie, "newbie", "gone", 1), + status: 409, msg: msgUsernameTaken}, + {name: "invalid", op: opUserCreate, method: "POST", path: "/users", persona: "admin", body: `{"username":"cli","role":"owner","password":"x"}`, + status: 422, msg: "invalid user"}, + {name: "change audit failure", op: opUserCreate, method: "POST", path: "/users", persona: "admin", body: newbie, status: 500, + msg: msgInternalError, setup: auditFails, + check: func(t *testing.T, env *matrixEnv, _ webResult) { + if _, err := env.h.store.view().userByUsername("newbie"); !errors.Is(err, errRowNotFound) { + t.Fatal("user created without audit") + } + }}, + {name: "actor demoted meanwhile", op: opUserCreate, method: "POST", path: "/users", persona: "admin", body: newbie, status: 403, + msg: msgAdminRequired, setup: demoteActor}, + {name: "unavailable", op: opUserCreate, method: "POST", path: "/users", persona: "admin", body: newbie, status: 503, + msg: msgDatabaseDown, setup: mxStoreFail("CreateUser", errDatabase)}, + + {name: "active", op: opUserRead, method: "GET", path: "/users/alice", persona: "admin", status: 200, target: mxUserID("alice"), + check: func(t *testing.T, _ *matrixEnv, res webResult) { + if !strings.Contains(res.body, `"zones":[{"zone":"example.org.","exists":true},{"zone":"stale.org.","exists":false}]`) { + t.Fatal(res.body) + } + }}, + {name: "deleted", op: opUserRead, method: "GET", path: "/users/gone", persona: "admin", status: 200, target: gone}, + {name: "unknown", tag: "user", op: opUserRead, method: "GET", path: "/users/nobody", persona: "admin", status: 404, msg: msgUserNotFound}, + {name: "invalid username", tag: "user", op: opUserRead, method: "GET", path: "/users/-x", persona: "admin", status: 404, msg: msgUserNotFound}, + {name: "zones failure", op: opUserRead, method: "GET", path: "/users/alice", persona: "admin", status: 500, msg: msgInternalError, + target: mxUserID("alice"), setup: mxStoreFail("UserZones", errMatrixInternal)}, + {name: "unavailable", op: opUserRead, method: "GET", path: "/users/alice", persona: "admin", status: 503, msg: msgDatabaseDown, + setup: mxStoreFail("UserByUsername", errDatabase)}, + }...) + type userWrite struct { + op, method, suffix, body string + status int + before, after string + } + for _, w := range []userWrite{ + {opUserRole, "PUT", "/role", `{"role":"admin"}`, 204, mxSeedUser("dave"), daveAdmin}, + {opUserPassword, "PUT", "/password", `{"password":"another-long-password"}`, 204, mxSeedUser("dave"), mxSeedUser("dave")}, + {opUserDelete, "DELETE", "", `{"confirm":"dave"}`, 204, mxSeedUser("dave"), daveDeleted}, + } { + forUser := func(name string) (string, string) { + return "/users/" + name + w.suffix, strings.Replace(w.body, `"dave"`, `"`+name+`"`, 1) + } + path, body := forUser("dave") + ownPath, ownBody := forUser("admin") + nobodyPath, nobodyBody := forUser("nobody") + gonePath, goneBody := forUser("gone") + cases = append(cases, []matrixCase{ + {name: "changed", op: w.op, method: w.method, path: path, persona: "admin", body: body, status: w.status, + target: dave, before: w.before, after: w.after}, + {name: "malformed", op: w.op, method: w.method, path: path, persona: "admin", body: `{"x"`, status: 400, msg: "malformed JSON", check: unchanged("dave")}, + {name: "own account", op: w.op, method: w.method, path: ownPath, persona: "admin", body: ownBody, status: 403, msg: msgOwnAccount, + target: admin, check: unchanged("admin")}, + {name: "unknown", tag: "user", op: w.op, method: w.method, path: nobodyPath, persona: "admin", body: nobodyBody, status: 404, msg: msgUserNotFound}, + {name: "deleted", tag: "user", op: w.op, method: w.method, path: gonePath, persona: "admin", body: goneBody, status: 404, msg: msgUserNotFound, + target: gone, check: unchanged("gone")}, + {name: "actor demoted meanwhile", op: w.op, method: w.method, path: path, persona: "admin", body: body, status: 403, msg: msgAdminRequired, + target: dave, setup: demoteActor, check: unchanged("dave")}, + {name: "change audit failure", op: w.op, method: w.method, path: path, persona: "admin", body: body, status: 500, msg: msgInternalError, + target: dave, setup: auditFails, check: unchanged("dave")}, + {name: "unavailable", op: w.op, method: w.method, path: path, persona: "admin", body: body, status: 503, msg: msgDatabaseDown, + setup: mxStoreFail("InTx", errDatabase), check: unchanged("dave")}, + }...) + } + return append(cases, []matrixCase{ + {name: "unchanged role", op: opUserRole, method: "PUT", path: "/users/dave/role", persona: "admin", body: `{"role":"user"}`, status: 204, + target: dave, check: unchanged("dave")}, + {name: "invalid role", op: opUserRole, method: "PUT", path: "/users/dave/role", persona: "admin", body: `{"role":"owner"}`, status: 422, + msg: "invalid role", check: unchanged("dave")}, + {name: "short password", op: opUserPassword, method: "PUT", path: "/users/dave/password", persona: "admin", body: `{"password":"short"}`, status: 422, + msg: "invalid password", check: unchanged("dave")}, + {name: "confirmation mismatch", op: opUserDelete, method: "DELETE", path: "/users/dave", persona: "admin", body: `{"confirm":"Dave"}`, status: 422, + msg: "invalid confirm", check: unchanged("dave")}, + }...) +} diff --git a/apimatrix_env_test.go b/apimatrix_env_test.go new file mode 100644 index 0000000..28608b9 --- /dev/null +++ b/apimatrix_env_test.go @@ -0,0 +1,143 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright (C) 2026 Bryan Joshua Pedini + +package main + +import ( + "database/sql" + "encoding/json" + "errors" + "fmt" + "net" + "strings" + "testing" + "time" +) + +const ( + mxOrigin = "192.0.2.10" + mxZone = "example.org." + mxStale = "stale.org." + mxOther = "other.org." + mxMissing = "missing.org." + mxCreated = "2026-11-16T12:00:00.000000Z" + mxNow = "2026-11-18T12:00:00.000000Z" + mxSOA = `{"ns":"ns.example.net.","MBox":"hostmaster.example.org.","refresh":3600,"retry":600,"expire":604800,"minttl":300,"serial":2026111700}` + mxSOANext = `{"ns":"ns.example.net.","MBox":"hostmaster.example.org.","refresh":3600,"retry":600,"expire":604800,"minttl":300,"serial":2026111800}` + mxNS = `{"host":"ns.example.net."}` +) + +var ( + errMatrixInternal = errors.New("matrix internal failure") + errMatrixNet = &net.OpError{Op: "read", Net: "tcp", Err: errors.New("connection reset by peer")} +) + +var matrixUserSeed = []struct{ name, role string }{ + {"admin", roleAdmin}, {"root", roleAdmin}, {"alice", roleUser}, {"dave", roleUser}, + {"carol", roleUser}, {"bob", roleUser}, {"gone", roleUser}, +} + +func matrixSeedRecords() []recordRow { + rec := func(id int64, zone, name string, ttl int64, typ, content string) recordRow { + return recordRow{ID: id, Zone: zone, Name: name, TTL: sql.NullInt64{Int64: ttl, Valid: true}, + Content: sql.NullString{String: content, Valid: true}, RecordType: typ} + } + return []recordRow{ + rec(1, mxZone, "", 3600, "SOA", mxSOA), + rec(2, mxZone, "", 3600, "NS", mxNS), + rec(3, mxZone, "www", 300, "A", `{"ip":"192.0.2.1"}`), + rec(4, mxZone, "mail", 300, "A", `{"ip":"192.0.2.2"}`), + rec(5, mxOther, "", 3600, "SOA", strings.Replace(mxSOA, "example.org", "other.org", 1)), + rec(6, mxOther, "", 3600, "NS", mxNS), + } +} + +func matrixSeed(id int64) recordRow { + return matrixSeedRecords()[id-1] +} + +type matrixEnv struct { + t *testing.T + h *webHarness + sql *matrixSQL + users map[string]userRow + tokens map[string]string +} + +func newMatrixEnv(t *testing.T) *matrixEnv { + t.Helper() + h := newWebHarness(t) + m := newMatrixSQL(t, h.store) + h.s.db = m.open(t) + h.s.tables = fdbTables(t) + h.handler = h.s.Handler() + env := &matrixEnv{t: t, h: h, sql: m, users: map[string]userRow{}, tokens: map[string]string{}} + for _, u := range matrixUserSeed { + env.users[u.name] = h.user(u.name, u.role) + env.tokens[u.name] = h.login(env.users[u.name]) + } + gone := env.users["gone"] + gone.DeletedAt = sql.NullTime{Time: webNow.Add(-time.Hour), Valid: true} + h.store.setUser(gone) + env.users["gone"] = gone + for _, d := range []struct{ zone, user string }{{mxZone, "alice"}, {mxZone, "bob"}, {mxZone, "gone"}, {mxStale, "alice"}} { + h.store.delegate(d.zone, env.users[d.user]) + } + for _, r := range matrixSeedRecords() { + m.addRecord(r) + } + return env +} + +func mxJSON(v any) string { + b, err := json.Marshal(v) + if err != nil { + panic(err) + } + return string(b) +} + +func mxRecord(r recordRow) string { + return fmt.Sprintf(`{"id":%d,"zone":%s,"name":%s,"ttl":%d,"record_type":%s,"content":%s}`, + r.ID, mxJSON(r.Zone), mxJSON(r.Name), r.TTL.Int64, mxJSON(r.RecordType), mxJSON(r.Content.String)) +} + +func mxRecordWith(id int64, content string) string { + r := matrixSeed(id) + r.Content.String = content + return mxRecord(r) +} + +func mxArray(items ...string) string { + return "[" + strings.Join(items, ",") + "]" +} + +func mxUser(id int64, name, role, created string, deleted string) string { + d := "null" + if deleted != "" { + d = mxJSON(deleted) + } + return fmt.Sprintf(`{"id":%d,"username":%s,"role":%s,"created_at":%s,"deleted_at":%s}`, id, mxJSON(name), mxJSON(role), mxJSON(created), d) +} + +func mxDelegation(zone, username string) string { + return fmt.Sprintf(`{"zone":%s,"username":%s}`, mxJSON(zone), mxJSON(username)) +} + +func mxSeedUser(name string) string { + for i, u := range matrixUserSeed { + if u.name == name { + return mxUser(int64(i+1), u.name, u.role, mxCreated, "") + } + } + panic(name) +} + +func mxUserID(name string) int64 { + for i, u := range matrixUserSeed { + if u.name == name { + return int64(i + 1) + } + } + panic(name) +} diff --git a/apimatrix_test.go b/apimatrix_test.go new file mode 100644 index 0000000..e2cbe88 --- /dev/null +++ b/apimatrix_test.go @@ -0,0 +1,378 @@ +// 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)) +} diff --git a/e2e/compose.yaml b/e2e/compose.yaml index f7bee2f..cca38a8 100644 --- a/e2e/compose.yaml +++ b/e2e/compose.yaml @@ -266,5 +266,4 @@ services: E2E_FUZZ_CASES: ${E2E_FUZZ_CASES:-} E2E_OPERATOR_ACTIONS: ${E2E_OPERATOR_ACTIONS:-} E2E_ARGS: ${E2E_ARGS:-} - E2E_REVIEW_FIXES: ${E2E_REVIEW_FIXES:-} command: ["sh", "-c", "npx tsc --noEmit && exec npx playwright test $$E2E_ARGS"] diff --git a/e2e/harness/decisions.ts b/e2e/harness/decisions.ts index 3607bc8..d61f98e 100644 --- a/e2e/harness/decisions.ts +++ b/e2e/harness/decisions.ts @@ -3,15 +3,13 @@ import { expect } from '@playwright/test'; -export const REVIEW_FIXES: boolean = process.env.E2E_REVIEW_FIXES === 'enabled'; - export const UNKNOWN_API_OPERATION = 'api_unknown'; -export const UNKNOWN_API_ROW_COUNT = REVIEW_FIXES ? 1 : 0; -export const RECORD_DELETE_STATUS = REVIEW_FIXES ? 200 : 204; -export const ZONE_CREATE_DELEGATIONS_IN = REVIEW_FIXES ? 'before' : 'any'; +export const UNKNOWN_API_ROW_COUNT = 1; +export const RECORD_DELETE_STATUS = 200; +export const ZONE_CREATE_DELEGATIONS_IN = 'before'; export function expectRecordDeleteBody(json: unknown, what: string): void { - if (REVIEW_FIXES) expect(json, `${what}: record delete answers its warnings`).toEqual({ warnings: expect.any(Array) }); + expect(json, `${what}: record delete answers its warnings`).toEqual({ warnings: expect.any(Array) }); } export function bulkDeleteBody(deleted: number): Record { @@ -23,11 +21,10 @@ export function importApplyBody(added: number, updated: number, deleted: number) } export function expectZoneCreateWarnings(json: unknown): void { - if (REVIEW_FIXES) expect((json as { warnings?: unknown }).warnings, 'zone create answers its warnings').toEqual(expect.any(Array)); + expect((json as { warnings?: unknown }).warnings, 'zone create answers its warnings').toEqual(expect.any(Array)); } export function expectCheckErrorRowsCarryRaw(rows: Array<{ data: unknown; raw: string | null; problems: Array<{ severity: string }> }>, contentOf: (index: number) => string | null): void { - if (!REVIEW_FIXES) return; rows.forEach((r, i) => { if (r.problems.some((p) => p.severity === 'error')) expect(r.raw, 'a row with a check error carries its stored content in raw').toBe(contentOf(i)); }); diff --git a/e2e/harness/ledger.ts b/e2e/harness/ledger.ts index 0e6b226..c837910 100644 --- a/e2e/harness/ledger.ts +++ b/e2e/harness/ledger.ts @@ -3,7 +3,7 @@ import { expect } from '@playwright/test'; import type { AuditRow, Db } from './mysql'; -import { REVIEW_FIXES, UNKNOWN_API_OPERATION } from './decisions'; +import { UNKNOWN_API_OPERATION } from './decisions'; import type { SecretRegistry } from './secrets'; export const READ_OPERATIONS = new Set([ @@ -208,11 +208,7 @@ export class AuditLedger { return; } if (!route || x.status === 405) { - this.add( - REVIEW_FIXES - ? { operation: UNKNOWN_API_OPERATION, status: x.status, actor: x.actor, origin: x.origin, userIsActor: true, error: errorOf(x.body) ?? undefined, optional: false, source: x.source } - : { operation: '*', status: x.status, actor: x.actor, origin: x.origin, userIsActor: true, optional: true, source: x.source }, - ); + this.add({ operation: UNKNOWN_API_OPERATION, status: x.status, actor: x.actor, origin: x.origin, userIsActor: true, error: errorOf(x.body) ?? undefined, optional: false, source: x.source }); return; } const ok = x.status < 400; diff --git a/e2e/tests/core.spec.ts b/e2e/tests/core.spec.ts index 829d5b2..1a85b2c 100644 --- a/e2e/tests/core.spec.ts +++ b/e2e/tests/core.spec.ts @@ -7,7 +7,7 @@ import { zp, up } from '../harness/api'; import { parseTable, USAGE_TEXT } from '../harness/cli'; import { waitForZone, waitForZoneGone } from '../harness/dig'; import { runnerAddress, SESSION_COOKIE } from '../harness/env'; -import { bulkDeleteBody, expectCheckErrorRowsCarryRaw, expectZoneCreateWarnings, importApplyBody, REVIEW_FIXES, UNKNOWN_API_OPERATION, ZONE_CREATE_DELEGATIONS_IN } from '../harness/decisions'; +import { bulkDeleteBody, expectCheckErrorRowsCarryRaw, expectZoneCreateWarnings, importApplyBody, UNKNOWN_API_OPERATION, ZONE_CREATE_DELEGATIONS_IN } from '../harness/decisions'; import { READ_OPERATIONS } from '../harness/ledger'; import type { AuditRow, RecordRow } from '../harness/mysql'; import { newZoneSerial, uiValue, utcDay } from '../harness/records'; @@ -207,7 +207,7 @@ test.describe('core flow', () => { const change = await begin(world, zone); const mark = await world.db.auditMaxId(); const deleted = await adminUi.deleteRecord({ name: rec.name === '' ? '@' : rec.name, type: rec.type, value: uiValue(rec.type, rec.data) }); - expect([200, 204]).toContain(deleted.status); + expect(deleted.status).toBe(200); if (deleted.status === 200) expect(deleted.json).toMatchObject({ warnings: expect.any(Array) }); await threeWayGone(world, adminUi, zone, rec, change, what); expect(await world.db.recordById(before.id)).toBeUndefined(); @@ -558,6 +558,56 @@ test.describe('core flow', () => { await servedZone(world, zoneC); }); + test('noncanonical zones and selected SOA rows can be repaired through the UI', async ({ world }) => { + test.setTimeout(180_000); + const api = adminApi; + const zone = world.zoneName('repair-'); + expect((await api.post('/zones', { name: zone, ns: `ns1.${zone}`, mbox: `hostmaster@${zone}`, extra_ns: [], refresh: 3600, retry: 600, expire: 604800, minttl: 300, ttl: 3600 })).status).toBe(201); + const ui = adminUi; + await waitForZone(world.g, zone, { recorder: world.recorder }); + const baseline = await world.db.records(zone); + for (const [name, storedZone, code, ip] of [ + ['nodot', zone.slice(0, -1), 'zone_not_fqdn', '192.0.2.71'], + ['upper', zone.toUpperCase(), 'zone_case', '192.0.2.72'], + ]) { + const id = await world.db.insertRaw({ zone: storedZone, name, ttl: 300, content: JSON.stringify({ ip }), record_type: 'A' }); + await ui.openZone(zone); + expect((await ui.problems()).some((p) => p.code === code)).toBe(true); + await ui.editRecord({ name, type: 'A' }, { name, type: 'A', ttl: '300', fields: { ip } }, { expectStatus: 200 }); + expect((await world.db.recordById(id))?.zone).toBe(zone); + await threeWay(world, ui, zone, { name, type: 'A', ttl: 300, data: { ip } }, null, code); + } + const soa = baseline.find((row) => row.record_type === 'SOA')!; + const duplicateContent = JSON.stringify({ ...JSON.parse(soa.content!), ns: 'duplicate.example.net.' }); + const duplicateId = await world.db.insertRaw({ zone, name: '', ttl: soa.ttl, content: duplicateContent, record_type: 'SOA' }); + await ui.openZone(zone); + expect((await ui.problems()).some((p) => p.code === 'soa_multiple')).toBe(true); + await ui.deleteRecord({ name: '@', type: 'SOA', value: duplicateContent }, { expectStatus: 200 }); + expect(await world.db.recordById(duplicateId)).toBeUndefined(); + expect(await world.db.recordById(soa.id)).toBeDefined(); + await ui.expectRow({ name: '@', type: 'SOA' }); + await servedZone(world, zone); + const subId = await world.db.insertRaw({ zone, name: 'sub', ttl: soa.ttl, content: soa.content, record_type: 'SOA' }); + await ui.openZone(zone); + expect((await ui.problems()).some((p) => p.code === 'soa_not_apex')).toBe(true); + expect((await ui.problems()).some((p) => p.code === 'soa_multiple')).toBe(true); + await ui.deleteRecord({ name: '@', type: 'SOA' }, { expectStatus: 200 }); + expect(await world.db.recordById(soa.id)).toBeUndefined(); + const row = await ui.row({ name: 'sub', type: 'SOA' }); + await row.getByRole('button', { name: /^Edit / }).click(); + await expect(ui.page.locator('#soa-dialog')).toBeVisible(); + for (const [key, value] of Object.entries({ ns: `ns1.${zone}`, mbox: `hostmaster.${zone}`, ttl: '3600', refresh: '3600', retry: '600', expire: '604800', minttl: '300' })) await ui.page.fill(`#soa-${key}`, value); + const response = ui.page.waitForResponse((r) => r.request().method() === 'PUT' && new URL(r.url()).pathname.endsWith('/soa')); + await ui.page.locator('#soa-form button[type=submit]').click(); + expect((await response).status()).toBe(200); + await ui.settle(); + expect((await world.db.recordById(subId))?.name).toBe(''); + await ui.expectRow({ name: '@', type: 'SOA' }); + expect((await api.get(`${zp(zone)}/check`)).json.problems.filter((p: { severity: string }) => p.severity === 'error')).toEqual([]); + for (const original of baseline.filter((r) => r.id !== soa.id)) expect(await world.db.recordById(original.id)).toEqual(original); + await servedZone(world, zone); + }); + test('7. users and delegation: roles, zone visibility, revocation, promotion, deletion and the last active admin', async ({ world }) => { test.setTimeout(600_000); zoneB = `${world.unique('second-')}.core.test.`; @@ -990,7 +1040,7 @@ test.describe('core flow', () => { const zc = findAudit(await auditSince(world, cmark), 'zone_create', 201); const removed = JSON.stringify(parsedJson(ZONE_CREATE_DELEGATIONS_IN === 'before' ? zc.before_value : [zc.before_value, zc.after_value])); expect(removed, 'the creation audit row lists the removed delegations').toContain(user2.username); - if (REVIEW_FIXES) expect(JSON.stringify(parsedJson(zc.after_value)), 'removed delegations are not in after').not.toContain(`"username":"${user2.username}"`); + expect(JSON.stringify(parsedJson(zc.after_value)), 'removed delegations are not in after').not.toContain(`"username":"${user2.username}"`); await waitForZone(world.g, zoneD, { recorder: world.recorder }); await servedZone(world, zoneD); }); diff --git a/e2e/tests/operator.spec.ts b/e2e/tests/operator.spec.ts index c68a6e9..f6ca87c 100644 --- a/e2e/tests/operator.spec.ts +++ b/e2e/tests/operator.spec.ts @@ -60,7 +60,7 @@ test('a long operator session preserves state and audit invariants through mixed await threeWay(world, ui, zone, replacement, change, operation); model.set(current.name, replacement); } else { - expect([200, 204]).toContain((await ui.deleteRecord(match)).status); + expect((await ui.deleteRecord(match)).status).toBe(200); await threeWayGone(world, ui, zone, current, change, operation); model.delete(current.name); } diff --git a/e2e/tests/power.spec.ts b/e2e/tests/power.spec.ts index 58fcd96..38d01ab 100644 --- a/e2e/tests/power.spec.ts +++ b/e2e/tests/power.spec.ts @@ -4,9 +4,11 @@ import { test, expect } from '../harness/fixtures'; import { up, zp } from '../harness/api'; import { importApplyBody } from '../harness/decisions'; -import { waitForZone } from '../harness/dig'; +import { parseRR, waitForZone } from '../harness/dig'; +import { COREDNS_HOST } from '../harness/env'; +import { run } from '../harness/proc'; import { address, addAddress, createZone, restartWithSessions, zoneInput } from '../harness/personas'; -import { begin, storedRow, threeWay } from '../harness/verify'; +import { begin, servedZone, threeWay } from '../harness/verify'; test.use({ group: 'power' }); @@ -75,7 +77,16 @@ test('a power user operates a large installation, with restart and edit conflict await waitForZone(world.g, imports, { recorder: world.recorder }); await threeWay(world, first, imports, { ...address('load-0', ip), type: 'A' }, importChange, 'large import'); expect(await world.db.records(imports)).toHaveLength(1202); - await storedRow(world, imports, { ...address('load-1199', ip), type: 'A' }); + const imported = (await world.db.records(imports)).filter((row) => row.name.startsWith('load-')); + expect(imported).toHaveLength(1200); + const queries = imported.map((row) => `${row.name}.${imports} A`).join('\n') + '\n'; + const batch = await run('dig', [`@${COREDNS_HOST}`, '-p', String(world.g.dnsPort), '+norecurse', '+nocookie', '+time=3', '+tries=2', '+noall', '+answer', '-f', '-'], { input: queries, timeoutMs: 120_000 }); + expect(batch.code, batch.stderr).toBe(0); + const answers = batch.stdout.split('\n').filter((line) => line.trim() && !line.startsWith(';')).map(parseRR); + expect(answers.map((rr) => `${rr.name} ${rr.ttl} ${rr.type} ${rr.data}`).sort()).toEqual( + imported.map((row) => `${row.name}.${imports} 300 A ${ip}`).sort(), + ); + for (const row of imported) expect(row).toMatchObject({ zone: imports, ttl: 300, record_type: 'A', content: JSON.stringify({ ip }) }); expect((await api.get(`${zp(imports)}/check`)).json.problems).toEqual([]); }); @@ -100,4 +111,5 @@ test('a power user imports the supported types in one transaction', async ({ wor expect((await ui.importPreview(zone, entries.map(([n, t, v]) => `${n} 300 IN ${t} ${v}\n`).join(''), 'merge')).status).toBe(200); expect((await ui.importApply()).status).toBe(200); expect((await world.db.records(zone)).map((row) => row.record_type).sort()).toEqual(['A', 'AAAA', 'CAA', 'CNAME', 'MX', 'NS', 'NS', 'SOA', 'SRV', 'TXT']); + await servedZone(world, zone); }); diff --git a/fakedb_test.go b/fakedb_test.go index 56aedfa..6a021c7 100644 --- a/fakedb_test.go +++ b/fakedb_test.go @@ -39,6 +39,9 @@ type fdbState struct { commits int rollbacks int closeErr error + onBegin func() + onCommit func() error + onEnd func() } func (s *fdbState) record(query string, args []driver.NamedValue) fdbResponse { @@ -94,6 +97,9 @@ func (c *fdbConn) BeginTx(context.Context, driver.TxOptions) (driver.Tx, error) if c.s.beginErr != nil { return nil, c.s.beginErr } + if c.s.onBegin != nil { + c.s.onBegin() + } return &fdbTx{s: c.s}, nil } @@ -118,16 +124,27 @@ func (c *fdbConn) QueryContext(_ context.Context, query string, args []driver.Na type fdbTx struct{ s *fdbState } func (t *fdbTx) Commit() error { + if t.s.onEnd != nil { + defer t.s.onEnd() + } t.s.mu.Lock() defer t.s.mu.Unlock() if t.s.commitErr != nil { return t.s.commitErr } + if t.s.onCommit != nil { + if err := t.s.onCommit(); err != nil { + return err + } + } t.s.commits++ return nil } func (t *fdbTx) Rollback() error { + if t.s.onEnd != nil { + defer t.s.onEnd() + } t.s.mu.Lock() defer t.s.mu.Unlock() t.s.rollbacks++ diff --git a/handlers_api.go b/handlers_api.go index 5926ada..ecbdff6 100644 --- a/handlers_api.go +++ b/handlers_api.go @@ -1445,7 +1445,7 @@ func zoneAPIRecordResponse(row recordRow, warnings []zoneProblem, now time.Time, func (h zoneHandlers) createRecord(ctx context.Context, c *apiContext) (apiResponse, error) { var in zoneAPIRecordInput decodeErr := c.decodeJSON(&in) - return h.writeZone(ctx, c, false, func(w zoneAPIWrite) (apiResponse, error) { + response, err := h.writeZone(ctx, c, false, func(w zoneAPIWrite) (apiResponse, error) { if decodeErr != nil { return apiResponse{}, decodeErr } @@ -1466,6 +1466,10 @@ func (h zoneHandlers) createRecord(ctx context.Context, c *apiContext) (apiRespo c.Entry.RecordID = sql.NullInt64{Int64: row.ID, Valid: true} return zoneAPIRecordResponse(row, warnings, c.Now, http.StatusCreated), nil }) + if err != nil { + c.Entry.RecordID = sql.NullInt64{} + } + return response, err } func zoneAPIRequestedID(c *apiContext) (int64, error) { diff --git a/handlers_api_test.go b/handlers_api_test.go index 4d28d75..9a4be3e 100644 --- a/handlers_api_test.go +++ b/handlers_api_test.go @@ -709,73 +709,71 @@ func TestAuditRawJSONFallback(t *testing.T) { } type matrixPersona struct { - name string - token string + name string + username string + token string } type matrixRoute struct { method, path, body string + ifMatch int64 op string access string allowed int } func matrixRoutes() []matrixRoute { - out := []matrixRoute{ - {"GET", "/account", "", opAccountRead, accessSession, 200}, - {"PUT", "/account/password", `{"current":"` + testPassword + `","password":"another-password"}`, opPasswordChange, accessSession, 204}, - {"GET", "/zones/example.org./users", "", opDelegationList, accessAdmin, 200}, - {"PUT", "/zones/example.org./users/bob", "", opDelegationGrant, accessAdmin, 204}, - {"DELETE", "/zones/example.org./users/carol", "", opDelegationRevoke, accessAdmin, 204}, - {"GET", "/users", "", opUserList, accessAdmin, 200}, - {"POST", "/users", `{"username":"newbie","role":"user","password":"long-enough-pw"}`, opUserCreate, accessAdmin, 201}, - {"GET", "/users/bob", "", opUserRead, accessAdmin, 200}, - {"PUT", "/users/bob/role", `{"role":"admin"}`, opUserRole, accessAdmin, 204}, - {"PUT", "/users/bob/password", `{"password":"long-enough-pw"}`, opUserPassword, accessAdmin, 204}, - {"DELETE", "/users/bob", `{"confirm":"bob"}`, opUserDelete, accessAdmin, 204}, - {"GET", "/audit", "", opAuditRead, accessSession, 200}, + 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}, } - for _, r := range apiRoutes { - if !slices.Contains(zoneOperations, r.Operation) { - continue - } - path := strings.NewReplacer("{zone}", "example.org.", "{id}", "7").Replace(r.Path) - out = append(out, matrixRoute{r.Method, path, "", r.Operation, r.Access, 200}) - } - return out } func matrixHarness(t *testing.T) (*webHarness, []matrixPersona) { - h := newWebHarness(t) - h.withFakeZoneHandlers() - admin := h.user("admin", roleAdmin) - h.user("root", roleAdmin) - h.user("bob", roleUser) - carol := h.user("carol", roleUser) - delegated := h.user("alice", roleUser) - plain := h.user("dave", roleUser) + env := newMatrixEnv(t) + h := env.h promoted := h.user("pat", roleUser) demoted := h.user("dan", roleAdmin) - gone := h.user("gone", roleUser) - h.store.addZone(testZone) - for _, u := range []userRow{carol, delegated, promoted, gone} { - h.store.delegate(testZone, u) - } + h.store.delegate(testZone, promoted) personas := []matrixPersona{ - {"admin", h.login(admin)}, - {"delegated user", h.login(delegated)}, - {"user without delegation", h.login(plain)}, - {"promoted user", h.login(promoted)}, - {"demoted admin", h.login(demoted)}, - {"deleted user", h.login(gone)}, - {"no session", ""}, + {"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) - gone.DeletedAt = sql.NullTime{Time: webNow, Valid: true} - h.store.setUser(gone) return h, personas } @@ -799,11 +797,18 @@ func expectedMatrixStatus(persona string, r matrixRoute) (int, string) { } 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] - res := h.api(r.method, r.path, p.token, r.body) + 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) @@ -816,10 +821,10 @@ func TestAPIAuthorizationMatrix(t *testing.T) { continue } e := expectOneAudit(t, res, r.op, status) - if e.Actor == "" || !e.UserID.Valid || e.Origin != "192.0.2.10" { + 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.String != testZone || !e.Zone.Valid) && status != 403 { + 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) } } @@ -828,23 +833,21 @@ func TestAPIAuthorizationMatrix(t *testing.T) { func TestZoneNotFoundResponsesIdentical(t *testing.T) { h, personas := matrixHarness(t) - plain := personas[2].token - admin := personas[0].token - h.withHandlers(frameworkTestHandlers(map[string]apiHandler{ - opZoneRead: func(ctx context.Context, c *apiContext) (apiResponse, error) { - ok, err := c.Server.store.ZoneExists(ctx, c.Zone) - if err != nil || !ok { - return apiResponse{}, errZoneNotFound() - } - return okJSON(map[string]string{}), nil - }, - })) - a := h.api("GET", "/zones/example.org.", plain, "") - b := h.api("GET", "/zones/missing.org.", plain, "") - c := h.api("GET", "/zones/missing.org.", admin, "") - for _, r := range []webResult{a, b, c} { - if r.status != 404 || r.body != a.body || r.header.Get("Content-Type") != a.header.Get("Content-Type") || len(r.header) != len(a.header) { - t.Fatalf("%d %s %v", r.status, r.body, r.header) + 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) } } } diff --git a/webfake_test.go b/webfake_test.go index 4ff6c5f..1cf4a99 100644 --- a/webfake_test.go +++ b/webfake_test.go @@ -658,41 +658,6 @@ func (h *webHarness) withHandlers(handlers map[string]apiHandler) { h.handler = h.s.Handler() } -func (h *webHarness) withFakeZoneHandlers() { - handlers := frameworkAPIHandlers(h.s) - maps.Copy(handlers, fakeZoneHandlers()) - h.withHandlers(handlers) -} - -func fakeZoneHandlers() map[string]apiHandler { - out := map[string]apiHandler{} - for _, op := range zoneOperations { - kind := "" - for _, o := range auditOperations { - if o.Name == op { - kind = o.Kind - } - } - if kind == auditKindRead { - out[op] = func(ctx context.Context, c *apiContext) (apiResponse, error) { - return okJSON(map[string]string{"operation": op, "zone": c.Zone}), nil - } - continue - } - out[op] = func(ctx context.Context, c *apiContext) (apiResponse, error) { - err := c.Server.store.InTx(ctx, func(tx webTx) error { - c.Entry.After = []byte(`{"fake":true}`) - return c.writeChangeAuditWith(ctx, tx, http.StatusOK) - }) - if err != nil { - return apiResponse{}, err - } - return okJSON(map[string]string{"operation": op}), nil - } - } - return out -} - func (h *webHarness) user(username, role string) userRow { u := h.store.addUser(username, role) h.users[username] = u