From 99fa5de747d0ecdb4a23ee569f1633b48a545f3d Mon Sep 17 00:00:00 2001 From: Bryan Joshua Pedini Date: Wed, 18 Nov 2026 21:45:15 +0100 Subject: [PATCH] feat(auth): add argon2id passwords, sessions, rate limiter, authorization and audit builders - feat(auth): add argon2id passwords, sessions, rate limiter, authorization and audit builders - feat(cli): add check and audit commands - feat(api): add api framework, login, page routes and account, user, delegation and audit handlers - test(auth): cover passwords, sessions, rate limiter, authorization and audit builders - test(api): cover the api framework, sessions, client origin, headers and cross-origin refusal - test(api): cover account, user, delegation and audit handlers and the authorization matrix - test(ui): cover login, logout, page routes and the page authorization matrix --- audit.go | 340 ++++++++++++++++ audit_store.go | 13 +- audit_test.go | 221 ++++++++++ auth.go | 298 ++++++++++++++ auth_test.go | 313 ++++++++++++++ authz.go | 81 ++++ authz_test.go | 98 +++++ cli.go | 201 +++++---- cli_test.go | 184 ++++++++- go.mod | 3 +- go.sum | 6 +- handlers_api.go | 723 +++++++++++++++++++++++++++++++++ handlers_api_test.go | 858 +++++++++++++++++++++++++++++++++++++++ handlers_pages.go | 319 +++++++++++++++ handlers_session_test.go | 446 ++++++++++++++++++++ integration_cli_test.go | 21 +- main.go | 4 +- middleware.go | 699 +++++++++++++++++++++++++++++++ middleware_test.go | 721 ++++++++++++++++++++++++++++++++ ratelimit.go | 155 +++++++ ratelimit_test.go | 173 ++++++++ routes.go | 4 +- stores_test.go | 9 +- stub_contracts.go | 113 ------ type_webserver.go | 22 + type_webserver_test.go | 6 +- user_store.go | 24 -- webfake_test.go | 779 +++++++++++++++++++++++++++++++++++ 28 files changed, 6591 insertions(+), 243 deletions(-) create mode 100644 audit.go create mode 100644 audit_test.go create mode 100644 auth.go create mode 100644 auth_test.go create mode 100644 authz.go create mode 100644 authz_test.go create mode 100644 handlers_session_test.go create mode 100644 middleware.go create mode 100644 middleware_test.go create mode 100644 ratelimit.go create mode 100644 ratelimit_test.go delete mode 100644 stub_contracts.go create mode 100644 webfake_test.go diff --git a/audit.go b/audit.go new file mode 100644 index 0000000..b426551 --- /dev/null +++ b/audit.go @@ -0,0 +1,340 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright (C) 2026 Bryan Joshua Pedini + +package main + +import ( + "database/sql" + "encoding/json" + "slices" + "strings" + "time" +) + +type auditEntry struct { + ID int64 + Time time.Time + UserID sql.NullInt64 + Actor string + Origin string + Operation string + Status sql.NullInt64 + Error sql.NullString + Zone sql.NullString + RecordID sql.NullInt64 + TargetUserID sql.NullInt64 + Before []byte + After []byte +} + +const ( + opLogin = "login" + opLogout = "logout" + opAccountRead = "account_read" + opPasswordChange = "password_change" + opZoneList = "zone_list" + opZoneRead = "zone_read" + opZoneCreate = "zone_create" + opZoneDelete = "zone_delete" + opRecordList = "record_list" + opRecordCreate = "record_create" + opRecordUpdate = "record_update" + opRecordDelete = "record_delete" + opRecordBulkDelete = "record_bulk_delete" + opSOAUpdate = "soa_update" + opZoneCheck = "zone_check" + opCheckAll = "check_all" + opZoneExport = "zone_export" + opZoneImportPreview = "zone_import_preview" + opZoneImport = "zone_import" + opDelegationList = "delegation_list" + opDelegationGrant = "delegation_grant" + opDelegationRevoke = "delegation_revoke" + opUserList = "user_list" + opUserRead = "user_read" + opUserCreate = "user_create" + opUserRole = "user_role" + opUserPassword = "user_password" + opUserDelete = "user_delete" + opAuditRead = "audit_read" +) + +const ( + cliActor = reservedUsername + cliOrigin = "local" + auditTimeLayout = "2006-01-02T15:04:05.000000Z" + defaultBodyLimit = 64 << 10 + importBodyLimit = 2 << 20 + apiPrefix = "/api/v1" + auditDefaultLimit = 50 + auditMaxLimit = 200 +) + +type auditOperation struct { + Name string + Kind string +} + +var auditOperations = []auditOperation{ + {opAccountRead, auditKindRead}, + {opLogin, auditKindChange}, + {opLogout, auditKindChange}, + {opPasswordChange, auditKindChange}, + {opZoneList, auditKindRead}, + {opZoneRead, auditKindRead}, + {opZoneCreate, auditKindChange}, + {opZoneDelete, auditKindChange}, + {opRecordList, auditKindRead}, + {opRecordCreate, auditKindChange}, + {opRecordUpdate, auditKindChange}, + {opRecordDelete, auditKindChange}, + {opRecordBulkDelete, auditKindChange}, + {opSOAUpdate, auditKindChange}, + {opZoneCheck, auditKindRead}, + {opCheckAll, auditKindRead}, + {opZoneExport, auditKindRead}, + {opZoneImportPreview, auditKindRead}, + {opZoneImport, auditKindChange}, + {opDelegationList, auditKindRead}, + {opDelegationGrant, auditKindChange}, + {opDelegationRevoke, auditKindChange}, + {opUserList, auditKindRead}, + {opUserRead, auditKindRead}, + {opUserCreate, auditKindChange}, + {opUserRole, auditKindChange}, + {opUserPassword, auditKindChange}, + {opUserDelete, auditKindChange}, + {opAuditRead, auditKindRead}, +} + +var auditChangeOperations = operationsOfKind(auditKindChange) + +var zoneOperations = []string{ + opZoneList, opZoneRead, opZoneCreate, opZoneDelete, + opRecordList, opRecordCreate, opRecordUpdate, opRecordDelete, opRecordBulkDelete, opSOAUpdate, + opZoneCheck, opCheckAll, opZoneExport, opZoneImportPreview, opZoneImport, +} + +func operationsOfKind(kind string) []string { + var out []string + for _, o := range auditOperations { + if o.Kind == kind { + out = append(out, o.Name) + } + } + return out +} + +func knownOperation(name string) bool { + return slices.ContainsFunc(auditOperations, func(o auditOperation) bool { return o.Name == name }) +} + +type apiRoute struct { + Method string + Path string + Operation string + Access string + BodyLimit int64 +} + +var apiRoutes = []apiRoute{ + {"GET", "/account", opAccountRead, accessSession, defaultBodyLimit}, + {"PUT", "/account/password", opPasswordChange, accessSession, defaultBodyLimit}, + {"GET", "/zones", opZoneList, accessSession, defaultBodyLimit}, + {"POST", "/zones", opZoneCreate, accessAdmin, defaultBodyLimit}, + {"GET", "/zones/{zone}", opZoneRead, accessZone, defaultBodyLimit}, + {"DELETE", "/zones/{zone}", opZoneDelete, accessAdmin, defaultBodyLimit}, + {"GET", "/zones/{zone}/records", opRecordList, accessZone, defaultBodyLimit}, + {"POST", "/zones/{zone}/records", opRecordCreate, accessZone, defaultBodyLimit}, + {"PUT", "/zones/{zone}/records/{id}", opRecordUpdate, accessZone, defaultBodyLimit}, + {"DELETE", "/zones/{zone}/records/{id}", opRecordDelete, accessZone, defaultBodyLimit}, + {"POST", "/zones/{zone}/records/delete", opRecordBulkDelete, accessZone, defaultBodyLimit}, + {"PUT", "/zones/{zone}/soa", opSOAUpdate, accessZone, defaultBodyLimit}, + {"GET", "/zones/{zone}/check", opZoneCheck, accessZone, defaultBodyLimit}, + {"GET", "/check", opCheckAll, accessSession, defaultBodyLimit}, + {"GET", "/zones/{zone}/export", opZoneExport, accessZone, defaultBodyLimit}, + {"POST", "/zones/{zone}/import/preview", opZoneImportPreview, accessZone, importBodyLimit}, + {"POST", "/zones/{zone}/import/apply", opZoneImport, accessZone, importBodyLimit}, + {"GET", "/zones/{zone}/users", opDelegationList, accessAdmin, defaultBodyLimit}, + {"PUT", "/zones/{zone}/users/{username}", opDelegationGrant, accessAdmin, defaultBodyLimit}, + {"DELETE", "/zones/{zone}/users/{username}", opDelegationRevoke, accessAdmin, defaultBodyLimit}, + {"GET", "/users", opUserList, accessAdmin, defaultBodyLimit}, + {"POST", "/users", opUserCreate, accessAdmin, defaultBodyLimit}, + {"GET", "/users/{username}", opUserRead, accessAdmin, defaultBodyLimit}, + {"PUT", "/users/{username}/role", opUserRole, accessAdmin, defaultBodyLimit}, + {"PUT", "/users/{username}/password", opUserPassword, accessAdmin, defaultBodyLimit}, + {"DELETE", "/users/{username}", opUserDelete, accessAdmin, defaultBodyLimit}, + {"GET", "/audit", opAuditRead, accessSession, defaultBodyLimit}, +} + +type pageRoute struct { + Method string + Path string + Access string + Page string +} + +var pageRoutes = []pageRoute{ + {"GET", "/login", accessNone, "login"}, + {"POST", "/login", accessNone, ""}, + {"POST", "/logout", accessSession, ""}, + {"GET", "/", accessSession, "zones"}, + {"GET", "/zones/{zone}", accessZone, "zone"}, + {"GET", "/zones/{zone}/import", accessZone, "import"}, + {"GET", "/audit", accessSession, "audit"}, + {"GET", "/account", accessSession, "account"}, + {"GET", "/users", accessAdmin, "users"}, + {"GET", "/users/{username}", accessAdmin, "user"}, + {"GET", "/version", accessNone, ""}, + {"GET", "/health", accessNone, ""}, + {"GET", "/static/{hash}/...", accessNone, ""}, +} + +func routeHasZone(path string) bool { + return strings.Contains(path, "{zone}") +} + +func apiAuditEntry(now time.Time, p principal, origin, operation, zone string) auditEntry { + e := auditEntry{ + Time: now, + UserID: sql.NullInt64{Int64: p.User.ID, Valid: true}, + Actor: p.User.Username, + Origin: origin, + Operation: operation, + } + if zone != "" { + e.Zone = sql.NullString{String: zone, Valid: true} + } + return e +} + +func loginActor(submitted string) string { + return printableText(submitted, auditMaxActorRunes) +} + +func loginAuditEntry(now time.Time, operation, submitted string, user *userRow, origin string) auditEntry { + e := auditEntry{Time: now, Actor: loginActor(submitted), Origin: origin, Operation: operation} + if user != nil { + e.UserID = sql.NullInt64{Int64: user.ID, Valid: true} + } + return e +} + +func finishAuditEntry(e *auditEntry, status int, message string) { + e.Status = sql.NullInt64{Int64: int64(status), Valid: true} + e.Error = sql.NullString{} + if status >= 400 { + e.Error = sql.NullString{String: message, Valid: true} + } +} + +func cliAuditEntry(now time.Time, operation string, target userRow, before, after *userRow) auditEntry { + e := auditEntry{ + Time: now, + Actor: cliActor, + Origin: cliOrigin, + Operation: operation, + TargetUserID: sql.NullInt64{Int64: target.ID, Valid: true}, + } + if before != nil { + e.Before = auditUserJSON(*before) + } + if after != nil { + e.After = auditUserJSON(*after) + } + return e +} + +func formatAuditTime(t time.Time) string { + return t.UTC().Format(auditTimeLayout) +} + +func formatAuditNullTime(t sql.NullTime) *string { + if !t.Valid { + return nil + } + s := formatAuditTime(t.Time) + return &s +} + +type auditUserValue struct { + ID int64 `json:"id"` + Username string `json:"username"` + Role string `json:"role"` + CreatedAt string `json:"created_at"` + DeletedAt *string `json:"deleted_at"` +} + +type auditRecordValue struct { + ID int64 `json:"id"` + Zone string `json:"zone"` + Name string `json:"name"` + TTL *int64 `json:"ttl"` + RecordType string `json:"record_type"` + Content *string `json:"content"` +} + +type auditDelegationValue struct { + Zone string `json:"zone"` + Username string `json:"username"` +} + +func mustAuditJSON(v any) []byte { + b, _ := json.Marshal(v) + return b +} + +func auditUserValueOf(u userRow) auditUserValue { + return auditUserValue{ID: u.ID, Username: u.Username, Role: u.Role, CreatedAt: formatAuditTime(u.CreatedAt), DeletedAt: formatAuditNullTime(u.DeletedAt)} +} + +func auditUserJSON(u userRow) []byte { + return mustAuditJSON(auditUserValueOf(u)) +} + +func auditRecordValueOf(r recordRow) auditRecordValue { + v := auditRecordValue{ID: r.ID, Zone: r.Zone, Name: r.Name, RecordType: r.RecordType} + if r.TTL.Valid { + ttl := r.TTL.Int64 + v.TTL = &ttl + } + if r.Content.Valid { + content := r.Content.String + v.Content = &content + } + return v +} + +func auditRecordJSON(r recordRow) []byte { + return mustAuditJSON(auditRecordValueOf(r)) +} + +func auditRecordsJSON(rows []recordRow) []byte { + values := make([]auditRecordValue, 0, len(rows)) + for _, r := range rows { + values = append(values, auditRecordValueOf(r)) + } + return mustAuditJSON(values) +} + +func auditDelegationJSON(zone, username string) []byte { + return mustAuditJSON(auditDelegationValue{Zone: zone, Username: username}) +} + +func auditDelegationsJSON(rows []delegationRow) []byte { + values := make([]auditDelegationValue, 0, len(rows)) + for _, d := range rows { + values = append(values, auditDelegationValue{Zone: d.Zone, Username: d.Username}) + } + return mustAuditJSON(values) +} + +func auditVisibleTo(p principal, e auditEntry, delegated map[string]bool) bool { + if p.isAdmin() { + return true + } + if e.UserID.Valid && e.UserID.Int64 == p.User.ID { + return true + } + return e.Zone.Valid && delegated[e.Zone.String] +} diff --git a/audit_store.go b/audit_store.go index 484694e..4ef2303 100644 --- a/audit_store.go +++ b/audit_store.go @@ -23,15 +23,6 @@ const ( auditMaxListLimit = 1000 ) -var auditStoreChangeOperations = []string{ - "login", "logout", "password_change", - "zone_create", "zone_delete", - "record_create", "record_update", "record_delete", "record_bulk_delete", "soa_update", - "zone_import", - "delegation_grant", "delegation_revoke", - "user_create", "user_role", "user_password", "user_delete", -} - type auditFilter struct { Zone string Actor string @@ -127,9 +118,9 @@ func auditFilterSQL(f auditFilter) (string, []any, error) { if f.Kind == auditKindRead { op = "NOT IN" } - marks := strings.TrimSuffix(strings.Repeat("?, ", len(auditStoreChangeOperations)), ", ") + marks := strings.TrimSuffix(strings.Repeat("?, ", len(auditChangeOperations)), ", ") conds = append(conds, "a.`operation` "+op+" ("+marks+")") - for _, o := range auditStoreChangeOperations { + for _, o := range auditChangeOperations { args = append(args, o) } default: diff --git a/audit_test.go b/audit_test.go new file mode 100644 index 0000000..0c727e4 --- /dev/null +++ b/audit_test.go @@ -0,0 +1,221 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright (C) 2026 Bryan Joshua Pedini + +package main + +import ( + "database/sql" + "slices" + "strings" + "testing" + "time" +) + +var specRoutes = []string{ + "GET /account session account_read", + "PUT /account/password session password_change", + "GET /zones session zone_list", + "POST /zones admin zone_create", + "GET /zones/{zone} zone zone_read", + "DELETE /zones/{zone} admin zone_delete", + "GET /zones/{zone}/records zone record_list", + "POST /zones/{zone}/records zone record_create", + "PUT /zones/{zone}/records/{id} zone record_update", + "DELETE /zones/{zone}/records/{id} zone record_delete", + "POST /zones/{zone}/records/delete zone record_bulk_delete", + "PUT /zones/{zone}/soa zone soa_update", + "GET /zones/{zone}/check zone zone_check", + "GET /check session check_all", + "GET /zones/{zone}/export zone zone_export", + "POST /zones/{zone}/import/preview zone zone_import_preview", + "POST /zones/{zone}/import/apply zone zone_import", + "GET /zones/{zone}/users admin delegation_list", + "PUT /zones/{zone}/users/{username} admin delegation_grant", + "DELETE /zones/{zone}/users/{username} admin delegation_revoke", + "GET /users admin user_list", + "POST /users admin user_create", + "GET /users/{username} admin user_read", + "PUT /users/{username}/role admin user_role", + "PUT /users/{username}/password admin user_password", + "DELETE /users/{username} admin user_delete", + "GET /audit session audit_read", +} + +func TestRouteTableMatchesSpec(t *testing.T) { + var got []string + seen := map[string]bool{} + for _, r := range apiRoutes { + got = append(got, r.Method+" "+r.Path+" "+r.Access+" "+r.Operation) + if seen[r.Operation] { + t.Errorf("operation %s mapped twice", r.Operation) + } + seen[r.Operation] = true + want := int64(defaultBodyLimit) + if r.Operation == opZoneImport || r.Operation == opZoneImportPreview { + want = importBodyLimit + } + if r.BodyLimit != want { + t.Errorf("%s body limit %d", r.Operation, r.BodyLimit) + } + } + if !slices.Equal(got, specRoutes) { + t.Fatalf("route table differs:\n%s", strings.Join(got, "\n")) + } + if defaultBodyLimit != 65536 || importBodyLimit != 2097152 { + t.Fatal("body limits") + } +} + +func TestOperationTable(t *testing.T) { + reads := []string{"account_read", "zone_list", "zone_read", "record_list", "zone_check", "check_all", "zone_export", "zone_import_preview", "delegation_list", "user_list", "user_read", "audit_read"} + changes := []string{"login", "logout", "password_change", "zone_create", "zone_delete", "record_create", "record_update", "record_delete", "record_bulk_delete", "soa_update", "zone_import", "delegation_grant", "delegation_revoke", "user_create", "user_role", "user_password", "user_delete"} + gotReads, gotChanges := operationsOfKind(auditKindRead), operationsOfKind(auditKindChange) + slices.Sort(gotReads) + slices.Sort(gotChanges) + slices.Sort(reads) + slices.Sort(changes) + if !slices.Equal(gotReads, reads) || !slices.Equal(gotChanges, changes) { + t.Fatal(gotReads, gotChanges) + } + if len(auditChangeOperations) != len(changes) { + t.Fatal(auditChangeOperations) + } + for _, op := range append(reads, changes...) { + if !knownOperation(op) || len(op) > auditMaxOperationLen { + t.Errorf("%s", op) + } + } + if knownOperation("drop_table") || knownOperation("") { + t.Fatal("unknown operation accepted") + } + for _, r := range apiRoutes { + if !knownOperation(r.Operation) { + t.Errorf("route operation %s unknown", r.Operation) + } + } + for _, op := range zoneOperations { + if !knownOperation(op) { + t.Errorf("zone operation %s unknown", op) + } + } + if len(zoneOperations) != 15 { + t.Fatal(len(zoneOperations)) + } +} + +func TestPageTable(t *testing.T) { + want := []string{ + "GET /login none", "POST /login none", "POST /logout session", "GET / session", "GET /zones/{zone} zone", + "GET /zones/{zone}/import zone", "GET /audit session", "GET /account session", "GET /users admin", + "GET /users/{username} admin", "GET /version none", "GET /health none", "GET /static/{hash}/... none", + } + var got []string + for _, r := range pageRoutes { + got = append(got, r.Method+" "+r.Path+" "+r.Access) + } + if !slices.Equal(got, want) { + t.Fatal(got) + } + if !routeHasZone("/zones/{zone}/import") || routeHasZone("/users/{username}") { + t.Fatal("routeHasZone") + } +} + +func TestAPIAuditEntry(t *testing.T) { + p := principal{User: userRow{ID: 4, Username: "alice", Role: roleUser}} + e := apiAuditEntry(webNow, p, "192.0.2.1", opZoneRead, testZone) + if !e.Time.Equal(webNow) || e.UserID != (sql.NullInt64{Int64: 4, Valid: true}) || e.Actor != "alice" || e.Origin != "192.0.2.1" || e.Operation != opZoneRead || e.Zone.String != testZone || !e.Zone.Valid { + t.Fatalf("%+v", e) + } + if e := apiAuditEntry(webNow, p, "o", opAccountRead, ""); e.Zone.Valid || e.Status.Valid || e.Before != nil { + t.Fatalf("%+v", e) + } + finishAuditEntry(&e, 422, "invalid ttl") + if e.Status.Int64 != 422 || e.Error != (sql.NullString{String: "invalid ttl", Valid: true}) { + t.Fatalf("%+v", e) + } + finishAuditEntry(&e, 399, "ignored") + if e.Status.Int64 != 399 || e.Error.Valid { + t.Fatalf("%+v", e) + } +} + +func TestLoginAuditEntry(t *testing.T) { + e := loginAuditEntry(webNow, opLogin, "evil\x00\nname"+strings.Repeat("ü", 80), nil, "198.51.100.1") + if e.UserID.Valid || e.Actor != "evil name"+strings.Repeat("ü", 54) || len([]rune(e.Actor)) != 64 || e.Origin != "198.51.100.1" || e.Operation != opLogin { + t.Fatalf("%+v", e) + } + u := &userRow{ID: 9, Username: "bob"} + if e := loginAuditEntry(webNow, opLogin, "bob", u, "o"); e.UserID.Int64 != 9 || !e.UserID.Valid || e.Actor != "bob" { + t.Fatalf("%+v", e) + } +} + +func TestCLIAuditEntry(t *testing.T) { + created := time.Date(2026, 1, 2, 3, 4, 5, 6000, time.UTC) + u := userRow{ID: 3, Username: "bob", Role: roleUser, PasswordHash: "$argon2id$secret", CreatedAt: created} + after := u + after.Role = roleAdmin + e := cliAuditEntry(webNow, opUserRole, u, &u, &after) + if e.UserID.Valid || e.Actor != "cli" || e.Origin != "local" || e.Status.Valid || e.Error.Valid || e.TargetUserID.Int64 != 3 || e.Operation != opUserRole { + t.Fatalf("%+v", e) + } + if string(e.Before) != `{"id":3,"username":"bob","role":"user","created_at":"2026-01-02T03:04:05.000006Z","deleted_at":null}` || + string(e.After) != `{"id":3,"username":"bob","role":"admin","created_at":"2026-01-02T03:04:05.000006Z","deleted_at":null}` { + t.Fatal(string(e.Before), string(e.After)) + } + if e := cliAuditEntry(webNow, opUserCreate, u, nil, &u); e.Before != nil || e.After == nil { + t.Fatal("create entry") + } + if strings.Contains(string(e.Before)+string(e.After), "secret") { + t.Fatal("hash in audit") + } +} + +func TestSnapshotBuilders(t *testing.T) { + r := recordRow{ID: 5, Zone: testZone, Name: "www", TTL: sql.NullInt64{Int64: 300, Valid: true}, Content: sql.NullString{String: `{"ip":"192.0.2.1"}`, Valid: true}, RecordType: "A"} + if got := string(auditRecordJSON(r)); got != `{"id":5,"zone":"example.org.","name":"www","ttl":300,"record_type":"A","content":"{\"ip\":\"192.0.2.1\"}"}` { + t.Fatal(got) + } + broken := recordRow{ID: 6, Zone: testZone, Name: "", RecordType: "a"} + if got := string(auditRecordsJSON([]recordRow{broken})); got != `[{"id":6,"zone":"example.org.","name":"","ttl":null,"record_type":"a","content":null}]` { + t.Fatal(got) + } + if got := string(auditRecordsJSON(nil)); got != `[]` { + t.Fatal(got) + } + if got := string(auditDelegationJSON(testZone, "bob")); got != `{"zone":"example.org.","username":"bob"}` { + t.Fatal(got) + } + if got := string(auditDelegationsJSON([]delegationRow{{Zone: testZone, Username: "a", UserID: 1}, {Zone: testZone, Username: "b"}})); got != `[{"zone":"example.org.","username":"a"},{"zone":"example.org.","username":"b"}]` { + t.Fatal(got) + } + deleted := userRow{ID: 1, Username: "x", Role: roleUser, CreatedAt: webNow, DeletedAt: sql.NullTime{Time: webNow.Add(time.Microsecond), Valid: true}} + if got := string(auditUserJSON(deleted)); got != `{"id":1,"username":"x","role":"user","created_at":"2026-11-18T12:00:00.000000Z","deleted_at":"2026-11-18T12:00:00.000001Z"}` { + t.Fatal(got) + } + if formatAuditNullTime(sql.NullTime{}) != nil { + t.Fatal("null time") + } +} + +func TestAuditVisibility(t *testing.T) { + admin := principal{User: userRow{ID: 1, Role: roleAdmin}} + user := principal{User: userRow{ID: 2, Role: roleUser}} + delegated := map[string]bool{testZone: true} + own := auditEntry{UserID: sql.NullInt64{Int64: 2, Valid: true}, Zone: sql.NullString{String: otherZone, Valid: true}} + zoneRow := auditEntry{UserID: sql.NullInt64{Int64: 3, Valid: true}, Zone: sql.NullString{String: testZone, Valid: true}} + foreign := auditEntry{UserID: sql.NullInt64{Int64: 3, Valid: true}, Zone: sql.NullString{String: otherZone, Valid: true}} + cli := auditEntry{Actor: "cli"} + for _, e := range []auditEntry{own, zoneRow, foreign, cli} { + if !auditVisibleTo(admin, e, nil) { + t.Fatal("admin sees everything") + } + } + if !auditVisibleTo(user, own, delegated) || !auditVisibleTo(user, zoneRow, delegated) { + t.Fatal("user rows hidden") + } + if auditVisibleTo(user, foreign, delegated) || auditVisibleTo(user, cli, delegated) || auditVisibleTo(user, zoneRow, nil) { + t.Fatal("foreign rows visible") + } +} diff --git a/auth.go b/auth.go new file mode 100644 index 0000000..700515b --- /dev/null +++ b/auth.go @@ -0,0 +1,298 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright (C) 2026 Bryan Joshua Pedini + +package main + +import ( + "crypto/rand" + "crypto/sha256" + "crypto/subtle" + "encoding/base64" + "errors" + "fmt" + "io" + "net/http" + "regexp" + "strconv" + "strings" + "time" + "unicode" + "unicode/utf8" + + "golang.org/x/crypto/argon2" +) + +const ( + argon2Memory = 64 * 1024 + argon2Iterations = 3 + argon2Parallelism = 2 + argon2SaltBytes = 16 + argon2KeyBytes = 32 + maxConcurrentHashes = 4 + phcMaxMemory = 1 << 20 + phcMaxIterations = 64 + phcMaxParallelism = 16 + phcMinBytes = 8 + phcMaxBytes = 64 + sessionTokenBytes = 32 + sessionCookieName = "coredns_webui_session" + sessionTouchInterval = time.Minute + minPasswordBytes = 12 + maxPasswordBytes = 256 + maxUserAgentRunes = 255 + reservedUsername = "cli" + roleAdmin = "admin" + roleUser = "user" +) + +const dummyPasswordHash = "$argon2id$v=19$m=65536,t=3,p=2$c2VjdXJpdHktZHVtbXktMQ$2v9Q3n6Pq0m0V4bJxv1q8kP0cQ8Zr5u3m2b0YQ8d9xE" + +var usernamePattern = regexp.MustCompile(`^[a-z0-9][a-z0-9._-]{0,63}$`) + +var hashSlots = make(chan struct{}, maxConcurrentHashes) + +var ( + errInvalidPasswordHash = errors.New("invalid password hash") + errNoSession = errors.New("no valid session") +) + +type phcHash struct { + memory uint32 + iterations uint32 + parallelism uint8 + salt []byte + key []byte +} + +var dummyPHC = mustParsePHC(dummyPasswordHash) + +func mustParsePHC(encoded string) phcHash { + h, err := parsePHC(encoded) + if err != nil { + panic(err) + } + return h +} + +func argon2Key(password string, h phcHash) []byte { + hashSlots <- struct{}{} + defer func() { <-hashSlots }() + return argon2.IDKey([]byte(password), h.salt, h.iterations, h.memory, h.parallelism, uint32(len(h.key))) +} + +func hashPassword(password string) (string, error) { + return hashPasswordWith(rand.Reader, password) +} + +func hashPasswordWith(random io.Reader, password string) (string, error) { + h := phcHash{ + memory: argon2Memory, + iterations: argon2Iterations, + parallelism: argon2Parallelism, + salt: make([]byte, argon2SaltBytes), + key: make([]byte, argon2KeyBytes), + } + if _, err := io.ReadFull(random, h.salt); err != nil { + return "", fmt.Errorf("password salt: %w", err) + } + h.key = argon2Key(password, h) + return encodePHC(h), nil +} + +func encodePHC(h phcHash) string { + return fmt.Sprintf("$argon2id$v=%d$m=%d,t=%d,p=%d$%s$%s", argon2.Version, h.memory, h.iterations, h.parallelism, + base64.RawStdEncoding.EncodeToString(h.salt), base64.RawStdEncoding.EncodeToString(h.key)) +} + +func parsePHCParam(s, name string, max uint64) (uint64, error) { + v, ok := strings.CutPrefix(s, name+"=") + if !ok || v == "" || strings.Trim(v, "0123456789") != "" || (len(v) > 1 && v[0] == '0') { + return 0, errInvalidPasswordHash + } + n, err := strconv.ParseUint(v, 10, 32) + if err != nil || n == 0 || n > max { + return 0, errInvalidPasswordHash + } + return n, nil +} + +func parsePHCBytes(s string) ([]byte, error) { + b, err := base64.RawStdEncoding.Strict().DecodeString(s) + if err != nil || len(b) < phcMinBytes || len(b) > phcMaxBytes { + return nil, errInvalidPasswordHash + } + return b, nil +} + +func parsePHC(encoded string) (phcHash, error) { + parts := strings.Split(encoded, "$") + if len(parts) != 6 || parts[0] != "" || parts[1] != "argon2id" || parts[2] != "v="+strconv.Itoa(argon2.Version) { + return phcHash{}, errInvalidPasswordHash + } + params := strings.Split(parts[3], ",") + if len(params) != 3 { + return phcHash{}, errInvalidPasswordHash + } + m, err := parsePHCParam(params[0], "m", phcMaxMemory) + if err != nil { + return phcHash{}, err + } + t, err := parsePHCParam(params[1], "t", phcMaxIterations) + if err != nil { + return phcHash{}, err + } + p, err := parsePHCParam(params[2], "p", phcMaxParallelism) + if err != nil { + return phcHash{}, err + } + if m < 8*p { + return phcHash{}, errInvalidPasswordHash + } + salt, err := parsePHCBytes(parts[4]) + if err != nil { + return phcHash{}, err + } + key, err := parsePHCBytes(parts[5]) + if err != nil { + return phcHash{}, err + } + return phcHash{memory: uint32(m), iterations: uint32(t), parallelism: uint8(p), salt: salt, key: key}, nil +} + +func verifyPassword(password, encoded string) bool { + h, err := parsePHC(encoded) + valid := err == nil + if !valid { + h = dummyPHC + } + key := argon2Key(password, h) + return subtle.ConstantTimeCompare(key, h.key) == 1 && valid +} + +type passwordVerifier func(password, encoded string) bool + +func verifyLogin(verify passwordVerifier, user *userRow, password string) bool { + encoded := dummyPasswordHash + active := user != nil && !user.DeletedAt.Valid + if active { + encoded = user.PasswordHash + } + match := verify(password, encoded) + return active && match +} + +func validUsernameSyntax(username string) bool { + return usernamePattern.MatchString(username) +} + +func checkUsername(username string) error { + if !validUsernameSyntax(username) { + return errors.New("username must be 1 to 64 characters of lowercase letters, digits, dots, underscores and hyphens, starting with a letter or digit") + } + if username == reservedUsername { + return errors.New("username is reserved") + } + return nil +} + +func checkPasswordRules(password string) error { + if len(password) < minPasswordBytes || len(password) > maxPasswordBytes { + return fmt.Errorf("password must be %d to %d bytes", minPasswordBytes, maxPasswordBytes) + } + if !utf8.ValidString(password) { + return errors.New("password must be valid UTF-8") + } + for _, r := range password { + if unicode.IsControl(r) { + return errors.New("password must not contain control characters") + } + } + return nil +} + +func validRole(role string) bool { + return role == roleAdmin || role == roleUser +} + +func newSessionToken(random io.Reader) (string, []byte, error) { + raw := make([]byte, sessionTokenBytes) + if _, err := io.ReadFull(random, raw); err != nil { + return "", nil, fmt.Errorf("session token: %w", err) + } + token := base64.RawURLEncoding.EncodeToString(raw) + return token, sessionTokenHash(token), nil +} + +func sessionTokenHash(token string) []byte { + sum := sha256.Sum256([]byte(token)) + return sum[:] +} + +func validSessionToken(token string) bool { + if len(token) != base64.RawURLEncoding.EncodedLen(sessionTokenBytes) { + return false + } + raw, err := base64.RawURLEncoding.Strict().DecodeString(token) + return err == nil && len(raw) == sessionTokenBytes +} + +func sessionValid(s sessionRow, u userRow, now time.Time, idle, maxAge time.Duration) bool { + return !u.DeletedAt.Valid && now.Before(s.ExpiresAt) && now.Sub(s.CreatedAt) < maxAge && now.Sub(s.LastSeenAt) < idle +} + +func sessionTouchDue(s sessionRow, now time.Time) bool { + return now.Sub(s.LastSeenAt) >= sessionTouchInterval +} + +func newSessionRow(tokenHash []byte, userID int64, now time.Time, maxAge time.Duration, origin, userAgent string) sessionRow { + return sessionRow{ + TokenHash: tokenHash, + UserID: userID, + CreatedAt: now, + LastSeenAt: now, + ExpiresAt: now.Add(maxAge), + Origin: origin, + UserAgent: printableText(userAgent, maxUserAgentRunes), + } +} + +func sessionCookie(token string, secure bool) *http.Cookie { + return &http.Cookie{ + Name: sessionCookieName, + Value: token, + Path: "/", + HttpOnly: true, + Secure: secure, + SameSite: http.SameSiteStrictMode, + } +} + +func expiredSessionCookie(secure bool) *http.Cookie { + c := sessionCookie("", secure) + c.MaxAge = -1 + return c +} + +func requestSessionToken(r *http.Request) (string, bool) { + c, err := r.Cookie(sessionCookieName) + if err != nil || !validSessionToken(c.Value) { + return "", false + } + return c.Value, true +} + +func printableText(s string, maxRunes int) string { + var b strings.Builder + n := 0 + for i, r := range s { + if maxRunes >= 0 && n == maxRunes { + break + } + if (r == utf8.RuneError && !strings.HasPrefix(s[i:], "�")) || !unicode.IsPrint(r) { + r = ' ' + } + b.WriteRune(r) + n++ + } + return b.String() +} diff --git a/auth_test.go b/auth_test.go new file mode 100644 index 0000000..48440d0 --- /dev/null +++ b/auth_test.go @@ -0,0 +1,313 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright (C) 2026 Bryan Joshua Pedini + +package main + +import ( + "bytes" + "crypto/sha256" + "database/sql" + "encoding/base64" + "errors" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" +) + +func TestHashAndVerifyPassword(t *testing.T) { + salt := bytes.Repeat([]byte{7}, 16) + h, err := hashPasswordWith(bytes.NewReader(salt), "correct horse battery") + if err != nil { + t.Fatal(err) + } + want := "$argon2id$v=19$m=65536,t=3,p=2$" + base64.RawStdEncoding.EncodeToString(salt) + "$" + if !strings.HasPrefix(h, want) || len(h) != len(want)+43 { + t.Fatalf("hash %q", h) + } + parsed, err := parsePHC(h) + if err != nil || parsed.memory != argon2Memory || parsed.iterations != argon2Iterations || parsed.parallelism != argon2Parallelism || len(parsed.key) != argon2KeyBytes || !bytes.Equal(parsed.salt, salt) { + t.Fatalf("%+v %v", parsed, err) + } + if !verifyPassword("correct horse battery", h) { + t.Fatal("correct password refused") + } + if verifyPassword("correct horse batterz", h) { + t.Fatal("wrong password accepted") + } + if _, err := hashPasswordWith(failingReader{}, "x"); err == nil { + t.Fatal("salt failure ignored") + } +} + +func TestVerifyPasswordInvalidHashUsesDummy(t *testing.T) { + if verifyPassword("anything", "not a hash") { + t.Fatal("invalid hash accepted") + } + if verifyPassword("anything", dummyPasswordHash) { + t.Fatal("dummy hash accepted a password") + } +} + +func TestDummyHashHasProductionCost(t *testing.T) { + if dummyPHC.memory != argon2Memory || dummyPHC.iterations != argon2Iterations || dummyPHC.parallelism != argon2Parallelism || len(dummyPHC.key) != argon2KeyBytes || len(dummyPHC.salt) != argon2SaltBytes { + t.Fatalf("%+v", dummyPHC) + } + defer func() { + if recover() == nil { + t.Fatal("mustParsePHC accepted garbage") + } + }() + mustParsePHC("garbage") +} + +func TestParsePHCRejects(t *testing.T) { + salt := base64.RawStdEncoding.EncodeToString(bytes.Repeat([]byte{1}, 16)) + key := base64.RawStdEncoding.EncodeToString(bytes.Repeat([]byte{2}, 32)) + valid := "$argon2id$v=19$m=65536,t=3,p=2$" + salt + "$" + key + if _, err := parsePHC(valid); err != nil { + t.Fatal(err) + } + cases := []string{ + "", + "argon2id$v=19$m=65536,t=3,p=2$" + salt + "$" + key, + "$argon2i$v=19$m=65536,t=3,p=2$" + salt + "$" + key, + "$argon2id$v=18$m=65536,t=3,p=2$" + salt + "$" + key, + "$argon2id$v=19$m=65536,t=3$" + salt + "$" + key, + "$argon2id$v=19$t=3,m=65536,p=2$" + salt + "$" + key, + "$argon2id$v=19$m=065536,t=3,p=2$" + salt + "$" + key, + "$argon2id$v=19$m=0,t=3,p=2$" + salt + "$" + key, + "$argon2id$v=19$m=65536,t=0,p=2$" + salt + "$" + key, + "$argon2id$v=19$m=65536,t=3,p=0$" + salt + "$" + key, + "$argon2id$v=19$m=65536,t=3,p=17$" + salt + "$" + key, + "$argon2id$v=19$m=2097152,t=3,p=2$" + salt + "$" + key, + "$argon2id$v=19$m=65536,t=65,p=2$" + salt + "$" + key, + "$argon2id$v=19$m=15,t=3,p=2$" + salt + "$" + key, + "$argon2id$v=19$m=+65536,t=3,p=2$" + salt + "$" + key, + "$argon2id$v=19$m=,t=3,p=2$" + salt + "$" + key, + "$argon2id$v=19$m=99999999999,t=3,p=2$" + salt + "$" + key, + "$argon2id$v=19$m=65536,t=3,p=2$" + salt + "=$" + key, + "$argon2id$v=19$m=65536,t=3,p=2$" + salt + "$" + key + "$", + "$argon2id$v=19$m=65536,t=3,p=2$c2hvcnQ$" + key, + "$argon2id$v=19$m=65536,t=3,p=2$" + salt + "$" + base64.RawStdEncoding.EncodeToString(make([]byte, 65)), + "$argon2id$v=19$m=65536,t=3,p=2$" + salt + "$!!!!", + } + for _, c := range cases { + if _, err := parsePHC(c); !errors.Is(err, errInvalidPasswordHash) { + t.Errorf("%q: %v", c, err) + } + } +} + +func TestHashConcurrencyLimit(t *testing.T) { + cheap := phcHash{memory: 8, iterations: 1, parallelism: 1, salt: make([]byte, 8), key: make([]byte, 8)} + for range maxConcurrentHashes { + hashSlots <- struct{}{} + } + done := make(chan struct{}) + go func() { + argon2Key("x", cheap) + close(done) + }() + select { + case <-done: + t.Fatal("a fifth hash ran while four were running") + case <-time.After(100 * time.Millisecond): + } + <-hashSlots + select { + case <-done: + case <-time.After(5 * time.Second): + t.Fatal("hash did not run after a slot was freed") + } + for range maxConcurrentHashes - 1 { + <-hashSlots + } + if cap(hashSlots) != 4 || len(hashSlots) != 0 { + t.Fatal(cap(hashSlots), len(hashSlots)) + } +} + +func TestVerifyLoginUsesDummyForUnknownAndDeleted(t *testing.T) { + var seen []string + verify := func(password, encoded string) bool { + seen = append(seen, encoded) + return password == "right" + } + active := &userRow{ID: 1, PasswordHash: "$stored"} + deleted := &userRow{ID: 2, PasswordHash: "$stored", DeletedAt: sql.NullTime{Time: webNow, Valid: true}} + if !verifyLogin(verify, active, "right") || verifyLogin(verify, active, "wrong") { + t.Fatal("active user") + } + if verifyLogin(verify, nil, "right") || verifyLogin(verify, deleted, "right") { + t.Fatal("unknown or deleted user accepted") + } + want := []string{"$stored", "$stored", dummyPasswordHash, dummyPasswordHash} + if strings.Join(seen, ",") != strings.Join(want, ",") { + t.Fatal(seen) + } +} + +func TestUsernameRules(t *testing.T) { + for _, u := range []string{"a", "alice", "a.b-c_d", "0x", strings.Repeat("z", 64)} { + if err := checkUsername(u); err != nil { + t.Errorf("%q: %v", u, err) + } + } + for _, u := range []string{"", "Alice", "-a", "a b", strings.Repeat("z", 65), "é"} { + if err := checkUsername(u); err == nil || err.Error() != "username must be 1 to 64 characters of lowercase letters, digits, dots, underscores and hyphens, starting with a letter or digit" { + t.Errorf("%q: %v", u, err) + } + } + if err := checkUsername("cli"); err == nil || err.Error() != "username is reserved" { + t.Fatal(err) + } +} + +func TestPasswordRules(t *testing.T) { + for _, p := range []string{strings.Repeat("a", 12), strings.Repeat("a", 256), "pässwörd-long", "spaces are fine ok"} { + if err := checkPasswordRules(p); err != nil { + t.Errorf("%q: %v", p, err) + } + } + cases := map[string]string{ + strings.Repeat("a", 11): "password must be 12 to 256 bytes", + strings.Repeat("a", 257): "password must be 12 to 256 bytes", + "long-enough-\xff-password": "password must be valid UTF-8", + "long-enough-\tpassword": "password must not contain control characters", + "long-enough-\x00password": "password must not contain control characters", + "long-enough-\u0085password": "password must not contain control characters", + strings.Repeat("ä", 6): "", + strings.Repeat("ä", 129): "password must be 12 to 256 bytes", + "long-enough-password\n": "password must not contain control characters", + "long-enough-password\u007f": "password must not contain control characters", + "shortä": "password must be 12 to 256 bytes", + "​zero-width-is-printable-ok": "", + } + for p, want := range cases { + err := checkPasswordRules(p) + if (want == "" && err != nil) || (want != "" && (err == nil || err.Error() != want)) { + t.Errorf("%q: %v, want %q", p, err, want) + } + } +} + +func TestRoles(t *testing.T) { + if !validRole("admin") || !validRole("user") || validRole("Admin") || validRole("") || validRole("root") { + t.Fatal("role rules") + } +} + +func TestSessionTokens(t *testing.T) { + raw := bytes.Repeat([]byte{0xfb}, 32) + token, hash, err := newSessionToken(bytes.NewReader(raw)) + if err != nil { + t.Fatal(err) + } + sum := sha256.Sum256([]byte(token)) + if token != base64.RawURLEncoding.EncodeToString(raw) || !bytes.Equal(hash, sum[:]) || len(token) != 43 || strings.ContainsAny(token, "+/=") { + t.Fatal(token) + } + if !validSessionToken(token) || validSessionToken(token+"A") || validSessionToken(token[:42]) || validSessionToken(strings.Repeat("!", 43)) { + t.Fatal("token syntax") + } + if _, _, err := newSessionToken(failingReader{}); err == nil { + t.Fatal("entropy failure ignored") + } + other, _, _ := newSessionToken(bytes.NewReader(bytes.Repeat([]byte{1}, 32))) + if other == token { + t.Fatal("tokens repeat") + } +} + +func TestSessionValidity(t *testing.T) { + idle, maxAge := time.Hour, 12*time.Hour + s := newSessionRow([]byte("h"), 3, webNow, maxAge, "192.0.2.1", "Agent\x00\n"+strings.Repeat("x", 300)) + if !s.ExpiresAt.Equal(webNow.Add(maxAge)) || s.UserAgent != "Agent "+strings.Repeat("x", 248) || s.UserID != 3 || s.Origin != "192.0.2.1" { + t.Fatalf("%+v", s) + } + u := userRow{ID: 3} + cases := []struct { + now time.Time + lastSeen time.Time + deleted bool + valid bool + }{ + {webNow, webNow, false, true}, + {webNow.Add(59 * time.Minute), webNow, false, true}, + {webNow.Add(time.Hour), webNow, false, false}, + {webNow.Add(11 * time.Hour), webNow.Add(11*time.Hour - time.Minute), false, true}, + {webNow.Add(12 * time.Hour), webNow.Add(12*time.Hour - time.Minute), false, false}, + {webNow, webNow, true, false}, + } + for i, c := range cases { + row := s + row.LastSeenAt = c.lastSeen + user := u + if c.deleted { + user.DeletedAt = sql.NullTime{Time: webNow, Valid: true} + } + if got := sessionValid(row, user, c.now, idle, maxAge); got != c.valid { + t.Errorf("case %d: %v", i, got) + } + } + row := s + row.ExpiresAt = webNow.Add(time.Minute) + if sessionValid(row, u, webNow.Add(time.Minute), idle, maxAge) { + t.Fatal("expires_at ignored") + } + if sessionTouchDue(s, webNow.Add(59*time.Second)) || !sessionTouchDue(s, webNow.Add(time.Minute)) { + t.Fatal("touch interval") + } +} + +func TestSessionCookies(t *testing.T) { + c := sessionCookie("tok", true) + if c.Name != "coredns_webui_session" || c.Value != "tok" || c.Path != "/" || !c.HttpOnly || !c.Secure || c.SameSite != http.SameSiteStrictMode || c.MaxAge != 0 { + t.Fatalf("%+v", c) + } + if sessionCookie("tok", false).Secure { + t.Fatal("secure flag") + } + e := expiredSessionCookie(false) + if e.Value != "" || e.MaxAge != -1 || e.Secure || !e.HttpOnly { + t.Fatalf("%+v", e) + } + token, _, _ := newSessionToken(bytes.NewReader(bytes.Repeat([]byte{9}, 32))) + r := httptest.NewRequest("GET", "/", nil) + if _, ok := requestSessionToken(r); ok { + t.Fatal("no cookie") + } + r.AddCookie(&http.Cookie{Name: sessionCookieName, Value: "short"}) + if _, ok := requestSessionToken(r); ok { + t.Fatal("malformed cookie accepted") + } + r = httptest.NewRequest("GET", "/", nil) + r.AddCookie(&http.Cookie{Name: sessionCookieName, Value: token}) + if got, ok := requestSessionToken(r); !ok || got != token { + t.Fatal(got) + } +} + +func TestPrintableText(t *testing.T) { + cases := []struct { + in string + max int + want string + }{ + {"alice", 64, "alice"}, + {"a\x00b\nc\td", 64, "a b c d"}, + {"bad\xffbyte", 64, "bad byte"}, + {"keep�replacement", 64, "keep�replacement"}, + {"‮evil", 64, " evil"}, + {strings.Repeat("é", 70), 64, strings.Repeat("é", 64)}, + {"abc", 0, ""}, + {"abc", -1, "abc"}, + } + for _, c := range cases { + if got := printableText(c.in, c.max); got != c.want { + t.Errorf("%q: %q", c.in, got) + } + } +} diff --git a/authz.go b/authz.go new file mode 100644 index 0000000..bf6ae27 --- /dev/null +++ b/authz.go @@ -0,0 +1,81 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright (C) 2026 Bryan Joshua Pedini + +package main + +import "slices" + +const ( + accessNone = "none" + accessSession = "session" + accessZone = "zone" + accessAdmin = "admin" +) + +type accessDecision int + +const ( + accessAllowed accessDecision = iota + accessUnauthenticated + accessForbidden + accessNotFound +) + +func authorize(access string, p *principal, delegated bool) accessDecision { + if access == accessNone { + return accessAllowed + } + if p == nil { + return accessUnauthenticated + } + switch access { + case accessAdmin: + if !p.isAdmin() { + return accessForbidden + } + case accessZone: + if !p.isAdmin() && !delegated { + return accessNotFound + } + } + return accessAllowed +} + +func needsDelegation(access string, p principal) bool { + return access == accessZone && !p.isAdmin() +} + +func canAccessZone(p principal, zone string, delegated map[string]bool) bool { + return p.isAdmin() || (p.User.Role == roleUser && delegated[zone]) +} + +func visibleZones(p principal, zones []string, delegated map[string]bool) []string { + out := make([]string, 0, len(zones)) + for _, z := range zones { + if canAccessZone(p, z, delegated) { + out = append(out, z) + } + } + return out +} + +func isOwnAccount(p principal, username string) bool { + return p.User.Username == username +} + +func delegationTargetError(target userRow) *apiError { + if target.DeletedAt.Valid { + return errUserNotFound() + } + if target.Role != roleUser { + return &apiError{Status: 422, Message: "zones cannot be delegated to admins", Fields: map[string]string{"username": "user is an admin and needs no delegation"}} + } + return nil +} + +func leavesNoActiveAdmin(target userRow, activeAdmins []userRow) bool { + if target.Role != roleAdmin || target.DeletedAt.Valid { + return false + } + return !slices.ContainsFunc(activeAdmins, func(u userRow) bool { return u.ID != target.ID }) +} diff --git a/authz_test.go b/authz_test.go new file mode 100644 index 0000000..e6e12c1 --- /dev/null +++ b/authz_test.go @@ -0,0 +1,98 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright (C) 2026 Bryan Joshua Pedini + +package main + +import ( + "database/sql" + "net/http" + "slices" + "testing" +) + +func TestAuthorize(t *testing.T) { + admin := &principal{User: userRow{ID: 1, Role: roleAdmin}} + user := &principal{User: userRow{ID: 2, Role: roleUser}} + cases := []struct { + access string + p *principal + delegated bool + want accessDecision + }{ + {accessNone, nil, false, accessAllowed}, + {accessSession, nil, false, accessUnauthenticated}, + {accessZone, nil, true, accessUnauthenticated}, + {accessAdmin, nil, false, accessUnauthenticated}, + {accessSession, user, false, accessAllowed}, + {accessSession, admin, false, accessAllowed}, + {accessAdmin, user, true, accessForbidden}, + {accessAdmin, admin, false, accessAllowed}, + {accessZone, user, false, accessNotFound}, + {accessZone, user, true, accessAllowed}, + {accessZone, admin, false, accessAllowed}, + } + for i, c := range cases { + if got := authorize(c.access, c.p, c.delegated); got != c.want { + t.Errorf("case %d: %v", i, got) + } + } + if !needsDelegation(accessZone, *user) || needsDelegation(accessZone, *admin) || needsDelegation(accessSession, *user) || needsDelegation(accessAdmin, *user) { + t.Fatal("needsDelegation") + } +} + +func TestVisibleZones(t *testing.T) { + zones := []string{"a.test.", "b.test.", "c.test."} + delegated := map[string]bool{"b.test.": true, "z.test.": true} + admin := principal{User: userRow{Role: roleAdmin}} + user := principal{User: userRow{Role: roleUser}} + if got := visibleZones(admin, zones, delegated); !slices.Equal(got, zones) { + t.Fatal(got) + } + if got := visibleZones(user, zones, delegated); !slices.Equal(got, []string{"b.test."}) { + t.Fatal(got) + } + if got := visibleZones(user, zones, nil); len(got) != 0 { + t.Fatal(got) + } + if canAccessZone(principal{User: userRow{Role: "other"}}, "b.test.", delegated) { + t.Fatal("unknown role") + } +} + +func TestOwnAccountAndTargets(t *testing.T) { + p := principal{User: userRow{ID: 1, Username: "alice", Role: roleAdmin}} + if !isOwnAccount(p, "alice") || isOwnAccount(p, "bob") { + t.Fatal("own account") + } + if delegationTargetError(userRow{Role: roleUser}) != nil { + t.Fatal("user refused") + } + if e := delegationTargetError(userRow{Role: roleAdmin}); e == nil || e.Status != http.StatusUnprocessableEntity || e.Fields["username"] == "" { + t.Fatal(e) + } + if e := delegationTargetError(userRow{Role: roleUser, DeletedAt: sql.NullTime{Valid: true}}); e == nil || e.Status != http.StatusNotFound || e.Message != "user not found" { + t.Fatal(e) + } +} + +func TestLeavesNoActiveAdmin(t *testing.T) { + a := userRow{ID: 1, Role: roleAdmin} + b := userRow{ID: 2, Role: roleAdmin} + u := userRow{ID: 3, Role: roleUser} + if !leavesNoActiveAdmin(a, []userRow{a}) { + t.Fatal("last admin") + } + if leavesNoActiveAdmin(a, []userRow{a, b}) { + t.Fatal("two admins") + } + if leavesNoActiveAdmin(u, []userRow{a}) || leavesNoActiveAdmin(u, nil) { + t.Fatal("user target") + } + if leavesNoActiveAdmin(userRow{ID: 1, Role: roleAdmin, DeletedAt: sql.NullTime{Valid: true}}, nil) { + t.Fatal("deleted target") + } + if !leavesNoActiveAdmin(a, nil) { + t.Fatal("admin not in the locked list") + } +} diff --git a/cli.go b/cli.go index 0dfc35e..fcbd533 100644 --- a/cli.go +++ b/cli.go @@ -14,13 +14,10 @@ import ( "net" "net/http" "net/netip" - "regexp" "strconv" "strings" "text/tabwriter" "time" - "unicode" - "unicode/utf8" ) const usageText = `usage: @@ -39,20 +36,14 @@ const usageText = `usage: const ( healthcheckTimeout = 3 * time.Second - cliActor = "cli" - cliOrigin = "local" defaultAuditRows = 20 maxAuditRows = 1000000 - minPasswordBytes = 12 - maxPasswordBytes = 256 maxPasswordLineBytes = 4096 cliTimeLayout = "2006-01-02T15:04:05Z" ) -var usernamePattern = regexp.MustCompile(`^[a-z0-9][a-z0-9._-]{0,63}$`) - var ( - errNotImplemented = errors.New("not implemented") + errZoneHasNoRows = errors.New("the zone has no records") errNoActiveUser = errors.New("no active user has this username") errLastActiveAdmin = errors.New("the last active admin cannot be demoted or deleted") ) @@ -203,7 +194,7 @@ func (a *app) parseUserCommand(args []string) (cliCommand, error) { if err := checkUsernameArg(username); err != nil { return cliCommand{}, err } - if username == cliActor { + if username == reservedUsername { return cliCommand{}, usageError("reserved username") } if err := checkRoleArg(role); err != nil { @@ -292,31 +283,12 @@ func checkUsernameArg(username string) error { } func checkRoleArg(role string) error { - if role != "admin" && role != "user" { + if !validRole(role) { return usageError("invalid role") } return nil } -func validUsernameSyntax(username string) bool { - return usernamePattern.MatchString(username) -} - -func checkPasswordRules(password string) error { - if len(password) < minPasswordBytes || len(password) > maxPasswordBytes { - return fmt.Errorf("password must be %d to %d bytes", minPasswordBytes, maxPasswordBytes) - } - if !utf8.ValidString(password) { - return errors.New("password must be valid UTF-8") - } - for _, r := range password { - if unicode.IsControl(r) { - return errors.New("password must not contain control characters") - } - } - return nil -} - func (a *app) readPassword() (string, error) { if a.stdinIsTerminal() { first, err := a.promptPassword("Password: ") @@ -402,12 +374,127 @@ func parseAuditCount(s string) (int, error) { return n, nil } +type cliReadBackend interface { + ListZones(ctx context.Context) ([]zoneSummary, error) + ZoneRows(ctx context.Context, zone string) ([]recordRow, error) + LatestAudit(ctx context.Context, n int) ([]auditRow, error) +} + +type sqlReadBackend struct { + recordStore + auditStore +} + +func newSQLReadBackend(db *sql.DB, t tableNames) cliReadBackend { + return sqlReadBackend{recordStore: newRecordStore(db, t), auditStore: newAuditStore(db, t)} +} + +var checkHeader = []string{"ZONE", "NAME", "TYPE", "ID", "SEVERITY", "PROBLEM"} + +var auditHeader = []string{"TIME", "ACTOR", "ORIGIN", "OPERATION", "STATUS", "ZONE", "RECORD", "TARGET_USER"} + +func cliText(s string) string { + s = strings.TrimSpace(printableText(s, -1)) + if s == "" { + return "-" + } + return s +} + +func checkRows(zone string, problems []zoneProblem) [][]string { + rows := make([][]string, 0, len(problems)) + for _, p := range problems { + name, recordType, id := "-", "-", "-" + if p.RecordID != 0 { + name, recordType, id = p.Name, cliText(p.Type), strconv.FormatInt(p.RecordID, 10) + if name == "" { + name = "@" + } + name = cliText(name) + } + rows = append(rows, []string{cliText(zone), name, recordType, id, p.Severity, cliText(p.Code + ": " + p.Message)}) + } + return rows +} + func (a *app) runCheck(ctx context.Context, db *sql.DB, t tableNames, log *slog.Logger, zone string) error { - return fmt.Errorf("check: %w", errNotImplemented) + return a.checkZones(ctx, a.newReadBackend(db, t), zone) +} + +func (a *app) checkZones(ctx context.Context, b cliReadBackend, zone string) error { + zones := []string{zone} + if zone == "" { + summaries, err := b.ListZones(ctx) + if err != nil { + return err + } + zones = zones[:0] + for _, z := range summaries { + zones = append(zones, z.Zone) + } + } + now := a.now() + var table [][]string + for _, z := range zones { + rows, err := b.ZoneRows(ctx, z) + if err != nil { + return err + } + if len(rows) == 0 { + return errZoneHasNoRows + } + table = append(table, checkRows(z, checkZone(z, rows, now))...) + } + if err := writeTable(a.stdout, checkHeader, table); err != nil { + return err + } + if len(table) > 0 { + return errCheckProblems + } + return nil } func (a *app) runAudit(ctx context.Context, db *sql.DB, t tableNames, log *slog.Logger, n int) error { - return fmt.Errorf("audit: %w", errNotImplemented) + return a.printAudit(ctx, a.newReadBackend(db, t), n) +} + +func cliNullInt(v sql.NullInt64) string { + if !v.Valid { + return "-" + } + return strconv.FormatInt(v.Int64, 10) +} + +func cliNullText(v sql.NullString) string { + if !v.Valid { + return "-" + } + return cliText(v.String) +} + +func auditRows(entries []auditRow) [][]string { + rows := make([][]string, 0, len(entries)) + for _, e := range entries { + rows = append(rows, []string{ + formatCLITime(e.Time), + cliText(e.Actor), + cliText(e.Origin), + cliText(e.Operation), + cliNullInt(e.Status), + cliNullText(e.Zone), + cliNullInt(e.RecordID), + cliNullText(e.TargetUsername), + }) + } + return rows +} + +func (a *app) printAudit(ctx context.Context, b cliReadBackend, n int) error { + entries, err := b.LatestAudit(ctx, n) + if err != nil { + return err + } + return writeTable(a.stdout, auditHeader, auditRows(entries)) } func newHealthClient() *http.Client { @@ -543,34 +630,8 @@ func (a *app) userList(ctx context.Context, b cliUserBackend, all bool) error { return writeTable(a.stdout, userListHeader, userListRows(users)) } -func cliAuditEntry(now time.Time, operation string, target userRow, before, after *userRow) (auditEntry, error) { - e := auditEntry{ - Time: now, - Actor: cliActor, - Origin: cliOrigin, - Operation: operation, - TargetUserID: sql.NullInt64{Int64: target.ID, Valid: true}, - } - var err error - if before != nil { - if e.Before, err = auditUserJSON(*before); err != nil { - return auditEntry{}, err - } - } - if after != nil { - if e.After, err = auditUserJSON(*after); err != nil { - return auditEntry{}, err - } - } - return e, nil -} - func insertCLIAudit(ctx context.Context, tx cliUserTx, now time.Time, operation string, target userRow, before, after *userRow) error { - e, err := cliAuditEntry(now, operation, target, before, after) - if err != nil { - return fmt.Errorf("audit value: %w", err) - } - _, err = tx.InsertAudit(ctx, e) + _, err := tx.InsertAudit(ctx, cliAuditEntry(now, operation, target, before, after)) return err } @@ -593,12 +654,12 @@ func (a *app) userAdd(ctx context.Context, b cliUserBackend, log *slog.Logger, u if err != nil { return err } - return insertCLIAudit(ctx, tx, now, "user_create", u, nil, &u) + return insertCLIAudit(ctx, tx, now, opUserCreate, u, nil, &u) }) if err != nil { return err } - logCLIChange(ctx, log, "user_create", username) + logCLIChange(ctx, log, opUserCreate, username) return nil } @@ -615,12 +676,12 @@ func (a *app) userPasswd(ctx context.Context, b cliUserBackend, log *slog.Logger if _, err := tx.DeleteUserSessions(ctx, u.ID); err != nil { return err } - return insertCLIAudit(ctx, tx, now, "user_password", u, &u, &u) + return insertCLIAudit(ctx, tx, now, opUserPassword, u, &u, &u) }) if err != nil { return err } - logCLIChange(ctx, log, "user_password", username) + logCLIChange(ctx, log, opUserPassword, username) return nil } @@ -639,7 +700,7 @@ func (a *app) userRole(ctx context.Context, b cliUserBackend, log *slog.Logger, if u.Role == role { return nil } - if u.Role == "admin" && len(admins) <= 1 { + if u.Role == roleAdmin && len(admins) <= 1 { return errLastActiveAdmin } if err := tx.SetRole(ctx, u.ID, role, now); err != nil { @@ -649,13 +710,13 @@ func (a *app) userRole(ctx context.Context, b cliUserBackend, log *slog.Logger, after.Role = role after.UpdatedAt = now changed = true - return insertCLIAudit(ctx, tx, now, "user_role", u, &u, &after) + return insertCLIAudit(ctx, tx, now, opUserRole, u, &u, &after) }) if err != nil { return err } if changed { - logCLIChange(ctx, log, "user_role", username) + logCLIChange(ctx, log, opUserRole, username) } return nil } @@ -671,7 +732,7 @@ func (a *app) userDelete(ctx context.Context, b cliUserBackend, log *slog.Logger if err != nil { return err } - if u.Role == "admin" && len(admins) <= 1 { + if u.Role == roleAdmin && len(admins) <= 1 { return errLastActiveAdmin } if err := tx.MarkDeleted(ctx, u.ID, now); err != nil { @@ -683,11 +744,11 @@ func (a *app) userDelete(ctx context.Context, b cliUserBackend, log *slog.Logger after := u after.DeletedAt = sql.NullTime{Time: now, Valid: true} after.UpdatedAt = now - return insertCLIAudit(ctx, tx, now, "user_delete", u, &u, &after) + return insertCLIAudit(ctx, tx, now, opUserDelete, u, &u, &after) }) if err != nil { return err } - logCLIChange(ctx, log, "user_delete", username) + logCLIChange(ctx, log, opUserDelete, username) return nil } diff --git a/cli_test.go b/cli_test.go index 605f837..d0c184a 100644 --- a/cli_test.go +++ b/cli_test.go @@ -665,21 +665,173 @@ func TestUserDelete(t *testing.T) { } } -func TestCheckAndAuditCommands(t *testing.T) { +type fakeReadBackend struct { + zones []zoneSummary + rows map[string][]recordRow + audit []auditRow + failOn string + auditN int + rowCalls []string +} + +func (f *fakeReadBackend) ListZones(ctx context.Context) ([]zoneSummary, error) { + if f.failOn == "ListZones" { + return nil, errFakeStore + } + return f.zones, nil +} + +func (f *fakeReadBackend) ZoneRows(ctx context.Context, zone string) ([]recordRow, error) { + f.rowCalls = append(f.rowCalls, zone) + if f.failOn == "ZoneRows" { + return nil, errFakeStore + } + return f.rows[zone], nil +} + +func (f *fakeReadBackend) LatestAudit(ctx context.Context, n int) ([]auditRow, error) { + f.auditN = n + if f.failOn == "LatestAudit" { + return nil, errFakeStore + } + return f.audit, nil +} + +func cliRecord(id int64, zone, name, recordType string, ttl any, content any) recordRow { + r := recordRow{ID: id, Zone: zone, Name: name, RecordType: recordType} + if v, ok := ttl.(int); ok { + r.TTL = sql.NullInt64{Int64: int64(v), Valid: true} + } + if v, ok := content.(string); ok { + r.Content = sql.NullString{String: v, Valid: true} + } + return r +} + +func cleanZoneRows(zone string) []recordRow { + return []recordRow{ + cliRecord(1, zone, "", "SOA", 3600, `{"ns":"ns1.`+zone+`","MBox":"hostmaster.`+zone+`","refresh":3600,"retry":600,"expire":604800,"minttl":300,"serial":2026111800}`), + cliRecord(2, zone, "", "NS", 3600, `{"host":"ns1.`+zone+`"}`), + cliRecord(3, zone, "ns1", "A", 3600, `{"ip":"192.0.2.1"}`), + } +} + +func (h *cliHarness) withReadBackend(b *fakeReadBackend) { + h.a.newReadBackend = func(*sql.DB, tableNames) cliReadBackend { return b } +} + +func TestCheckCommand(t *testing.T) { var zone string + b := &fakeReadBackend{rows: map[string][]recordRow{"example.org.": cleanZoneRows("example.org.")}} h := newCLIHarness(t, "") - h.a.normalizeZone = func(z string) (string, error) { zone = z; return "example.org.", nil } - if code := h.run("check", "Example.Org"); code != 1 || h.stderr.String() != "coredns-web-ui: check: not implemented\n" || h.prepared != 1 || zone != "Example.Org" { + h.withReadBackend(b) + h.a.normalizeZone = func(z string) (string, error) { zone = z; return normalizeZone(z) } + if code := h.run("check", "Example.Org"); code != 0 || h.stderr.Len() != 0 || h.prepared != 1 || zone != "Example.Org" { t.Fatalf("%d %q", code, h.stderr.String()) } + if h.stdout.String() != "ZONE NAME TYPE ID SEVERITY PROBLEM\n" || len(b.rowCalls) != 1 || b.rowCalls[0] != "example.org." { + t.Fatalf("%q %v", h.stdout.String(), b.rowCalls) + } + + broken := []recordRow{ + cliRecord(7, "broken.test.", "www", "A", nil, `{"ip":"192.0.2.7"}`), + cliRecord(8, "broken.test.", "", "TXT", 300, "x\ty"), + } + b = &fakeReadBackend{ + zones: []zoneSummary{{Zone: "broken.test."}, {Zone: "example.org."}}, + rows: map[string][]recordRow{"example.org.": cleanZoneRows("example.org."), "broken.test.": broken}, + } h = newCLIHarness(t, "") - if code := h.run("check"); code != 1 || h.prepared != 1 { + h.withReadBackend(b) + if code := h.run("check"); code != 3 || h.stderr.Len() != 0 { + t.Fatalf("%d %q", code, h.stderr.String()) + } + lines := strings.Split(strings.TrimSuffix(h.stdout.String(), "\n"), "\n") + if !strings.HasPrefix(lines[0], "ZONE ") || !strings.Contains(lines[0], "PROBLEM") { + t.Fatal(lines[0]) + } + out := h.stdout.String() + for _, want := range []string{"ttl_null: stored TTL is NULL", "soa_missing", "content_json", " www ", " @ ", " 7 ", " 8 ", "error"} { + if !strings.Contains(out, want) { + t.Errorf("missing %q in\n%s", want, out) + } + } + if strings.Contains(out, "example.org.") || strings.Contains(out, "\t") { + t.Fatalf("unexpected output\n%s", out) + } + for _, line := range lines[1:] { + if !strings.HasPrefix(line, "broken.test.") { + t.Fatalf("line %q", line) + } + } + if !strings.Contains(out, "broken.test. - - - error") { + t.Fatalf("zone level problem row missing\n%s", out) + } + + h = newCLIHarness(t, "") + h.withReadBackend(&fakeReadBackend{rows: map[string][]recordRow{}}) + if code := h.run("check", "missing.test"); code != 1 || h.stderr.String() != "coredns-web-ui: the zone has no records\n" || h.stdout.Len() != 0 { + t.Fatalf("%d %q", code, h.stderr.String()) + } + for _, op := range []string{"ListZones", "ZoneRows"} { + h = newCLIHarness(t, "") + h.withReadBackend(&fakeReadBackend{zones: []zoneSummary{{Zone: "a.test."}}, failOn: op}) + if code := h.run("check"); code != 1 || h.stdout.Len() != 0 { + t.Fatalf("%s: %d", op, code) + } + } + h = newCLIHarness(t, "") + h.withReadBackend(&fakeReadBackend{}) + if code := h.run("check"); code != 0 || h.stdout.String() != "ZONE NAME TYPE ID SEVERITY PROBLEM\n" { + t.Fatalf("no zones: %d %q", code, h.stdout.String()) + } + h = newCLIHarness(t, "") + if code := h.run("check", "a", "b"); code != 2 || h.prepared != 0 { t.Fatal(code) } - for _, args := range [][]string{{"audit"}, {"audit", "5"}, {"audit", "0001"}, {"audit", "1000000"}} { + h = newCLIHarness(t, "") + if code := h.run("check", "bad zone"); code != 2 || h.prepared != 0 || strings.Contains(h.stderr.String(), "bad zone") { + t.Fatal(code, h.stderr.String()) + } +} + +func TestAuditCommand(t *testing.T) { + at := time.Date(2026, 11, 18, 10, 11, 12, 345678000, time.UTC) + b := &fakeReadBackend{audit: []auditRow{ + {auditEntry: auditEntry{ID: 1, Time: at, Actor: "cli", Origin: "local", Operation: "user_create", TargetUserID: sql.NullInt64{Int64: 3, Valid: true}}, TargetUsername: sql.NullString{String: "bob", Valid: true}}, + {auditEntry: auditEntry{ID: 2, Time: at.Add(time.Second), UserID: sql.NullInt64{Int64: 3, Valid: true}, Actor: "bad\tactor\n", Origin: "192.0.2.1", Operation: "record_update", + Status: sql.NullInt64{Int64: 200, Valid: true}, Zone: sql.NullString{String: "example.org.", Valid: true}, RecordID: sql.NullInt64{Int64: 42, Valid: true}}}, + {auditEntry: auditEntry{ID: 3, Time: at.Add(2 * time.Second), Actor: "", Origin: "2001:db8::1", Operation: "login", Status: sql.NullInt64{Int64: 401, Valid: true}}}, + }} + h := newCLIHarness(t, "") + h.withReadBackend(b) + if code := h.run("audit"); code != 0 || h.stderr.Len() != 0 || b.auditN != 20 || h.prepared != 1 { + t.Fatalf("%d %q %d", code, h.stderr.String(), b.auditN) + } + want := "TIME ACTOR ORIGIN OPERATION STATUS ZONE RECORD TARGET_USER\n" + + "2026-11-18T10:11:12Z cli local user_create - - - bob\n" + + "2026-11-18T10:11:13Z bad actor 192.0.2.1 record_update 200 example.org. 42 -\n" + + "2026-11-18T10:11:14Z - 2001:db8::1 login 401 - - -\n" + if h.stdout.String() != want { + t.Fatalf("got\n%s\nwant\n%s", h.stdout.String(), want) + } + for args, n := range map[string]int{"5": 5, "0001": 1, "1000000": 1000000} { + b = &fakeReadBackend{} h = newCLIHarness(t, "") - if code := h.run(args...); code != 1 || h.stderr.String() != "coredns-web-ui: audit: not implemented\n" || h.prepared != 1 { - t.Fatalf("%v: %d %q", args, code, h.stderr.String()) + h.withReadBackend(b) + if code := h.run("audit", args); code != 0 || b.auditN != n || h.stdout.String() != "TIME ACTOR ORIGIN OPERATION STATUS ZONE RECORD TARGET_USER\n" { + t.Fatalf("%s: %d %d %q", args, code, b.auditN, h.stdout.String()) + } + } + h = newCLIHarness(t, "") + h.withReadBackend(&fakeReadBackend{failOn: "LatestAudit"}) + if code := h.run("audit"); code != 1 || h.stdout.Len() != 0 { + t.Fatal(code) + } + for _, args := range [][]string{{"audit", "0"}, {"audit", "-1"}, {"audit", "x"}, {"audit", "1000001"}, {"audit", "1", "2"}, {"audit", "+5"}} { + h = newCLIHarness(t, "") + if code := h.run(args...); code != 2 || h.prepared != 0 { + t.Fatalf("%v: %d", args, code) } } if n, err := parseAuditCount("20"); n != 20 || err != nil { @@ -687,6 +839,24 @@ func TestCheckAndAuditCommands(t *testing.T) { } } +func TestSQLReadBackend(t *testing.T) { + db, state := newFakeDB(t, fdbRules()) + b := newSQLReadBackend(db, fdbTables(t)) + if _, err := b.ListZones(context.Background()); err != nil { + t.Fatal(err) + } + if _, err := b.ZoneRows(context.Background(), "example.org."); err != nil { + t.Fatal(err) + } + if _, err := b.LatestAudit(context.Background(), 3); err != nil { + t.Fatal(err) + } + q := state.Queries() + if len(q) != 3 || !strings.Contains(q[0], "GROUP BY") || !strings.Contains(q[1], "`coredns_records`") || !strings.Contains(q[2], "`coredns_webui_audit`") { + t.Fatal(q) + } +} + func TestExitCodes(t *testing.T) { h := newCLIHarness(t, "") if h.a.exitCode(nil) != 0 { diff --git a/go.mod b/go.mod index c87fb0e..2772a23 100644 --- a/go.mod +++ b/go.mod @@ -6,11 +6,12 @@ require ( github.com/go-sql-driver/mysql v1.10.2 github.com/gorilla/mux v1.8.1 github.com/miekg/dns v1.1.73 + golang.org/x/crypto v0.59.0 golang.org/x/term v0.48.0 ) require ( filippo.io/edwards25519 v1.2.0 // indirect - golang.org/x/net v0.57.0 // indirect + golang.org/x/net v0.62.0 // indirect golang.org/x/sys v0.50.0 // indirect ) diff --git a/go.sum b/go.sum index 1703890..ae9f1f9 100644 --- a/go.sum +++ b/go.sum @@ -6,8 +6,10 @@ github.com/gorilla/mux v1.8.1 h1:TuBL49tXwgrFYWhqrNgrUNEY92u81SPhu7sTdzQEiWY= github.com/gorilla/mux v1.8.1/go.mod h1:AKf9I4AEqPTmMytcMc0KkNouC66V3BtZ4qD5fmWSiMQ= github.com/miekg/dns v1.1.73 h1:uhT8nJxmTrPJYClxVxTCX+CVn6qnzSiybRk72Z6DgrE= github.com/miekg/dns v1.1.73/go.mod h1:RW2Obtfd5NZHvOFe3zYG0W8koWOQtAzyHaLo8vASBuQ= -golang.org/x/net v0.57.0 h1:K5+3DljvIuDG9/Jv9rvyMywYNFCQ9RSUY6OOTTkT+tE= -golang.org/x/net v0.57.0/go.mod h1:KpXc8iv+r3XplLAG/f7Jsf9RPszJzdR0f58q9vGOuEU= +golang.org/x/crypto v0.59.0 h1:xS2jhqYbzNrpvkWP2YTDf4TJwBy3ykR03i8vFDxEc7c= +golang.org/x/crypto v0.59.0/go.mod h1:veDyUwATGs3c+vN3VfTbzViMGXeTBk3WyhBOkn+F/4U= +golang.org/x/net v0.62.0 h1:18ELalfM5+XNRwzM2nYqXsZQ9ByS1uhj2O/U7+5jqRY= +golang.org/x/net v0.62.0/go.mod h1:WgDCOTH8iwtB66T4/GfI94AHo/hhdb7Hah9NDseQfiI= golang.org/x/sync v0.22.0 h1:SZjpbeLmrCk4xhRSZFNZW5gFUeCeFgjekvI/+gfScek= golang.org/x/sync v0.22.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0= golang.org/x/sys v0.50.0 h1:dkKZEFTEKaLr1sjhs0WiKqoi8Jj5nHbS3Njmx1UoMJs= diff --git a/handlers_api.go b/handlers_api.go index b9baee9..52fd56f 100644 --- a/handlers_api.go +++ b/handlers_api.go @@ -11,12 +11,735 @@ import ( "errors" "maps" "net/http" + "net/url" "slices" "strconv" "strings" "time" ) +const ( + msgOwnAccount = "use the account page to change your own account" + msgLastActiveAdmin = "the last active admin cannot be demoted or deleted" + msgUsernameTaken = "username already used" + msgDelegationAbsent = "delegation not found" + msgWrongPassword = "current password is wrong" + msgConfirmMismatch = "confirmation does not match" +) + +func frameworkAPIHandlers(s *WebServer) map[string]apiHandler { + return map[string]apiHandler{ + opAccountRead: handleAccountRead, + opPasswordChange: handlePasswordChange, + opDelegationList: handleDelegationList, + opDelegationGrant: handleDelegationGrant, + opDelegationRevoke: handleDelegationRevoke, + opUserList: handleUserList, + opUserCreate: handleUserCreate, + opUserRead: handleUserRead, + opUserRole: handleUserRole, + opUserPassword: handleUserPassword, + opUserDelete: handleUserDelete, + opAuditRead: handleAuditRead, + } +} + +func apiTime(t time.Time) string { + return t.UTC().Format(time.RFC3339Nano) +} + +func apiNullTime(t sql.NullTime) *string { + if !t.Valid { + return nil + } + s := apiTime(t.Time) + return &s +} + +func noContent() apiResponse { + return apiResponse{Status: http.StatusNoContent} +} + +func okJSON(body any) apiResponse { + return apiResponse{Status: http.StatusOK, Body: body} +} + +func badParameter(name string) *apiError { + return &apiError{Status: http.StatusBadRequest, Message: "invalid parameter " + name} +} + +func ownAccountError() *apiError { + return &apiError{Status: http.StatusForbidden, Message: msgOwnAccount} +} + +func lastAdminError() *apiError { + return &apiError{Status: http.StatusConflict, Message: msgLastActiveAdmin} +} + +func passwordFieldError(field string, err error) *apiError { + return fieldError(field, err.Error()) +} + +func (c *apiContext) setTargetUser(u userRow) { + c.Entry.TargetUserID = sql.NullInt64{Int64: u.ID, Valid: true} +} + +func (c *apiContext) pathUsername() (string, error) { + username := c.Vars["username"] + if !validUsernameSyntax(username) { + return "", errUserNotFound() + } + return username, nil +} + +func (c *apiContext) lookupUser(ctx context.Context) (userRow, error) { + username, err := c.pathUsername() + if err != nil { + return userRow{}, err + } + u, err := c.Server.store.UserByUsername(ctx, username) + if errors.Is(err, errRowNotFound) { + return userRow{}, errUserNotFound() + } + if err != nil { + return userRow{}, err + } + c.setTargetUser(u) + return u, nil +} + +func activeTargetForUpdate(ctx context.Context, c *apiContext, tx webTx, username string) (userRow, error) { + u, err := tx.UserByUsernameForUpdate(ctx, username) + if errors.Is(err, errRowNotFound) { + return userRow{}, errUserNotFound() + } + if err != nil { + return userRow{}, err + } + c.setTargetUser(u) + if u.DeletedAt.Valid { + return userRow{}, errUserNotFound() + } + return u, nil +} + +func (c *apiContext) recordChange(before, after []byte) { + c.Entry.Before, c.Entry.After = before, after +} + +func (c *apiContext) commitChange(ctx context.Context, tx webTx, status int) error { + return c.writeChangeAuditWith(ctx, tx, status) +} + +type accountResponse struct { + Username string `json:"username"` + Role string `json:"role"` + Zones []string `json:"zones"` +} + +func handleAccountRead(ctx context.Context, c *apiContext) (apiResponse, error) { + u := c.Principal.User + resp := accountResponse{Username: u.Username, Role: u.Role, Zones: []string{}} + if !c.Principal.isAdmin() { + zones, err := c.Server.store.UserZones(ctx, u.ID) + if err != nil { + return apiResponse{}, err + } + for _, z := range zones { + if z.ZoneExists { + resp.Zones = append(resp.Zones, z.Zone) + } + } + } + return okJSON(resp), nil +} + +type passwordChangeRequest struct { + Current string `json:"current"` + Password string `json:"password"` +} + +func handlePasswordChange(ctx context.Context, c *apiContext) (apiResponse, error) { + var req passwordChangeRequest + if err := c.decodeJSON(&req); err != nil { + return apiResponse{}, err + } + s := c.Server + fields := map[string]string{} + if !s.verifyPassword(req.Current, c.Principal.User.PasswordHash) { + fields["current"] = msgWrongPassword + } + if err := checkPasswordRules(req.Password); err != nil { + fields["password"] = err.Error() + } + if len(fields) > 0 { + return apiResponse{}, &apiError{Status: http.StatusUnprocessableEntity, Message: "invalid password change", Fields: fields} + } + hash, err := s.hashPassword(req.Password) + if err != nil { + return apiResponse{}, err + } + c.setTargetUser(c.Principal.User) + err = s.store.InTx(ctx, func(tx webTx) error { + u, err := tx.UserByIDForUpdate(ctx, c.Principal.User.ID) + if err != nil { + return err + } + if u.DeletedAt.Valid { + return errUserNotFound() + } + if err := tx.SetPassword(ctx, u.ID, hash, c.Now); err != nil { + return err + } + if _, err := tx.DeleteUserSessionsExcept(ctx, u.ID, c.Principal.TokenHash); err != nil { + return err + } + snapshot := auditUserJSON(u) + c.recordChange(snapshot, snapshot) + return c.commitChange(ctx, tx, http.StatusNoContent) + }) + if err != nil { + return apiResponse{}, err + } + return noContent(), nil +} + +type delegatedUser struct { + Username string `json:"username"` + Role string `json:"role"` +} + +func requireZone(ctx context.Context, exists func(context.Context, string) (bool, error), zone string) error { + ok, err := exists(ctx, zone) + if err != nil { + return err + } + if !ok { + return errZoneNotFound() + } + return nil +} + +func handleDelegationList(ctx context.Context, c *apiContext) (apiResponse, error) { + store := c.Server.store + if err := requireZone(ctx, store.ZoneExists, c.Zone); err != nil { + return apiResponse{}, err + } + users, err := store.ZoneUsers(ctx, c.Zone) + if err != nil { + return apiResponse{}, err + } + out := make([]delegatedUser, 0, len(users)) + for _, u := range users { + out = append(out, delegatedUser{Username: u.Username, Role: u.Role}) + } + return okJSON(map[string]any{"users": out}), nil +} + +func handleDelegationGrant(ctx context.Context, c *apiContext) (apiResponse, error) { + username, err := c.pathUsername() + if err != nil { + return apiResponse{}, err + } + err = c.Server.store.InTx(ctx, func(tx webTx) error { + if err := requireZone(ctx, tx.ZoneExists, c.Zone); err != nil { + return err + } + u, err := tx.UserByUsernameForUpdate(ctx, username) + if errors.Is(err, errRowNotFound) { + return errUserNotFound() + } + if err != nil { + return err + } + c.setTargetUser(u) + if aerr := delegationTargetError(u); aerr != nil { + return aerr + } + created, err := tx.GrantDelegation(ctx, c.Zone, u.ID, c.Principal.User.ID, c.Now) + if err != nil || !created { + return err + } + c.recordChange(nil, auditDelegationJSON(c.Zone, u.Username)) + return c.commitChange(ctx, tx, http.StatusNoContent) + }) + if err != nil { + return apiResponse{}, err + } + return noContent(), nil +} + +func handleDelegationRevoke(ctx context.Context, c *apiContext) (apiResponse, error) { + username, err := c.pathUsername() + if err != nil { + return apiResponse{}, err + } + err = c.Server.store.InTx(ctx, func(tx webTx) error { + u, err := activeTargetForUpdate(ctx, c, tx, username) + if err != nil { + return err + } + revoked, err := tx.RevokeDelegation(ctx, c.Zone, u.ID) + if err != nil { + return err + } + if !revoked { + return &apiError{Status: http.StatusNotFound, Message: msgDelegationAbsent} + } + c.recordChange(auditDelegationJSON(c.Zone, u.Username), nil) + return c.commitChange(ctx, tx, http.StatusNoContent) + }) + if err != nil { + return apiResponse{}, err + } + return noContent(), nil +} + +type userListItem struct { + Username string `json:"username"` + Role string `json:"role"` + ZoneCount int64 `json:"zone_count"` + CreatedAt string `json:"created_at"` + LastLoginAt *string `json:"last_login_at"` + DeletedAt *string `json:"deleted_at"` +} + +func userListItemOf(u userRow, zones int64) userListItem { + return userListItem{ + Username: u.Username, + Role: u.Role, + ZoneCount: zones, + CreatedAt: apiTime(u.CreatedAt), + LastLoginAt: apiNullTime(u.LastLoginAt), + DeletedAt: apiNullTime(u.DeletedAt), + } +} + +func queryFlag(q url.Values, name string) (bool, error) { + if !q.Has(name) { + return false, nil + } + switch q.Get(name) { + case "true": + return true, nil + case "false", "": + return false, nil + } + return false, badParameter(name) +} + +func handleUserList(ctx context.Context, c *apiContext) (apiResponse, error) { + deleted, err := queryFlag(c.Request.URL.Query(), "deleted") + if err != nil { + return apiResponse{}, err + } + users, err := c.Server.store.ListUsers(ctx, deleted) + if err != nil { + return apiResponse{}, err + } + out := make([]userListItem, 0, len(users)) + for _, u := range users { + out = append(out, userListItemOf(u.userRow, u.Zones)) + } + return okJSON(map[string]any{"users": out}), nil +} + +type userCreateRequest struct { + Username string `json:"username"` + Role string `json:"role"` + Password string `json:"password"` +} + +func roleFieldMessage() string { + return "must be admin or user" +} + +func handleUserCreate(ctx context.Context, c *apiContext) (apiResponse, error) { + var req userCreateRequest + if err := c.decodeJSON(&req); err != nil { + return apiResponse{}, err + } + fields := map[string]string{} + if err := checkUsername(req.Username); err != nil { + fields["username"] = err.Error() + } + if !validRole(req.Role) { + fields["role"] = roleFieldMessage() + } + if err := checkPasswordRules(req.Password); err != nil { + fields["password"] = err.Error() + } + if len(fields) > 0 { + return apiResponse{}, &apiError{Status: http.StatusUnprocessableEntity, Message: "invalid user", Fields: fields} + } + s := c.Server + hash, err := s.hashPassword(req.Password) + if err != nil { + return apiResponse{}, err + } + var created userRow + err = s.store.InTx(ctx, func(tx webTx) error { + u, err := tx.CreateUser(ctx, req.Username, req.Role, hash, c.Now) + if errors.Is(err, errUsernameTaken) { + return &apiError{Status: http.StatusConflict, Message: msgUsernameTaken} + } + if err != nil { + return err + } + created = u + c.setTargetUser(u) + c.recordChange(nil, auditUserJSON(u)) + return c.commitChange(ctx, tx, http.StatusCreated) + }) + if err != nil { + return apiResponse{}, err + } + return apiResponse{Status: http.StatusCreated, Body: userListItemOf(created, 0)}, nil +} + +type userZoneItem struct { + Zone string `json:"zone"` + Exists bool `json:"exists"` +} + +type userDetail struct { + Username string `json:"username"` + Role string `json:"role"` + CreatedAt string `json:"created_at"` + LastLoginAt *string `json:"last_login_at"` + DeletedAt *string `json:"deleted_at"` + Zones []userZoneItem `json:"zones"` +} + +func handleUserRead(ctx context.Context, c *apiContext) (apiResponse, error) { + u, err := c.lookupUser(ctx) + if err != nil { + return apiResponse{}, err + } + zones, err := c.Server.store.UserZones(ctx, u.ID) + if err != nil { + return apiResponse{}, err + } + out := userDetail{ + Username: u.Username, + Role: u.Role, + CreatedAt: apiTime(u.CreatedAt), + LastLoginAt: apiNullTime(u.LastLoginAt), + DeletedAt: apiNullTime(u.DeletedAt), + Zones: make([]userZoneItem, 0, len(zones)), + } + for _, z := range zones { + out.Zones = append(out.Zones, userZoneItem{Zone: z.Zone, Exists: z.ZoneExists}) + } + return okJSON(out), nil +} + +func (c *apiContext) foreignUsername() (string, error) { + username, err := c.pathUsername() + if err != nil { + return "", err + } + if isOwnAccount(c.Principal, username) { + c.setTargetUser(c.Principal.User) + return "", ownAccountError() + } + return username, nil +} + +type userRoleRequest struct { + Role string `json:"role"` +} + +func lockAdminsAndTarget(ctx context.Context, c *apiContext, tx webTx, username string) (userRow, []userRow, error) { + admins, err := tx.LockActiveAdmins(ctx) + if err != nil { + return userRow{}, nil, err + } + u, err := activeTargetForUpdate(ctx, c, tx, username) + return u, admins, err +} + +func handleUserRole(ctx context.Context, c *apiContext) (apiResponse, error) { + username, err := c.foreignUsername() + if err != nil { + return apiResponse{}, err + } + var req userRoleRequest + if err := c.decodeJSON(&req); err != nil { + return apiResponse{}, err + } + if !validRole(req.Role) { + return apiResponse{}, fieldError("role", roleFieldMessage()) + } + err = c.Server.store.InTx(ctx, func(tx webTx) error { + u, admins, err := lockAdminsAndTarget(ctx, c, tx, username) + if err != nil { + return err + } + if u.Role == req.Role { + return nil + } + if leavesNoActiveAdmin(u, admins) { + return lastAdminError() + } + if err := tx.SetRole(ctx, u.ID, req.Role, c.Now); err != nil { + return err + } + after := u + after.Role = req.Role + c.recordChange(auditUserJSON(u), auditUserJSON(after)) + return c.commitChange(ctx, tx, http.StatusNoContent) + }) + if err != nil { + return apiResponse{}, err + } + return noContent(), nil +} + +type userPasswordRequest struct { + Password string `json:"password"` +} + +func handleUserPassword(ctx context.Context, c *apiContext) (apiResponse, error) { + username, err := c.foreignUsername() + if err != nil { + return apiResponse{}, err + } + var req userPasswordRequest + if err := c.decodeJSON(&req); err != nil { + return apiResponse{}, err + } + if err := checkPasswordRules(req.Password); err != nil { + return apiResponse{}, passwordFieldError("password", err) + } + s := c.Server + hash, err := s.hashPassword(req.Password) + if err != nil { + return apiResponse{}, err + } + err = s.store.InTx(ctx, func(tx webTx) error { + u, err := activeTargetForUpdate(ctx, c, tx, username) + if err != nil { + return err + } + if err := tx.SetPassword(ctx, u.ID, hash, c.Now); err != nil { + return err + } + if _, err := tx.DeleteUserSessions(ctx, u.ID); err != nil { + return err + } + snapshot := auditUserJSON(u) + c.recordChange(snapshot, snapshot) + return c.commitChange(ctx, tx, http.StatusNoContent) + }) + if err != nil { + return apiResponse{}, err + } + return noContent(), nil +} + +type confirmRequest struct { + Confirm string `json:"confirm"` +} + +func handleUserDelete(ctx context.Context, c *apiContext) (apiResponse, error) { + username, err := c.foreignUsername() + if err != nil { + return apiResponse{}, err + } + var req confirmRequest + if err := c.decodeJSON(&req); err != nil { + return apiResponse{}, err + } + if req.Confirm != username { + return apiResponse{}, fieldError("confirm", msgConfirmMismatch) + } + err = c.Server.store.InTx(ctx, func(tx webTx) error { + u, admins, err := lockAdminsAndTarget(ctx, c, tx, username) + if err != nil { + return err + } + if leavesNoActiveAdmin(u, admins) { + return lastAdminError() + } + if err := tx.MarkDeleted(ctx, u.ID, c.Now); err != nil { + return err + } + if _, err := tx.DeleteUserSessions(ctx, u.ID); err != nil { + return err + } + after := u + after.DeletedAt = sql.NullTime{Time: dbTime(c.Now), Valid: true} + c.recordChange(auditUserJSON(u), auditUserJSON(after)) + return c.commitChange(ctx, tx, http.StatusNoContent) + }) + if err != nil { + return apiResponse{}, err + } + return noContent(), nil +} + +type auditItem struct { + ID int64 `json:"id"` + Time string `json:"time"` + Actor string `json:"actor"` + Origin string `json:"origin"` + Operation string `json:"operation"` + Status *int64 `json:"status"` + Error *string `json:"error"` + Zone *string `json:"zone"` + RecordID *int64 `json:"record_id"` + TargetUser *string `json:"target_user"` + Before json.RawMessage `json:"before"` + After json.RawMessage `json:"after"` +} + +type auditResponse struct { + Entries []auditItem `json:"entries"` + NextBeforeID *int64 `json:"next_before_id"` +} + +func nullInt(v sql.NullInt64) *int64 { + if !v.Valid { + return nil + } + return &v.Int64 +} + +func nullString(v sql.NullString) *string { + if !v.Valid { + return nil + } + return &v.String +} + +func rawJSON(b []byte) json.RawMessage { + if len(b) == 0 || !json.Valid(b) { + return json.RawMessage("null") + } + return json.RawMessage(b) +} + +func auditItemOf(r auditRow) auditItem { + return auditItem{ + ID: r.ID, + Time: apiTime(r.Time), + Actor: r.Actor, + Origin: r.Origin, + Operation: r.Operation, + Status: nullInt(r.Status), + Error: nullString(r.Error), + Zone: nullString(r.Zone), + RecordID: nullInt(r.RecordID), + TargetUser: nullString(r.TargetUsername), + Before: rawJSON(r.Before), + After: rawJSON(r.After), + } +} + +func parseAuditFilter(q url.Values) (auditFilter, error) { + f := auditFilter{Limit: auditDefaultLimit} + if v := q.Get("zone"); v != "" { + zone, err := normalizeZone(v) + if err != nil { + return auditFilter{}, badParameter("zone") + } + f.Zone = zone + } + if v := q.Get("actor"); v != "" { + if len([]rune(v)) > auditMaxActorRunes { + return auditFilter{}, badParameter("actor") + } + f.Actor = v + } + if v := q.Get("operation"); v != "" { + if !knownOperation(v) { + return auditFilter{}, badParameter("operation") + } + f.Operation = v + } + switch v := q.Get("kind"); v { + case "", auditKindRead, auditKindChange: + f.Kind = v + default: + return auditFilter{}, badParameter("kind") + } + switch v := q.Get("outcome"); v { + case "", auditOutcomeSuccess, auditOutcomeError: + f.Outcome = v + default: + return auditFilter{}, badParameter("outcome") + } + if v := q.Get("before_id"); v != "" { + n, err := parsePositive(v, 1<<62) + if err != nil { + return auditFilter{}, badParameter("before_id") + } + f.BeforeID = n + } + if v := q.Get("limit"); v != "" { + n, err := parsePositive(v, auditMaxLimit) + if err != nil { + return auditFilter{}, badParameter("limit") + } + f.Limit = int(n) + } + return f, nil +} + +func parsePositive(s string, max int64) (int64, error) { + if s == "" || len(s) > 19 { + return 0, strconv.ErrSyntax + } + for _, r := range s { + if r < '0' || r > '9' { + return 0, strconv.ErrSyntax + } + } + n, err := strconv.ParseInt(s, 10, 64) + if err != nil || n < 1 || n > max { + return 0, strconv.ErrRange + } + return n, nil +} + +func handleAuditRead(ctx context.Context, c *apiContext) (apiResponse, error) { + f, err := parseAuditFilter(c.Request.URL.Query()) + if err != nil { + return apiResponse{}, err + } + if !c.Principal.isAdmin() { + f.RestrictToUserID = sql.NullInt64{Int64: c.Principal.User.ID, Valid: true} + } + delegated := map[string]bool{} + if !c.Principal.isAdmin() { + zones, err := c.Server.store.UserZones(ctx, c.Principal.User.ID) + if err != nil { + return apiResponse{}, err + } + for _, z := range zones { + delegated[z.Zone] = true + } + } + limit := f.Limit + f.Limit = limit + 1 + rows, err := c.Server.store.ListAudit(ctx, f) + if err != nil { + return apiResponse{}, err + } + rows = slices.DeleteFunc(rows, func(r auditRow) bool { return !auditVisibleTo(c.Principal, r.auditEntry, delegated) }) + resp := auditResponse{Entries: make([]auditItem, 0, min(len(rows), limit))} + for i, r := range rows { + if i == limit { + next := rows[limit-1].ID + resp.NextBeforeID = &next + break + } + resp.Entries = append(resp.Entries, auditItemOf(r)) + } + return okJSON(resp), nil +} + func zoneAPIHandlers(s *WebServer) map[string]apiHandler { h := zoneHandlers{s} return map[string]apiHandler{ diff --git a/handlers_api_test.go b/handlers_api_test.go index c1e9c71..c320603 100644 --- a/handlers_api_test.go +++ b/handlers_api_test.go @@ -9,14 +9,872 @@ import ( "database/sql/driver" "encoding/json" "errors" + "fmt" "net/http" "net/http/httptest" + "net/url" "slices" "strconv" "strings" "testing" + "time" ) +func (h *webHarness) stored(username string) userRow { + h.t.Helper() + u, err := h.store.UserByUsername(context.Background(), username) + if err != nil { + h.t.Fatalf("%s: %v", username, err) + } + return u +} + +func expectError(t *testing.T, res webResult, status int, body string) { + t.Helper() + if res.status != status || res.body != body { + t.Fatalf("got %d %s, want %d %s", res.status, res.body, status, body) + } +} + +func expectChange(t *testing.T, res webResult, operation string, status int, target int64, before, after string) auditEntry { + t.Helper() + e := expectOneAudit(t, res, operation, status) + if !res.audit[0].inTx { + t.Fatalf("%s: change row not written in the change transaction", operation) + } + if target != 0 && (!e.TargetUserID.Valid || e.TargetUserID.Int64 != target) { + t.Fatalf("%s: target %v", operation, e.TargetUserID) + } + if string(e.Before) != before || string(e.After) != after { + t.Fatalf("%s: before %s after %s", operation, e.Before, e.After) + } + return e +} + +func expectNoChange(t *testing.T, res webResult, operation string, status int) auditEntry { + t.Helper() + e := expectOneAudit(t, res, operation, status) + if res.audit[0].inTx || e.Before != nil || e.After != nil { + t.Fatalf("%s: unexpected change row %+v", operation, res.audit[0]) + } + return e +} + +func userSnapshot(u userRow) string { + return string(auditUserJSON(u)) +} + +func TestAccountRead(t *testing.T) { + h := newWebHarness(t) + admin := h.user("admin", roleAdmin) + alice := h.user("alice", roleUser) + h.store.addZone(testZone) + h.store.delegate(testZone, alice) + h.store.delegate("gone.org.", alice) + h.store.delegate(testZone, admin) + res := h.api("GET", "/account", h.login(alice), "") + if res.status != 200 || res.body != `{"username":"alice","role":"user","zones":["example.org."]}` { + t.Fatalf("%d %s", res.status, res.body) + } + expectNoChange(t, res, opAccountRead, 200) + res = h.api("GET", "/account", h.login(admin), "") + if res.body != `{"username":"admin","role":"admin","zones":[]}` { + t.Fatal(res.body) + } + h.store.failOn["UserZones"] = errDatabase + expectError(t, h.api("GET", "/account", h.login(alice), ""), 503, `{"error":"database unavailable"}`) +} + +func TestPasswordChange(t *testing.T) { + h := newWebHarness(t) + alice := h.user("alice", roleUser) + token := h.login(alice) + other := h.login(alice) + path := "/account/password" + res := h.api("PUT", path, token, `{"current":"wrong-password","password":"brand-new-password"}`) + expectError(t, res, 422, `{"error":"invalid password change","fields":{"current":"current password is wrong"}}`) + expectNoChange(t, res, opPasswordChange, 422) + res = h.api("PUT", path, token, `{"current":"wrong","password":"short"}`) + expectError(t, res, 422, `{"error":"invalid password change","fields":{"current":"current password is wrong","password":"password must be 12 to 256 bytes"}}`) + res = h.api("PUT", path, token, `{"current":"`+testPassword+`","password":"short"}`) + expectError(t, res, 422, `{"error":"invalid password change","fields":{"password":"password must be 12 to 256 bytes"}}`) + res = h.api("PUT", path, token, `{"current":"`+testPassword+`"`) + expectError(t, res, 400, `{"error":"malformed JSON"}`) + expectNoChange(t, res, opPasswordChange, 400) + res = h.do(webRequest{method: "PUT", path: apiPrefix + path, token: token, body: `{}`, ctype: "text/plain"}) + expectError(t, res, 415, `{"error":"content type must be application/json"}`) + expectError(t, h.api("PUT", path, token, ""), 400, `{"error":"request body is required"}`) + + h.s.hashPassword = func(string) (string, error) { return "", errors.New("argon2 broke") } + expectError(t, h.api("PUT", path, token, `{"current":"`+testPassword+`","password":"brand-new-password"}`), 500, `{"error":"internal error"}`) + h.s.hashPassword = func(p string) (string, error) { return fakeHash(p), nil } + h.store.failOn["DeleteUserSessionsExcept"] = errors.New("boom") + expectError(t, h.api("PUT", path, token, `{"current":"`+testPassword+`","password":"brand-new-password"}`), 500, `{"error":"internal error"}`) + if h.stored("alice").PasswordHash != fakeHash(testPassword) { + t.Fatal("failed change kept") + } + delete(h.store.failOn, "DeleteUserSessionsExcept") + + res = h.api("PUT", path, token, `{"current":"`+testPassword+`","password":"brand-new-password"}`) + if res.status != 204 || res.body != "" { + t.Fatalf("%d %s", res.status, res.body) + } + expectChange(t, res, opPasswordChange, 204, alice.ID, userSnapshot(alice), userSnapshot(alice)) + if h.stored("alice").PasswordHash != fakeHash("brand-new-password") { + t.Fatal("password not changed") + } + if h.api("GET", "/account", token, "").status != 200 || h.api("GET", "/account", other, "").status != 401 { + t.Fatal("other sessions must end, the current one must stay") + } + gone := h.stored("alice") + gone.DeletedAt = sql.NullTime{Time: webNow, Valid: true} + h.store.onLock = nil + h.store.failOn = map[string]error{} + h.store.setUser(gone) + h.s.store = &deletedDuringRequest{fakeWebStore: h.store, user: gone} + res = h.api("PUT", path, token, `{"current":"brand-new-password","password":"another-password"}`) + expectError(t, res, 404, `{"error":"user not found"}`) +} + +type deletedDuringRequest struct { + *fakeWebStore + user userRow +} + +func (d *deletedDuringRequest) SessionByTokenHash(ctx context.Context, h []byte) (sessionWithUser, error) { + s, err := d.fakeWebStore.SessionByTokenHash(ctx, h) + s.User.DeletedAt = sql.NullTime{} + return s, err +} + +func delegationHarness(t *testing.T) (*webHarness, string) { + h := newWebHarness(t) + admin := h.user("admin", roleAdmin) + h.user("root", roleAdmin) + bob := h.user("bob", roleUser) + carol := h.user("carol", roleUser) + gone := h.user("gone", roleUser) + gone.DeletedAt = sql.NullTime{Time: webNow.Add(-time.Hour), Valid: true} + h.store.setUser(gone) + h.store.addZone(testZone) + h.store.addZone(otherZone) + h.store.delegate(testZone, carol) + h.store.delegate(testZone, gone) + h.store.delegate(testZone, h.users["root"]) + h.store.delegate("vanished.org.", bob) + _ = bob + return h, h.login(admin) +} + +func TestDelegationList(t *testing.T) { + h, token := delegationHarness(t) + h.store.delegate(testZone, h.users["bob"]) + res := h.api("GET", "/zones/EXAMPLE.org/users", token, "") + if res.status != 200 || res.body != `{"users":[{"username":"bob","role":"user"},{"username":"carol","role":"user"}]}` { + t.Fatalf("%d %s", res.status, res.body) + } + expectNoChange(t, res, opDelegationList, 200) + res = h.api("GET", "/zones/"+otherZone+"/users", token, "") + if res.body != `{"users":[]}` { + t.Fatal(res.body) + } + res = h.api("GET", "/zones/missing.org/users", token, "") + expectError(t, res, 404, `{"error":"zone not found"}`) + expectNoChange(t, res, opDelegationList, 404) + h.store.failOn["ZoneUsers"] = errDatabase + expectError(t, h.api("GET", "/zones/example.org/users", token, ""), 503, `{"error":"database unavailable"}`) +} + +func TestDelegationGrant(t *testing.T) { + h, token := delegationHarness(t) + bob := h.users["bob"] + res := h.api("PUT", "/zones/Example.org/users/bob", token, "") + if res.status != 204 || !h.store.hasDelegation(testZone, bob.ID) { + t.Fatalf("%d %s", res.status, res.body) + } + e := expectChange(t, res, opDelegationGrant, 204, bob.ID, "", `{"zone":"example.org.","username":"bob"}`) + if e.Zone.String != testZone { + t.Fatal(e.Zone) + } + res = h.api("PUT", "/zones/example.org./users/bob", token, "") + if res.status != 204 { + t.Fatal(res.status) + } + if e := expectNoChange(t, res, opDelegationGrant, 204); e.TargetUserID.Int64 != bob.ID { + t.Fatal("target missing on an idempotent grant") + } + cases := []struct { + path, body string + status int + }{ + {"/zones/missing.org/users/bob", `{"error":"zone not found"}`, 404}, + {"/zones/bad!zone/users/bob", `{"error":"zone not found"}`, 404}, + {"/zones/example.org/users/nobody", `{"error":"user not found"}`, 404}, + {"/zones/example.org/users/Bob", `{"error":"user not found"}`, 404}, + {"/zones/example.org/users/gone", `{"error":"user not found"}`, 404}, + {"/zones/example.org/users/root", `{"error":"zones cannot be delegated to admins","fields":{"username":"user is an admin and needs no delegation"}}`, 422}, + {"/zones/example.org/users/admin", `{"error":"zones cannot be delegated to admins","fields":{"username":"user is an admin and needs no delegation"}}`, 422}, + } + for _, c := range cases { + res := h.api("PUT", c.path, token, "") + expectError(t, res, c.status, c.body) + expectNoChange(t, res, opDelegationGrant, c.status) + } + if h.store.hasDelegation(otherZone, bob.ID) { + t.Fatal("unexpected delegation") + } + h.store.failOn["GrantDelegation"] = errors.New("deadlock") + expectError(t, h.api("PUT", "/zones/other.org/users/bob", token, ""), 500, `{"error":"internal error"}`) + if h.store.hasDelegation(otherZone, bob.ID) { + t.Fatal("failed grant kept") + } +} + +func TestDelegationRevoke(t *testing.T) { + h, token := delegationHarness(t) + carol, bob := h.users["carol"], h.users["bob"] + res := h.api("DELETE", "/zones/example.org/users/carol", token, "") + if res.status != 204 || h.store.hasDelegation(testZone, carol.ID) { + t.Fatalf("%d %s", res.status, res.body) + } + expectChange(t, res, opDelegationRevoke, 204, carol.ID, `{"zone":"example.org.","username":"carol"}`, "") + res = h.api("DELETE", "/zones/example.org/users/carol", token, "") + expectError(t, res, 404, `{"error":"delegation not found"}`) + expectNoChange(t, res, opDelegationRevoke, 404) + res = h.api("DELETE", "/zones/vanished.org/users/bob", token, "") + if res.status != 204 || h.store.hasDelegation("vanished.org.", bob.ID) { + t.Fatal("delegation of a missing zone not revoked", res.status) + } + res = h.api("DELETE", "/zones/example.org/users/root", token, "") + if res.status != 204 { + t.Fatal("delegation kept by a promoted user not revocable", res.status) + } + for _, path := range []string{"/zones/example.org/users/gone", "/zones/example.org/users/nobody", "/zones/example.org/users/-x"} { + res = h.api("DELETE", path, token, "") + expectError(t, res, 404, `{"error":"user not found"}`) + } + if !h.store.hasDelegation(testZone, h.users["gone"].ID) { + t.Fatal("deleted user's delegation changed") + } + expectError(t, h.api("DELETE", "/zones/bad!/users/bob", token, ""), 404, `{"error":"zone not found"}`) +} + +func usersHarness(t *testing.T) (*webHarness, string) { + h := newWebHarness(t) + admin := h.user("admin", roleAdmin) + h.user("root", roleAdmin) + bob := h.user("bob", roleUser) + gone := h.user("gone", roleUser) + gone.DeletedAt = sql.NullTime{Time: webNow.Add(-time.Hour), Valid: true} + gone.LastLoginAt = sql.NullTime{Time: webNow.Add(-2 * time.Hour), Valid: true} + h.store.setUser(gone) + h.users["gone"] = gone + h.store.addZone(testZone) + h.store.delegate(testZone, bob) + h.store.delegate("vanished.org.", bob) + return h, h.login(admin) +} + +func TestAPIUserList(t *testing.T) { + h, token := usersHarness(t) + created := `"created_at":"2026-11-16T12:00:00Z"` + res := h.api("GET", "/users", token, "") + want := `{"users":[{"username":"admin","role":"admin","zone_count":0,` + created + `,"last_login_at":null,"deleted_at":null},` + + `{"username":"bob","role":"user","zone_count":2,` + created + `,"last_login_at":null,"deleted_at":null},` + + `{"username":"root","role":"admin","zone_count":0,` + created + `,"last_login_at":null,"deleted_at":null}]}` + if res.status != 200 || res.body != want { + t.Fatalf("%d %s", res.status, res.body) + } + expectNoChange(t, res, opUserList, 200) + for _, q := range []string{"?deleted=false", "?deleted=", "?other=1"} { + if r := h.api("GET", "/users"+q, token, ""); r.body != want { + t.Fatal(q, r.body) + } + } + res = h.api("GET", "/users?deleted=true", token, "") + if !strings.Contains(res.body, `{"username":"gone","role":"user","zone_count":0,`+created+`,"last_login_at":"2026-11-18T10:00:00Z","deleted_at":"2026-11-18T11:00:00Z"}`) { + t.Fatal(res.body) + } + res = h.api("GET", "/users?deleted=yes", token, "") + expectError(t, res, 400, `{"error":"invalid parameter deleted"}`) + expectNoChange(t, res, opUserList, 400) +} + +func TestAPIUserCreate(t *testing.T) { + h, token := usersHarness(t) + h.clock.advance(1500 * time.Millisecond) + res := h.api("POST", "/users", token, `{"username":"dora","role":"user","password":"dora-password-1"}`) + if res.status != 201 || res.body != `{"username":"dora","role":"user","zone_count":0,"created_at":"2026-11-18T12:00:01.5Z","last_login_at":null,"deleted_at":null}` { + t.Fatalf("%d %s", res.status, res.body) + } + dora := h.stored("dora") + if dora.PasswordHash != fakeHash("dora-password-1") || dora.Role != roleUser { + t.Fatalf("%+v", dora) + } + expectChange(t, res, opUserCreate, 201, dora.ID, "", userSnapshot(dora)) + for _, name := range []string{"dora", "gone", "admin"} { + res = h.api("POST", "/users", token, `{"username":"`+name+`","role":"admin","password":"long-enough-pw"}`) + expectError(t, res, 409, `{"error":"username already used"}`) + expectNoChange(t, res, opUserCreate, 409) + } + cases := map[string]string{ + `{"username":"Bad Name","role":"user","password":"long-enough-pw"}`: `{"error":"invalid user","fields":{"username":"username must be 1 to 64 characters of lowercase letters, digits, dots, underscores and hyphens, starting with a letter or digit"}}`, + `{"username":"cli","role":"user","password":"long-enough-pw"}`: `{"error":"invalid user","fields":{"username":"username is reserved"}}`, + `{"username":"ed","role":"root","password":"long-enough-pw"}`: `{"error":"invalid user","fields":{"role":"must be admin or user"}}`, + `{"username":"ed","role":"user","password":"short"}`: `{"error":"invalid user","fields":{"password":"password must be 12 to 256 bytes"}}`, + `{}`: `{"error":"invalid user","fields":{"password":"password must be 12 to 256 bytes","role":"must be admin or user","username":"username must be 1 to 64 characters of lowercase letters, digits, dots, underscores and hyphens, starting with a letter or digit"}}`, + `{"username":"ed","role":"user","password":12}`: `{"error":"invalid field type","fields":{"password":"must be a string"}}`, + `{"username":"ed","role":"user","password":"x","a":1}`: `{"error":"request body has an unknown field"}`, + } + for body, want := range cases { + res := h.api("POST", "/users", token, body) + if res.status == 422 { + expectError(t, res, 422, want) + } else { + expectError(t, res, 400, want) + } + } + h.s.hashPassword = func(string) (string, error) { return "", errors.New("argon2 failure") } + expectError(t, h.api("POST", "/users", token, `{"username":"ed","role":"user","password":"long-enough-pw"}`), 500, `{"error":"internal error"}`) +} + +func TestAPIUserRead(t *testing.T) { + h, token := usersHarness(t) + bob := h.users["bob"] + res := h.api("GET", "/users/bob", token, "") + want := `{"username":"bob","role":"user","created_at":"2026-11-16T12:00:00Z","last_login_at":null,"deleted_at":null,"zones":[{"zone":"example.org.","exists":true},{"zone":"vanished.org.","exists":false}]}` + if res.status != 200 || res.body != want { + t.Fatalf("%d %s", res.status, res.body) + } + if e := expectNoChange(t, res, opUserRead, 200); e.TargetUserID.Int64 != bob.ID { + t.Fatal("target") + } + res = h.api("GET", "/users/gone", token, "") + if res.status != 200 || !strings.Contains(res.body, `"deleted_at":"2026-11-18T11:00:00Z","zones":[]`) { + t.Fatal(res.body) + } + for _, name := range []string{"nobody", "UPPER", "a%20b"} { + res = h.api("GET", "/users/"+name, token, "") + expectError(t, res, 404, `{"error":"user not found"}`) + if e := expectNoChange(t, res, opUserRead, 404); e.TargetUserID.Valid { + t.Fatal("target on a missing user") + } + } + h.store.failOn["UserByUsername"] = errDatabase + expectError(t, h.api("GET", "/users/bob", token, ""), 503, `{"error":"database unavailable"}`) + delete(h.store.failOn, "UserByUsername") + h.store.failOn["UserZones"] = errors.New("x") + expectError(t, h.api("GET", "/users/bob", token, ""), 500, `{"error":"internal error"}`) +} + +func TestAPIUserRole(t *testing.T) { + h, token := usersHarness(t) + bob := h.users["bob"] + res := h.api("PUT", "/users/bob/role", token, `{"role":"admin"}`) + if res.status != 204 || h.stored("bob").Role != roleAdmin { + t.Fatalf("%d %s", res.status, res.body) + } + promoted := bob + promoted.Role = roleAdmin + expectChange(t, res, opUserRole, 204, bob.ID, userSnapshot(bob), userSnapshot(promoted)) + if !h.store.hasDelegation(testZone, bob.ID) { + t.Fatal("promotion dropped delegations") + } + res = h.api("PUT", "/users/bob/role", token, `{"role":"admin"}`) + if res.status != 204 { + t.Fatal(res.status) + } + expectNoChange(t, res, opUserRole, 204) + if h.store.called("LockActiveAdmins") != 2 { + t.Fatal("active admins not locked in the change transaction") + } + res = h.api("PUT", "/users/admin/role", token, `{"role":"user"}`) + expectError(t, res, 403, `{"error":"use the account page to change your own account"}`) + if e := expectNoChange(t, res, opUserRole, 403); e.TargetUserID.Int64 != 1 { + t.Fatal("target on own account refusal") + } + for _, c := range []struct { + path, body, want string + status int + }{ + {"/users/gone/role", `{"role":"admin"}`, `{"error":"user not found"}`, 404}, + {"/users/nobody/role", `{"role":"admin"}`, `{"error":"user not found"}`, 404}, + {"/users/bob/role", `{"role":"owner"}`, `{"error":"invalid role","fields":{"role":"must be admin or user"}}`, 422}, + {"/users/bob/role", `{"role":5}`, `{"error":"invalid field type","fields":{"role":"must be a string"}}`, 422}, + {"/users/bob/role", ``, `{"error":"request body is required"}`, 400}, + } { + res := h.api("PUT", c.path, token, c.body) + expectError(t, res, c.status, c.want) + expectNoChange(t, res, opUserRole, c.status) + } + if h.stored("gone").Role != roleUser { + t.Fatal("deleted user changed") + } + + h.store.onLock = func(st *fakeWebState) { + for i := range st.users { + if st.users[i].Username != "root" { + st.users[i].Role = roleUser + } + } + } + res = h.api("PUT", "/users/root/role", token, `{"role":"user"}`) + expectError(t, res, 409, `{"error":"the last active admin cannot be demoted or deleted"}`) + expectNoChange(t, res, opUserRole, 409) + if h.stored("root").Role != roleAdmin { + t.Fatal("last admin demoted") + } + h.store.onLock = nil + h.store.failOn["SetRole"] = errors.New("x") + expectError(t, h.api("PUT", "/users/root/role", token, `{"role":"user"}`), 500, `{"error":"internal error"}`) + delete(h.store.failOn, "SetRole") + h.store.failOn["LockActiveAdmins"] = errLockTimeout + expectError(t, h.api("PUT", "/users/root/role", token, `{"role":"user"}`), 503, `{"error":"zone busy"}`) +} + +func TestAPIUserPassword(t *testing.T) { + h, token := usersHarness(t) + bob := h.users["bob"] + t1, t2 := h.login(bob), h.login(bob) + res := h.api("PUT", "/users/bob/password", token, `{"password":"reset-password-1"}`) + if res.status != 204 || h.stored("bob").PasswordHash != fakeHash("reset-password-1") { + t.Fatalf("%d %s", res.status, res.body) + } + expectChange(t, res, opUserPassword, 204, bob.ID, userSnapshot(bob), userSnapshot(bob)) + if h.store.sessionCount(bob.ID) != 0 || h.api("GET", "/account", t1, "").status != 401 || h.api("GET", "/account", t2, "").status != 401 { + t.Fatal("sessions not ended") + } + expectError(t, h.api("PUT", "/users/admin/password", token, `{"password":"reset-password-1"}`), 403, `{"error":"use the account page to change your own account"}`) + expectError(t, h.api("PUT", "/users/gone/password", token, `{"password":"reset-password-1"}`), 404, `{"error":"user not found"}`) + expectError(t, h.api("PUT", "/users/nobody/password", token, `{"password":"reset-password-1"}`), 404, `{"error":"user not found"}`) + expectError(t, h.api("PUT", "/users/bob/password", token, `{"password":"tiny"}`), 422, `{"error":"invalid password","fields":{"password":"password must be 12 to 256 bytes"}}`) + expectError(t, h.api("PUT", "/users/bob/password", token, `{"password":"bad\u0007-password-x"}`), 422, `{"error":"invalid password","fields":{"password":"password must not contain control characters"}}`) + h.s.hashPassword = func(string) (string, error) { return "", errors.New("x") } + expectError(t, h.api("PUT", "/users/bob/password", token, `{"password":"reset-password-2"}`), 500, `{"error":"internal error"}`) + h.s.hashPassword = func(p string) (string, error) { return fakeHash(p), nil } + h.store.failOn["DeleteUserSessions"] = errors.New("x") + expectError(t, h.api("PUT", "/users/bob/password", token, `{"password":"reset-password-2"}`), 500, `{"error":"internal error"}`) + if h.stored("bob").PasswordHash != fakeHash("reset-password-1") { + t.Fatal("rolled back change kept") + } +} + +func TestAPIUserDelete(t *testing.T) { + h, token := usersHarness(t) + bob := h.users["bob"] + bt := h.login(bob) + res := h.api("DELETE", "/users/bob", token, `{"confirm":"bob "}`) + expectError(t, res, 422, `{"error":"invalid confirm","fields":{"confirm":"confirmation does not match"}}`) + expectNoChange(t, res, opUserDelete, 422) + expectError(t, h.api("DELETE", "/users/bob", token, ""), 400, `{"error":"request body is required"}`) + h.clock.advance(time.Second) + res = h.api("DELETE", "/users/bob", token, `{"confirm":"bob"}`) + stored := h.stored("bob") + if res.status != 204 || !stored.DeletedAt.Valid || !stored.DeletedAt.Time.Equal(webNow.Add(time.Second)) { + t.Fatalf("%d %s %+v", res.status, res.body, stored) + } + after := bob + after.DeletedAt = sql.NullTime{Time: webNow.Add(time.Second), Valid: true} + expectChange(t, res, opUserDelete, 204, bob.ID, userSnapshot(bob), userSnapshot(after)) + if h.api("GET", "/account", bt, "").status != 401 || h.store.sessionCount(bob.ID) != 0 { + t.Fatal("sessions survive deletion") + } + if !h.store.hasDelegation(testZone, bob.ID) { + t.Fatal("delegations must stay") + } + expectError(t, h.api("DELETE", "/users/bob", token, `{"confirm":"bob"}`), 404, `{"error":"user not found"}`) + expectError(t, h.api("DELETE", "/users/admin", token, `{"confirm":"admin"}`), 403, `{"error":"use the account page to change your own account"}`) + h.store.onLock = func(st *fakeWebState) { + st.users[0].DeletedAt = sql.NullTime{Time: webNow, Valid: true} + } + res = h.api("DELETE", "/users/root", token, `{"confirm":"root"}`) + expectError(t, res, 409, `{"error":"the last active admin cannot be demoted or deleted"}`) + if h.stored("root").DeletedAt.Valid || h.stored("admin").DeletedAt.Valid { + t.Fatal("rolled back state kept") + } + h.store.onLock = nil + res = h.api("DELETE", "/users/root", token, `{"confirm":"root"}`) + if res.status != 204 { + t.Fatal("admin with another active admin not deletable", res.status) + } + h.store.failOn["MarkDeleted"] = errors.New("x") + h.user("eve", roleUser) + expectError(t, h.api("DELETE", "/users/eve", token, `{"confirm":"eve"}`), 500, `{"error":"internal error"}`) +} + +func auditHarness(t *testing.T) (*webHarness, string, string) { + h := newWebHarness(t) + admin := h.user("admin", roleAdmin) + alice := h.user("alice", roleUser) + bob := h.user("bob", roleUser) + h.store.addZone(testZone) + h.store.delegate(testZone, alice) + add := func(u userRow, op, zone string, status int64, before, after string) { + e := auditEntry{Time: webNow, UserID: sql.NullInt64{Int64: u.ID, Valid: true}, Actor: u.Username, Origin: "192.0.2.1", Operation: op, Status: sql.NullInt64{Int64: status, Valid: true}} + if zone != "" { + e.Zone = sql.NullString{String: zone, Valid: true} + } + if before != "" { + e.Before = []byte(before) + } + if after != "" { + e.After = []byte(after) + } + if status >= 400 { + e.Error = sql.NullString{String: "failed", Valid: true} + } + _, _ = h.store.InsertAudit(context.Background(), e) + } + add(admin, opZoneCreate, testZone, 201, "", `{"id":1}`) + add(bob, opZoneRead, otherZone, 404, "", "") + add(alice, opAccountRead, "", 200, "", "") + add(bob, opRecordUpdate, testZone, 200, `{"ttl":1}`, `{"ttl":2}`) + add(admin, opUserRole, "", 204, `{"role":"user"}`, `{"role":"admin"}`) + _, _ = h.store.InsertAudit(context.Background(), auditEntry{Time: webNow, Actor: "cli", Origin: "local", Operation: opUserCreate, TargetUserID: sql.NullInt64{Int64: bob.ID, Valid: true}, After: []byte(`{"id":3}`)}) + return h, h.login(admin), h.login(alice) +} + +type auditPage struct { + Entries []struct { + ID int64 `json:"id"` + Time string `json:"time"` + Actor string `json:"actor"` + Origin string `json:"origin"` + Operation string `json:"operation"` + Status *int64 `json:"status"` + Error *string `json:"error"` + Zone *string `json:"zone"` + RecordID *int64 `json:"record_id"` + TargetUser *string `json:"target_user"` + Before json.RawMessage `json:"before"` + After json.RawMessage `json:"after"` + } `json:"entries"` + NextBeforeID *int64 `json:"next_before_id"` +} + +func (r webResult) auditPage(t *testing.T) auditPage { + t.Helper() + var p auditPage + if err := json.Unmarshal([]byte(r.body), &p); err != nil { + t.Fatal(r.body, err) + } + return p +} + +func TestAuditRead(t *testing.T) { + h, adminToken, aliceToken := auditHarness(t) + res := h.api("GET", "/audit", adminToken, "") + if res.status != 200 { + t.Fatal(res.status, res.body) + } + expectNoChange(t, res, opAuditRead, 200) + p := res.auditPage(t) + if len(p.Entries) != 6 || p.NextBeforeID != nil || p.Entries[0].ID != 6 || p.Entries[5].ID != 1 { + t.Fatalf("%s", res.body) + } + cli := p.Entries[0] + if cli.Actor != "cli" || cli.Status != nil || cli.Error != nil || cli.Zone != nil || *cli.TargetUser != "bob" || string(cli.After) != `{"id":3}` || string(cli.Before) != "null" || cli.Time != "2026-11-18T12:00:00Z" { + t.Fatalf("%+v", cli) + } + if !strings.Contains(res.body, `{"id":4,"time":"2026-11-18T12:00:00Z","actor":"bob","origin":"192.0.2.1","operation":"record_update","status":200,"error":null,"zone":"example.org.","record_id":null,"target_user":null,"before":{"ttl":1},"after":{"ttl":2}}`) { + t.Fatal(res.body) + } + res = h.api("GET", "/audit?limit=2", adminToken, "") + p = res.auditPage(t) + if len(p.Entries) != 2 || p.NextBeforeID == nil || *p.NextBeforeID != 6 { + t.Fatal(res.body) + } + res = h.api("GET", "/audit?limit=2&before_id=6", adminToken, "") + p = res.auditPage(t) + if len(p.Entries) != 2 || p.Entries[0].ID != 5 || *p.NextBeforeID != 4 { + t.Fatal(res.body) + } + res = h.api("GET", "/audit", aliceToken, "") + p = res.auditPage(t) + var ids []int64 + for _, e := range p.Entries { + ids = append(ids, e.ID) + } + if fmt.Sprint(ids) != "[4 3 1]" { + t.Fatalf("user sees %v", ids) + } + h.store.failOn["UserZones"] = errDatabase + expectError(t, h.api("GET", "/audit", aliceToken, ""), 503, `{"error":"database unavailable"}`) + delete(h.store.failOn, "UserZones") + h.store.failOn["ListAudit"] = errors.New("x") + expectError(t, h.api("GET", "/audit", adminToken, ""), 500, `{"error":"internal error"}`) +} + +func TestAuditFilterParsing(t *testing.T) { + h, adminToken, _ := auditHarness(t) + res := h.api("GET", "/audit?operation=record_update", adminToken, "") + if p := res.auditPage(t); len(p.Entries) != 1 || p.Entries[0].Operation != "record_update" { + t.Fatal(res.body) + } + good := map[string]auditFilter{ + "": {Limit: 50}, + "zone=Example.ORG": {Zone: testZone, Limit: 50}, + "actor=alice": {Actor: "alice", Limit: 50}, + "operation=login": {Operation: "login", Limit: 50}, + "kind=read&outcome=error": {Kind: "read", Outcome: "error", Limit: 50}, + "kind=change&outcome=success": {Kind: "change", Outcome: "success", Limit: 50}, + "before_id=9007199254740993&limit=200": {BeforeID: 9007199254740993, Limit: 200}, + "limit=1": {Limit: 1}, + } + for q, want := range good { + values, _ := url.ParseQuery(q) + got, err := parseAuditFilter(values) + if err != nil || got != want { + t.Errorf("%q: %+v %v", q, got, err) + } + } + bad := map[string]string{ + "zone=bad!": "zone", + "actor=" + strings.Repeat("a", 65): "actor", + "operation=drop": "operation", + "kind=all": "kind", + "outcome=ok": "outcome", + "before_id=0": "before_id", + "before_id=-1": "before_id", + "before_id=1e3": "before_id", + "before_id=99999999999999999999": "before_id", + "limit=0": "limit", + "limit=201": "limit", + "limit=+5": "limit", + "limit=5x": "limit", + } + for q, param := range bad { + res := h.api("GET", "/audit?"+q, adminToken, "") + expectError(t, res, 400, `{"error":"invalid parameter `+param+`"}`) + expectNoChange(t, res, opAuditRead, 400) + } +} + +func TestAuditRawJSONFallback(t *testing.T) { + if string(rawJSON(nil)) != "null" || string(rawJSON([]byte("{bad"))) != "null" || string(rawJSON([]byte(`[1]`))) != "[1]" { + t.Fatal("rawJSON") + } + if nullInt(sql.NullInt64{}) != nil || *nullInt(sql.NullInt64{Int64: 4, Valid: true}) != 4 || nullString(sql.NullString{}) != nil { + t.Fatal("null helpers") + } +} + +type matrixPersona struct { + name string + token string +} + +type matrixRoute struct { + method, path, body string + 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}, + } + 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) + 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) + } + 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", ""}, + } + 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 +} + +func expectedMatrixStatus(persona string, r matrixRoute) (int, string) { + switch persona { + case "deleted user", "no session": + return 401, `{"error":"authentication required"}` + case "admin", "promoted user": + return r.allowed, "" + } + switch r.access { + case accessAdmin: + return 403, `{"error":"admin role required"}` + case accessZone: + if persona == "delegated user" { + return r.allowed, "" + } + return 404, `{"error":"zone not found"}` + } + return r.allowed, "" +} + +func TestAPIAuthorizationMatrix(t *testing.T) { + 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) + status, body := expectedMatrixStatus(p.name, r) + if res.status != status || (body != "" && res.body != body) { + t.Errorf("%s %s as %s: %d %s, want %d", r.method, r.path, p.name, res.status, res.body, status) + continue + } + if status == 401 { + if len(res.audit) != 0 { + t.Errorf("%s %s as %s: audit row without session", r.method, r.path, p.name) + } + continue + } + e := expectOneAudit(t, res, r.op, status) + if e.Actor == "" || !e.UserID.Valid || e.Origin != "192.0.2.10" { + 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 { + t.Errorf("%s as %s: zone %v", r.op, p.name, e.Zone) + } + } + } +} + +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) + } + } +} + +func TestNoSecretsInAuditOrLogs(t *testing.T) { + h := newWebHarness(t) + admin := h.user("admin", roleAdmin) + h.user("bob", roleUser) + h.store.addZone(testZone) + token := h.login(admin) + secrets := []string{"admin-new-password", "bob-new-password", "created-user-pw", testPassword, "wrong-password-xyz", token, "$fake$"} + h.do(webRequest{method: "POST", path: "/login", body: "username=admin&password=wrong-password-xyz", ctype: "application/x-www-form-urlencoded"}) + login := h.do(webRequest{method: "POST", path: "/login", body: "username=admin&password=" + testPassword, ctype: "application/x-www-form-urlencoded"}) + for _, c := range login.header.Values("Set-Cookie") { + v := strings.TrimPrefix(strings.Split(c, ";")[0], sessionCookieName+"=") + secrets = append(secrets, v) + } + h.api("POST", "/users", token, `{"username":"carl","role":"user","password":"created-user-pw"}`) + h.api("PUT", "/users/bob/password", token, `{"password":"bob-new-password"}`) + h.api("PUT", "/account/password", token, `{"current":"`+testPassword+`","password":"admin-new-password"}`) + h.api("POST", "/users", token, `{"username":"Bad","role":"user","password":"another-secret-1"}`) + secrets = append(secrets, "another-secret-1") + h.do(webRequest{method: "POST", path: "/logout", token: token}) + rows := h.store.auditRows() + if len(rows) < 7 { + t.Fatal(len(rows)) + } + logs := h.logs.String() + for _, row := range rows { + e := row.entry + text := strings.Join([]string{e.Actor, e.Origin, e.Operation, e.Error.String, e.Zone.String, string(e.Before), string(e.After)}, "|") + for _, s := range secrets { + if s != "" && strings.Contains(text, s) { + t.Fatalf("secret %q in audit row %s", s, text) + } + } + if strings.Contains(string(e.Before)+string(e.After), "password") { + t.Fatalf("password field in audit row %s", text) + } + } + for _, s := range secrets { + if s != "" && strings.Contains(logs, s) { + t.Fatalf("secret %q in logs", s) + } + } + if strings.Contains(logs, "Cookie") || strings.Contains(logs, sessionCookieName) { + t.Fatal("cookie in logs") + } +} + +func TestHandlersRequireStoredUserChanges(t *testing.T) { + h, token := usersHarness(t) + h.store.failOn["UserByUsernameForUpdate"] = errDatabase + for _, r := range []struct{ method, path, body string }{ + {"PUT", "/users/bob/role", `{"role":"admin"}`}, + {"PUT", "/users/bob/password", `{"password":"long-enough-pw"}`}, + {"DELETE", "/users/bob", `{"confirm":"bob"}`}, + {"PUT", "/zones/example.org./users/bob", ""}, + {"DELETE", "/zones/example.org./users/bob", ""}, + } { + expectError(t, h.api(r.method, r.path, token, r.body), http.StatusServiceUnavailable, `{"error":"database unavailable"}`) + } + delete(h.store.failOn, "UserByUsernameForUpdate") + h.store.failOn["ZoneExists"] = errors.New("x") + expectError(t, h.api("PUT", "/zones/example.org./users/bob", token, ""), 500, `{"error":"internal error"}`) + expectError(t, h.api("GET", "/zones/example.org./users", token, ""), 500, `{"error":"internal error"}`) + delete(h.store.failOn, "ZoneExists") + h.store.failOn["RevokeDelegation"] = errors.New("x") + expectError(t, h.api("DELETE", "/zones/example.org./users/bob", token, ""), 500, `{"error":"internal error"}`) + delete(h.store.failOn, "RevokeDelegation") + h.store.failOn["CreateUser"] = errors.New("x") + expectError(t, h.api("POST", "/users", token, `{"username":"zed","role":"user","password":"long-enough-pw"}`), 500, `{"error":"internal error"}`) + h.store.failOn["ListUsers"] = errors.New("x") + expectError(t, h.api("GET", "/users", token, ""), 500, `{"error":"internal error"}`) + h.store.failOn["UserByIDForUpdate"] = errors.New("x") + h.store.failOn["InTx"] = errDatabase + expectError(t, h.api("PUT", "/users/bob/role", token, `{"role":"admin"}`), 503, `{"error":"database unavailable"}`) +} + const zoneAPITestName = "example.org." const zoneAPITestSOA = `{"ns":"ns.example.net","mbox":"hostmaster@example.org","ttl":3600,"refresh":3600,"retry":600,"expire":604800,"minttl":300}` diff --git a/handlers_pages.go b/handlers_pages.go index d17444b..df5cf6e 100644 --- a/handlers_pages.go +++ b/handlers_pages.go @@ -5,16 +5,23 @@ package main import ( "bytes" + "context" "crypto/sha256" "embed" "encoding/hex" + "errors" "fmt" "html/template" "io/fs" + "maps" "net/http" + "net/url" "path" + "slices" "strconv" "strings" + + "github.com/gorilla/mux" ) //go:embed templates/html @@ -207,3 +214,315 @@ func (p *pageRenderer) staticHandler() http.Handler { } }) } + +const ( + loginFormLimit = 64 << 10 + msgInvalidLogin = "invalid username or password" + msgTooManyLogins = "too many failed login attempts, try again later" + msgLoginUnavailable = "login is temporarily unavailable, try again later" + msgInvalidLoginForm = "the login form is invalid" + msgPageUnavailable = "service unavailable" + msgPageInternalError = "internal server error" +) + +func validNextPath(next string) bool { + if !strings.HasPrefix(next, "/") || strings.HasPrefix(next, "//") || strings.ContainsAny(next, "\\") { + return false + } + for _, r := range next { + if r < 0x20 || r == 0x7f { + return false + } + } + u, err := url.Parse(next) + return err == nil && u.Scheme == "" && u.Host == "" && u.User == nil +} + +func safeNext(next string) string { + if validNextPath(next) { + return next + } + return "/" +} + +func loginLocation(r *http.Request) string { + return "/login?next=" + url.QueryEscape(r.URL.RequestURI()) +} + +func (s *WebServer) basePageData() pageData { + return pageData{AppName: s.cfg.AppName} +} + +func sessionPageData(base pageData, p principal) pageData { + base.Username, base.Role = p.User.Username, p.User.Role + return base +} + +func (s *WebServer) renderPage(w http.ResponseWriter, status int, page string, data pageData) { + if s.pages == nil { + http.Error(w, msgPageInternalError, http.StatusInternalServerError) + return + } + s.pages.render(w, status, page, data) +} + +func (s *WebServer) pageFailure(w http.ResponseWriter, r *http.Request, err error) { + s.log.ErrorContext(r.Context(), "page request failed", "path", r.URL.Path, "error", err) + if isDatabaseUnavailable(err) { + http.Error(w, msgPageUnavailable, http.StatusServiceUnavailable) + return + } + http.Error(w, msgPageInternalError, http.StatusInternalServerError) +} + +func (s *WebServer) optionalPageData(r *http.Request) pageData { + data := s.basePageData() + if p, err := s.authenticate(r); err == nil { + data = sessionPageData(data, p) + } + return data +} + +func (s *WebServer) handleNotFoundPage(w http.ResponseWriter, r *http.Request) { + s.renderPage(w, http.StatusNotFound, "not_found", s.optionalPageData(r)) +} + +func (s *WebServer) handleMethodNotAllowed(allow string) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Allow", allow) + http.Error(w, msgMethodNotAllowed, http.StatusMethodNotAllowed) + } +} + +func (s *WebServer) servePage(route pageRoute) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + ctx := r.Context() + p, err := s.authenticate(r) + if errors.Is(err, errNoSession) { + http.Redirect(w, r, loginLocation(r), http.StatusSeeOther) + return + } + if err != nil { + s.pageFailure(w, r, err) + return + } + data := sessionPageData(s.basePageData(), p) + if authorize(route.Access, &p, true) == accessForbidden { + s.log.WarnContext(ctx, "admin page refused", "path", r.URL.Path, "user", p.User.Username) + s.renderPage(w, http.StatusForbidden, "forbidden", data) + return + } + vars := mux.Vars(r) + if username, ok := vars["username"]; ok { + if !validUsernameSyntax(username) { + s.renderPage(w, http.StatusNotFound, "not_found", data) + return + } + data.TargetUser = username + } + if routeHasZone(route.Path) { + zone, err := normalizeZone(vars["zone"]) + if err != nil { + s.renderPage(w, http.StatusNotFound, "not_found", data) + return + } + delegated := false + if needsDelegation(route.Access, p) { + if delegated, err = s.store.HasDelegation(ctx, zone, p.User.ID); err != nil { + s.pageFailure(w, r, err) + return + } + } + if authorize(route.Access, &p, delegated) == accessNotFound { + s.log.WarnContext(ctx, "zone not delegated", "path", r.URL.Path, "zone", zone, "user", p.User.Username) + s.renderPage(w, http.StatusNotFound, "not_found", data) + return + } + data.Zone = zone + } + s.renderPage(w, http.StatusOK, route.Page, data) + } +} + +func (s *WebServer) renderLogin(w http.ResponseWriter, r *http.Request, status int, next, message string) { + data := s.basePageData() + data.Next = safeNext(next) + data.Error = message + if s.store != nil { + hasAdmin, err := s.store.HasActiveAdmin(r.Context()) + if err != nil { + s.log.ErrorContext(r.Context(), "active admin lookup failed", "error", err) + } + data.NoActiveAdmin = err == nil && !hasAdmin + } + s.renderPage(w, status, "login", data) +} + +func (s *WebServer) handleLoginPage(w http.ResponseWriter, r *http.Request) { + s.renderLogin(w, r, http.StatusOK, r.URL.Query().Get("next"), "") +} + +func (s *WebServer) loginAttemptAudit(ctx context.Context, e auditEntry, status int, message string) error { + finishAuditEntry(&e, status, message) + if err := s.insertAudit(ctx, e); err != nil { + s.log.ErrorContext(ctx, "audit insert failed", "operation", e.Operation, "status", status, "error", err) + return err + } + return nil +} + +func (s *WebServer) handleLogin(w http.ResponseWriter, r *http.Request) { + ctx := r.Context() + r.Body = http.MaxBytesReader(w, r.Body, loginFormLimit) + if err := r.ParseForm(); err != nil { + s.log.DebugContext(ctx, "invalid login form", "error", err) + s.renderLogin(w, r, http.StatusBadRequest, "", msgInvalidLoginForm) + return + } + username, password, next := r.PostForm.Get("username"), r.PostForm.Get("password"), safeNext(r.PostForm.Get("next")) + origin := clientOrigin(r, s.cfg.TrustedProxies) + actor := loginActor(username) + now := s.now().UTC() + if s.store == nil { + s.pageFailure(w, r, errDatabase) + return + } + var user *userRow + if validUsernameSyntax(username) { + u, err := s.store.UserByUsername(ctx, username) + switch { + case err == nil: + user = &u + case !errors.Is(err, errRowNotFound): + s.log.ErrorContext(ctx, "login user lookup failed", "error", err) + status, msg := failureStatus(err) + _ = s.loginAttemptAudit(ctx, loginAuditEntry(now, opLogin, username, nil, origin), status, msg) + s.renderLogin(w, r, status, next, msgLoginUnavailable) + return + } + } + entry := loginAuditEntry(now, opLogin, username, user, origin) + if !s.limiter.allow(actor, origin) { + s.log.WarnContext(ctx, "login rate limited", "actor", actor, "origin", origin) + if err := s.loginAttemptAudit(ctx, entry, http.StatusTooManyRequests, msgTooManyLogins); err != nil { + s.renderLogin(w, r, http.StatusInternalServerError, next, msgLoginUnavailable) + return + } + s.renderLogin(w, r, http.StatusTooManyRequests, next, msgTooManyLogins) + return + } + if !verifyLogin(s.verifyPassword, user, password) { + s.limiter.fail(actor, origin) + s.log.WarnContext(ctx, "login failed", "actor", actor, "origin", origin) + if err := s.loginAttemptAudit(ctx, entry, http.StatusUnauthorized, msgInvalidLogin); err != nil { + s.renderLogin(w, r, http.StatusInternalServerError, next, msgLoginUnavailable) + return + } + s.renderLogin(w, r, http.StatusUnauthorized, next, msgInvalidLogin) + return + } + token, hash, err := newSessionToken(s.random) + if err == nil { + err = s.store.InTx(ctx, func(tx webTx) error { + if old, ok := requestSessionToken(r); ok { + if _, err := tx.DeleteSession(ctx, sessionTokenHash(old)); err != nil { + return err + } + } + if err := tx.CreateSession(ctx, newSessionRow(hash, user.ID, now, s.cfg.SessionMaxAge, origin, r.UserAgent())); err != nil { + return err + } + if err := tx.TouchLastLogin(ctx, user.ID, now); err != nil { + return err + } + e := entry + finishAuditEntry(&e, http.StatusSeeOther, "") + _, err := tx.InsertAudit(ctx, e) + return err + }) + } + if err != nil { + s.log.ErrorContext(ctx, "login failed with an internal error", "actor", actor, "error", err) + status, msg := failureStatus(err) + _ = s.loginAttemptAudit(ctx, entry, status, msg) + s.renderLogin(w, r, status, next, msgLoginUnavailable) + return + } + s.limiter.succeed(actor) + s.log.InfoContext(ctx, "change committed", "operation", opLogin, "actor", user.Username) + setRequestUser(r, principal{User: *user}) + http.SetCookie(w, sessionCookie(token, s.cfg.CookieSecure)) + http.Redirect(w, r, next, http.StatusSeeOther) +} + +func (s *WebServer) handleLogout(w http.ResponseWriter, r *http.Request) { + ctx := r.Context() + p, err := s.authenticate(r) + if errors.Is(err, errNoSession) { + http.SetCookie(w, expiredSessionCookie(s.cfg.CookieSecure)) + http.Redirect(w, r, "/login", http.StatusSeeOther) + return + } + if err != nil { + s.pageFailure(w, r, err) + return + } + entry := apiAuditEntry(s.now().UTC(), p, clientOrigin(r, s.cfg.TrustedProxies), opLogout, "") + err = s.store.InTx(ctx, func(tx webTx) error { + if _, err := tx.DeleteSession(ctx, p.TokenHash); err != nil { + return err + } + e := entry + finishAuditEntry(&e, http.StatusSeeOther, "") + _, err := tx.InsertAudit(ctx, e) + return err + }) + if err != nil { + status, msg := failureStatus(err) + _ = s.loginAttemptAudit(ctx, entry, status, msg) + s.pageFailure(w, r, err) + return + } + s.log.InfoContext(ctx, "change committed", "operation", opLogout, "actor", p.User.Username) + http.SetCookie(w, expiredSessionCookie(s.cfg.CookieSecure)) + http.Redirect(w, r, "/login", http.StatusSeeOther) +} + +func (s *WebServer) registerPageRoutes(r *mux.Router) { + special := map[string]http.HandlerFunc{ + "GET /login": s.handleLoginPage, + "POST /login": s.handleLogin, + "POST /logout": s.handleLogout, + } + if s.pages != nil { + r.PathPrefix("/static/").Handler(s.pages.staticHandler()) + } + byPath := map[string]map[string]http.HandlerFunc{} + var paths []string + for _, route := range pageRoutes { + h := special[route.Method+" "+route.Path] + if h == nil && route.Page != "" { + h = s.servePage(route) + } + if h == nil { + continue + } + if byPath[route.Path] == nil { + byPath[route.Path] = map[string]http.HandlerFunc{} + paths = append(paths, route.Path) + } + byPath[route.Path][route.Method] = h + } + for _, path := range paths { + methods := byPath[path] + notAllowed := s.handleMethodNotAllowed(strings.Join(slices.Sorted(maps.Keys(methods)), ", ")) + r.HandleFunc(path, func(w http.ResponseWriter, req *http.Request) { + if h, ok := methods[req.Method]; ok { + h(w, req) + return + } + notAllowed(w, req) + }) + } + r.NotFoundHandler = http.HandlerFunc(s.handleNotFoundPage) +} diff --git a/handlers_session_test.go b/handlers_session_test.go new file mode 100644 index 0000000..1dd47b4 --- /dev/null +++ b/handlers_session_test.go @@ -0,0 +1,446 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright (C) 2026 Bryan Joshua Pedini + +package main + +import ( + "bytes" + "database/sql" + "errors" + "net/http" + "net/url" + "strings" + "testing" + "time" +) + +func loginForm(username, password, next string) string { + v := url.Values{"username": {username}, "password": {password}} + if next != "" { + v.Set("next", next) + } + return v.Encode() +} + +func (h *webHarness) postLogin(form string, token string) webResult { + h.t.Helper() + return h.do(webRequest{method: "POST", path: "/login", body: form, ctype: "application/x-www-form-urlencoded", token: token, header: map[string]string{"User-Agent": "Browser/1.0"}}) +} + +func responseCookie(t *testing.T, res webResult) *http.Cookie { + t.Helper() + cookies := (&http.Response{Header: res.header}).Cookies() + if len(cookies) != 1 { + t.Fatalf("cookies %v", cookies) + } + return cookies[0] +} + +func TestLoginSuccess(t *testing.T) { + h := newWebHarness(t) + alice := h.user("alice", roleUser) + old := h.login(alice) + h.clock.advance(time.Minute) + res := h.postLogin(loginForm("alice", testPassword, "/zones/example.org.?q=1"), old) + if res.status != 303 || res.header.Get("Location") != "/zones/example.org.?q=1" { + t.Fatalf("%d %v", res.status, res.header) + } + c := responseCookie(t, res) + if c.Name != sessionCookieName || !c.HttpOnly || !c.Secure || c.SameSite != http.SameSiteStrictMode || c.Path != "/" || !validSessionToken(c.Value) || c.Value == old { + t.Fatalf("%+v", c) + } + sw, err := h.store.SessionByTokenHash(t.Context(), sessionTokenHash(c.Value)) + if err != nil || sw.Session.UserID != alice.ID || sw.Session.Origin != "192.0.2.10" || sw.Session.UserAgent != "Browser/1.0" || + !sw.Session.CreatedAt.Equal(h.clock.Now()) || !sw.Session.ExpiresAt.Equal(h.clock.Now().Add(12*time.Hour)) { + t.Fatalf("%+v %v", sw, err) + } + if _, err := h.store.SessionByTokenHash(t.Context(), sessionTokenHash(old)); !errors.Is(err, errRowNotFound) { + t.Fatal("previous session of the browser kept") + } + if u := h.stored("alice"); !u.LastLoginAt.Valid || !u.LastLoginAt.Time.Equal(h.clock.Now()) { + t.Fatalf("%+v", u) + } + e := expectOneAudit(t, res, opLogin, 303) + if !res.audit[0].inTx || e.UserID.Int64 != alice.ID || e.Actor != "alice" || e.Origin != "192.0.2.10" || e.Zone.Valid || e.Before != nil || e.After != nil { + t.Fatalf("%+v", res.audit[0]) + } + if !strings.Contains(h.logs.String(), `msg="change committed" operation=login actor=alice`) { + t.Fatal("login not logged") + } + second := h.postLogin(loginForm("alice", testPassword, ""), "") + if second.header.Get("Location") != "/" || responseCookie(t, second).Value == c.Value { + t.Fatal("token reused or default next wrong") + } + if h.api("GET", "/account", c.Value, "").status != 200 { + t.Fatal("new session unusable") + } +} + +func TestLoginFailures(t *testing.T) { + h := newWebHarness(t) + alice := h.user("alice", roleUser) + gone := h.user("gone", roleUser) + gone.DeletedAt = sql.NullTime{Time: webNow, Valid: true} + h.store.setUser(gone) + var verified []string + h.s.verifyPassword = func(p, encoded string) bool { + verified = append(verified, encoded) + return fakeVerify(p, encoded) + } + cases := []struct { + username, password string + userID int64 + actor, hash string + }{ + {"alice", "wrong-password", alice.ID, "alice", fakeHash(testPassword)}, + {"nobody", testPassword, 0, "nobody", dummyPasswordHash}, + {"gone", testPassword, gone.ID, "gone", dummyPasswordHash}, + {"Bad\x00User\n", testPassword, 0, "Bad User ", dummyPasswordHash}, + {"", "", 0, "", dummyPasswordHash}, + } + for _, c := range cases { + verified = nil + res := h.postLogin(loginForm(c.username, c.password, "/audit"), "") + if res.status != 401 || !strings.Contains(res.body, "invalid username or password") || len(res.header.Values("Set-Cookie")) != 0 { + t.Fatalf("%q: %d", c.username, res.status) + } + if !strings.Contains(res.body, `name="next" value="/audit"`) { + t.Fatal("next lost on the login page") + } + e := expectOneAudit(t, res, opLogin, 401) + if e.Error.String != "invalid username or password" || e.Actor != c.actor || e.UserID.Valid != (c.userID != 0) || e.UserID.Int64 != c.userID { + t.Fatalf("%q: %+v", c.username, e) + } + if len(verified) != 1 || verified[0] != c.hash { + t.Fatalf("%q: verified against %v", c.username, verified) + } + } + if strings.Count(h.logs.String(), `level=WARN msg="login failed"`) != len(cases) { + t.Fatal("failed logins not logged at WARN") + } + if strings.Contains(h.logs.String(), "wrong-password") { + t.Fatal("password logged") + } +} + +func TestLoginRateLimit(t *testing.T) { + h := newWebHarness(t) + h.user("alice", roleUser) + h.user("bob", roleUser) + for i := range 4 { + res := h.do(webRequest{method: "POST", path: "/login", body: loginForm("alice", "bad", ""), ctype: "application/x-www-form-urlencoded", remote: "198.51.100." + string(rune('1'+i)) + ":1"}) + if res.status != 401 { + t.Fatal(res.status) + } + } + if res := h.postLogin(loginForm("alice", testPassword, ""), ""); res.status != 303 { + t.Fatal("login refused before the limit", res.status) + } + for range 5 { + h.do(webRequest{method: "POST", path: "/login", body: loginForm("alice", "bad", ""), ctype: "application/x-www-form-urlencoded", remote: "203.0.113.50:1"}) + } + res := h.do(webRequest{method: "POST", path: "/login", body: loginForm("alice", testPassword, ""), ctype: "application/x-www-form-urlencoded", remote: "203.0.113.51:1"}) + if res.status != 429 || !strings.Contains(res.body, "too many failed login attempts, try again later") || len(res.header.Values("Set-Cookie")) != 0 { + t.Fatalf("%d", res.status) + } + e := expectOneAudit(t, res, opLogin, 429) + if e.UserID.Int64 != h.users["alice"].ID || e.Error.String != "too many failed login attempts, try again later" { + t.Fatalf("%+v", e) + } + if res := h.do(webRequest{method: "POST", path: "/login", body: loginForm("bob", testPassword, ""), ctype: "application/x-www-form-urlencoded", remote: "203.0.113.50:1"}); res.status != 429 { + t.Fatal("origin not limited", res.status) + } + if !strings.Contains(h.logs.String(), `level=WARN msg="login rate limited"`) { + t.Fatal("rate limit not logged") + } + h.clock.advance(loginBlockDuration) + if res := h.postLogin(loginForm("alice", testPassword, ""), ""); res.status != 303 { + t.Fatal("block not lifted", res.status) + } + h.store.failOn["InsertAudit"] = errors.New("x") + for range 5 { + h.do(webRequest{method: "POST", path: "/login", body: loginForm("bob", "bad", ""), ctype: "application/x-www-form-urlencoded", remote: "203.0.113.60:1"}) + } + if res := h.do(webRequest{method: "POST", path: "/login", body: loginForm("bob", "bad", ""), ctype: "application/x-www-form-urlencoded", remote: "203.0.113.61:1"}); res.status != 500 { + t.Fatal("rate limited login without audit row", res.status) + } +} + +func TestLoginInternalFailures(t *testing.T) { + h := newWebHarness(t) + h.user("alice", roleUser) + h.store.failOn["UserByUsername"] = errDatabase + res := h.postLogin(loginForm("alice", testPassword, ""), "") + if res.status != 503 || !strings.Contains(res.body, "login is temporarily unavailable") { + t.Fatal(res.status) + } + if e := expectOneAudit(t, res, opLogin, 503); e.UserID.Valid || e.Error.String != "database unavailable" { + t.Fatalf("%+v", e) + } + delete(h.store.failOn, "UserByUsername") + h.store.failOn["CreateSession"] = errors.New("duplicate token") + res = h.postLogin(loginForm("alice", testPassword, ""), "") + if res.status != 500 || len(res.header.Values("Set-Cookie")) != 0 { + t.Fatal(res.status) + } + if e := expectOneAudit(t, res, opLogin, 500); res.audit[0].inTx || e.Error.String != "internal error" { + t.Fatalf("%+v", res.audit[0]) + } + if h.stored("alice").LastLoginAt.Valid { + t.Fatal("failed login touched last_login_at") + } + delete(h.store.failOn, "CreateSession") + h.s.random = bytes.NewReader(nil) + if res := h.postLogin(loginForm("alice", testPassword, ""), ""); res.status != 500 { + t.Fatal("token failure", res.status) + } + h.s.random = strings.NewReader(strings.Repeat("r", 64)) + h.store.failOn["InsertAudit"] = errors.New("x") + if res := h.postLogin(loginForm("alice", "wrong", ""), ""); res.status != 500 { + t.Fatal("failed login without audit row", res.status) + } + delete(h.store.failOn, "InsertAudit") + res = h.do(webRequest{method: "POST", path: "/login", body: "username=%zz", ctype: "application/x-www-form-urlencoded"}) + if res.status != 400 || !strings.Contains(res.body, "the login form is invalid") || len(res.audit) != 0 { + t.Fatal(res.status) + } + res = h.do(webRequest{method: "POST", path: "/login", body: "username=" + strings.Repeat("a", 70000), ctype: "application/x-www-form-urlencoded"}) + if res.status != 400 { + t.Fatal("oversized form", res.status) + } + h.s.store = nil + if res := h.postLogin(loginForm("alice", testPassword, ""), ""); res.status != 503 { + t.Fatal("no store", res.status) + } +} + +func TestLoginPage(t *testing.T) { + h := newWebHarness(t) + res := h.do(webRequest{method: "GET", path: "/login?next=/users"}) + if res.status != 200 || !strings.Contains(res.body, "No administrator exists yet") || !strings.Contains(res.body, "docker exec -i <container> /app user add <username> admin") || !strings.Contains(res.body, `value="/users"`) { + t.Fatalf("%d %s", res.status, res.body) + } + if len(res.audit) != 0 { + t.Fatal("page audited") + } + h.user("admin", roleAdmin) + res = h.do(webRequest{method: "GET", path: "/login?next=//evil.example/x"}) + if strings.Contains(res.body, "No administrator exists yet") || !strings.Contains(res.body, `name="next" value="/"`) { + t.Fatal(res.body) + } + admin := h.users["admin"] + admin.DeletedAt = sql.NullTime{Time: webNow, Valid: true} + h.store.setUser(admin) + h.user("demoted", roleUser) + if res := h.do(webRequest{method: "GET", path: "/login"}); !strings.Contains(res.body, "No administrator exists yet") { + t.Fatal("deleted admin counted as active") + } + h.store.failOn["HasActiveAdmin"] = errDatabase + res = h.do(webRequest{method: "GET", path: "/login"}) + if res.status != 200 || strings.Contains(res.body, "No administrator exists yet") || !strings.Contains(h.logs.String(), "active admin lookup failed") { + t.Fatal(res.status) + } +} + +func TestValidNextPath(t *testing.T) { + good := []string{"/", "/zones/example.org.", "/audit?zone=a.b.&kind=read", "/users/bob#x"} + bad := []string{"", "zones", "//evil.example", "/\\evil.example", "http://evil.example/", "/a\nb", "/a\x7fb", "\\\\evil", "/%zz"} + for _, n := range good { + if !validNextPath(n) || safeNext(n) != n { + t.Errorf("%q refused", n) + } + } + for _, n := range bad { + if validNextPath(n) || safeNext(n) != "/" { + t.Errorf("%q accepted", n) + } + } +} + +func TestLogout(t *testing.T) { + h := newWebHarness(t) + alice := h.user("alice", roleUser) + token := h.login(alice) + other := h.login(alice) + res := h.do(webRequest{method: "POST", path: "/logout", token: token}) + if res.status != 303 || res.header.Get("Location") != "/login" { + t.Fatal(res.status) + } + c := responseCookie(t, res) + if c.Value != "" || c.MaxAge != -1 { + t.Fatalf("%+v", c) + } + e := expectOneAudit(t, res, opLogout, 303) + if !res.audit[0].inTx || e.UserID.Int64 != alice.ID || e.Actor != "alice" { + t.Fatalf("%+v", e) + } + if h.api("GET", "/account", token, "").status != 401 || h.api("GET", "/account", other, "").status != 200 { + t.Fatal("logout must end only its own session") + } + res = h.do(webRequest{method: "POST", path: "/logout", token: token}) + if res.status != 303 || res.header.Get("Location") != "/login" || len(res.audit) != 0 { + t.Fatal("logout without session", res.status) + } + h.store.failOn["DeleteSession"] = errors.New("x") + res = h.do(webRequest{method: "POST", path: "/logout", token: other}) + if res.status != 500 { + t.Fatal(res.status) + } + if e := expectOneAudit(t, res, opLogout, 500); res.audit[0].inTx || e.Error.String != "internal error" { + t.Fatalf("%+v", e) + } + h.store.failOn = map[string]error{"SessionByTokenHash": errDatabase} + if res := h.do(webRequest{method: "POST", path: "/logout", token: other}); res.status != 503 { + t.Fatal(res.status) + } + if res := h.do(webRequest{method: "GET", path: "/logout", token: other}); res.status != 405 || res.header.Get("Allow") != "POST" { + t.Fatal(res.status) + } +} + +type pageCase struct { + path string + access string + page string +} + +var pageCases = []pageCase{ + {"/", accessSession, "zones"}, + {"/zones/example.org.", accessZone, "zone"}, + {"/zones/Example.ORG/import", accessZone, "import"}, + {"/audit", accessSession, "audit"}, + {"/account", accessSession, "account"}, + {"/users", accessAdmin, "users"}, + {"/users/bob", accessAdmin, "user"}, +} + +func TestPageAuthorizationMatrix(t *testing.T) { + for _, c := range pageCases { + for i := range 7 { + h, personas := matrixHarness(t) + p := personas[i] + res := h.do(webRequest{method: "GET", path: c.path, token: p.token}) + want, page := 200, c.page + switch { + case p.name == "deleted user" || p.name == "no session": + want = 303 + case p.name == "admin" || p.name == "promoted user": + case c.access == accessAdmin: + want, page = 403, "forbidden" + case c.access == accessZone && p.name != "delegated user": + want, page = 404, "not_found" + } + if res.status != want || len(res.audit) != 0 { + t.Errorf("%s as %s: %d (audit %d), want %d", c.path, p.name, res.status, len(res.audit), want) + continue + } + if want == 303 { + if res.header.Get("Location") != "/login?next="+url.QueryEscape(c.path) { + t.Errorf("%s: %s", c.path, res.header.Get("Location")) + } + continue + } + if !strings.Contains(res.body, `data-page="`+page+`"`) || res.header.Get("Content-Type") != "text/html; charset=utf-8" { + t.Errorf("%s as %s: page %s missing", c.path, p.name, page) + } + if !strings.Contains(res.body, `data-username="`) || strings.Contains(res.body, `data-username=""`) { + t.Errorf("%s as %s: user missing in layout", c.path, p.name) + } + isAdmin := p.name == "admin" || p.name == "promoted user" + if strings.Contains(res.body, `href="/users"`) != isAdmin { + t.Errorf("%s as %s: users link visibility", c.path, p.name) + } + if page == "zone" && !strings.Contains(res.body, `data-zone="example.org."`) { + t.Errorf("zone missing: %s", res.body) + } + if page == "import" && !strings.Contains(res.body, `data-zone="example.org."`) { + t.Errorf("zone missing on import page") + } + if page == "user" && !strings.Contains(res.body, `data-target-user="bob"`) { + t.Errorf("target user missing") + } + } + } +} + +func TestPagesCarryNoData(t *testing.T) { + h, personas := matrixHarness(t) + h.store.calls = nil + for _, c := range pageCases { + res := h.do(webRequest{method: "GET", path: c.path, token: personas[1].token}) + if strings.Contains(res.body, "carol") || strings.Contains(res.body, "dave") { + t.Fatalf("%s carries user data", c.path) + } + } + for _, call := range h.store.calls { + if call != "SessionByTokenHash" && call != "HasDelegation" { + t.Fatalf("page read %s", call) + } + } +} + +func TestPageEdgeCases(t *testing.T) { + h, personas := matrixHarness(t) + admin := personas[0].token + res := h.do(webRequest{method: "GET", path: "/users/BAD", token: admin}) + if res.status != 404 || !strings.Contains(res.body, `data-page="not_found"`) || !strings.Contains(res.body, `data-username="admin"`) { + t.Fatal(res.status) + } + if res := h.do(webRequest{method: "GET", path: "/zones/bad!zone", token: admin}); res.status != 404 { + t.Fatal(res.status) + } + res = h.do(webRequest{method: "GET", path: "/no/such/page", token: admin}) + if res.status != 404 || !strings.Contains(res.body, `data-username="admin"`) { + t.Fatal(res.status) + } + res = h.do(webRequest{method: "GET", path: "/no/such/page"}) + if res.status != 404 || !strings.Contains(res.body, `data-username=""`) { + t.Fatal(res.status) + } + res = h.do(webRequest{method: "GET", path: "/users", token: personas[1].token}) + if res.status != 403 || !strings.Contains(res.body, `data-username="alice"`) || !strings.Contains(res.body, "Forbidden") || !strings.Contains(h.logs.String(), `level=WARN msg="admin page refused"`) { + t.Fatal(res.status) + } + if res := h.do(webRequest{method: "DELETE", path: "/", token: admin}); res.status != 405 || res.header.Get("Allow") != "GET" { + t.Fatal(res.status) + } + if res := h.do(webRequest{method: "PUT", path: "/login"}); res.status != 405 || res.header.Get("Allow") != "GET, POST" { + t.Fatal(res.status) + } + res = h.do(webRequest{method: "GET", path: "/audit?zone=x", header: map[string]string{}}) + if res.status != 303 || res.header.Get("Location") != "/login?next=%2Faudit%3Fzone%3Dx" { + t.Fatal(res.header.Get("Location")) + } + h.store.failOn["HasDelegation"] = errDatabase + if res := h.do(webRequest{method: "GET", path: "/zones/example.org.", token: personas[1].token}); res.status != 503 { + t.Fatal(res.status) + } + h.store.failOn = map[string]error{"SessionByTokenHash": errors.New("x")} + if res := h.do(webRequest{method: "GET", path: "/", token: admin}); res.status != 500 || res.body != "internal server error\n" { + t.Fatal(res.status) + } + h.store.failOn = map[string]error{} + h.s.pages = nil + if res := h.do(webRequest{method: "GET", path: "/", token: admin}); res.status != 500 { + t.Fatal(res.status) + } +} + +func TestStaticRoutes(t *testing.T) { + h := newWebHarness(t) + prefix := h.s.pages.staticPrefix() + if res := h.do(webRequest{method: "GET", path: prefix + "js/common.js"}); res.status != 200 || res.header.Get("Content-Type") != "text/javascript; charset=utf-8" { + t.Fatal(res.status) + } + for _, p := range []string{"/static/0000000000000000/css/app.css", prefix + "nope.css", prefix + "../templates/html/layout.html", "/static/"} { + if res := h.do(webRequest{method: "GET", path: p}); res.status != 404 && res.status != 301 { + t.Errorf("%s: %d", p, res.status) + } + } + if res := h.do(webRequest{method: "POST", path: prefix + "css/app.css"}); res.status != 405 { + t.Fatal(res.status) + } + if res := h.do(webRequest{method: "GET", path: "/version"}); res.status != 200 || len(res.audit) != 0 { + t.Fatal(res.status) + } +} diff --git a/integration_cli_test.go b/integration_cli_test.go index ed5465a..11924ae 100644 --- a/integration_cli_test.go +++ b/integration_cli_test.go @@ -176,15 +176,30 @@ func TestIntegrationCheckAndAuditCommands(t *testing.T) { t.Parallel() d := newITDatabase(t, itOptions{prefix: "dns_"}) c := d.cli(t, "", time.Now()) - if code := c.run("check"); code != 1 || c.stderr.String() != "coredns-web-ui: check: not implemented\n" { - t.Fatalf("%d %q", code, c.stderr.String()) + if code := c.run("check"); code != 0 || c.stdout.String() != "ZONE NAME TYPE ID SEVERITY PROBLEM\n" { + t.Fatalf("%d %q %q", code, c.stdout.String(), c.stderr.String()) } if d.count(t, "SELECT `version` FROM `dns_webui_schema`") != 1 { t.Fatal("check did not migrate") } - if code := c.run("audit", "5"); code != 1 || c.stderr.String() != "coredns-web-ui: audit: not implemented\n" { + d.rootExec(t, "INSERT INTO `dns_records` (`zone`, `name`, `ttl`, `content`, `record_type`) VALUES ('example.org.', 'www', NULL, '{\"ip\": \"192.0.2.1\"}', 'A')") + c = d.cli(t, "", time.Now()) + if code := c.run("check", "EXAMPLE.org"); code != 3 || !strings.Contains(c.stdout.String(), "ttl_null") || !strings.Contains(c.stdout.String(), "soa_missing") { + t.Fatalf("%d %q %q", code, c.stdout.String(), c.stderr.String()) + } + c = d.cli(t, "", time.Now()) + if code := c.run("check", "missing.example"); code != 1 || c.stderr.String() != "coredns-web-ui: the zone has no records\n" { t.Fatalf("%d %q", code, c.stderr.String()) } + c = d.cli(t, "a-long-password\n", time.Date(2026, 11, 18, 9, 0, 0, 0, time.UTC)) + if code := c.run("user", "add", "alice", "admin"); code != 0 { + t.Fatalf("%d %q", code, c.stderr.String()) + } + c = d.cli(t, "", time.Now()) + if code := c.run("audit", "5"); code != 0 || c.stdout.String() != "TIME ACTOR ORIGIN OPERATION STATUS ZONE RECORD TARGET_USER\n"+ + "2026-11-18T09:00:00Z cli local user_create - - - alice\n" { + t.Fatalf("%d %q %q", code, c.stdout.String(), c.stderr.String()) + } if code := c.run("audit", "x"); code != 2 { t.Fatal(code) } diff --git a/main.go b/main.go index 794ff50..a0531b4 100644 --- a/main.go +++ b/main.go @@ -47,6 +47,7 @@ type app struct { openDB func(cfg Config, log *slog.Logger) (*sql.DB, error) prepareDB func(ctx context.Context, cfg Config, log *slog.Logger) (*sql.DB, tableNames, error) newUserBackend func(db *sql.DB, t tableNames) cliUserBackend + newReadBackend func(db *sql.DB, t tableNames) cliReadBackend pingBackoff backoff healthClient *http.Client serverStarted func(*WebServer, net.Listener) @@ -63,11 +64,12 @@ func newApp(lookupEnv func(string) (string, bool), stdin *os.File, stdout, stder return term.ReadPassword(int(stdin.Fd())) }, now: time.Now, - hashPassword: stubHashPassword, + hashPassword: hashPassword, normalizeZone: normalizeZone, listen: net.Listen, openDB: openDatabase, newUserBackend: newSQLUserBackend, + newReadBackend: newSQLReadBackend, pingBackoff: defaultPingBackoff(), healthClient: newHealthClient(), } diff --git a/middleware.go b/middleware.go new file mode 100644 index 0000000..7e8f2a8 --- /dev/null +++ b/middleware.go @@ -0,0 +1,699 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright (C) 2026 Bryan Joshua Pedini + +package main + +import ( + "bytes" + "cmp" + "context" + "database/sql" + "database/sql/driver" + "encoding/json" + "errors" + "fmt" + "io" + "log/slog" + "maps" + "mime" + "net" + "net/http" + "net/netip" + "reflect" + "slices" + "strings" + "time" + + "github.com/go-sql-driver/mysql" + "github.com/gorilla/mux" +) + +const ( + contentSecurityPolicy = "default-src 'none'; script-src 'self'; style-src 'self'; img-src 'self' data:; connect-src 'self'; form-action 'self'; frame-ancestors 'none'; base-uri 'none'" + auditInsertTimeout = 5 * time.Second + msgAuthRequired = "authentication required" + msgAdminRequired = "admin role required" + msgZoneNotFound = "zone not found" + msgUserNotFound = "user not found" + msgInternalError = "internal error" + msgDatabaseDown = "database unavailable" + msgZoneBusy = "zone busy" + msgNotFound = "not found" + msgMethodNotAllowed = "method not allowed" + msgCrossOrigin = "cross-origin request refused" + msgNotImplemented = "not implemented" +) + +type principal struct { + User userRow + TokenHash []byte +} + +func (p principal) isAdmin() bool { return p.User.Role == "admin" } + +type apiContext struct { + Request *http.Request + Principal principal + Zone string + Vars map[string]string + Now time.Time + Entry *auditEntry + Server *WebServer + auditDone bool + bodyLimit int64 +} + +type apiResponse struct { + Status int + Body any + Raw []byte + ContentType string + Header http.Header +} + +type apiError struct { + Status int + Message string + Fields map[string]string + Extra map[string]any +} + +func (e *apiError) Error() string { return e.Message } + +type apiHandler func(ctx context.Context, c *apiContext) (apiResponse, error) + +func errZoneNotFound() *apiError { + return &apiError{Status: http.StatusNotFound, Message: msgZoneNotFound} +} + +func errUserNotFound() *apiError { + return &apiError{Status: http.StatusNotFound, Message: msgUserNotFound} +} + +func fieldError(field, message string) *apiError { + return &apiError{Status: http.StatusUnprocessableEntity, Message: "invalid " + field, Fields: map[string]string{field: message}} +} + +type auditInserter interface { + InsertAudit(ctx context.Context, e auditEntry) (int64, error) +} + +type webTx interface { + auditInserter + CreateSession(ctx context.Context, row sessionRow) error + DeleteSession(ctx context.Context, tokenHash []byte) (bool, error) + DeleteUserSessions(ctx context.Context, userID int64) (int64, error) + DeleteUserSessionsExcept(ctx context.Context, userID int64, keepTokenHash []byte) (int64, error) + TouchLastLogin(ctx context.Context, id int64, now time.Time) error + CreateUser(ctx context.Context, username, role, passwordHash string, now time.Time) (userRow, error) + UserByIDForUpdate(ctx context.Context, id int64) (userRow, error) + UserByUsernameForUpdate(ctx context.Context, username string) (userRow, error) + LockActiveAdmins(ctx context.Context) ([]userRow, error) + SetRole(ctx context.Context, id int64, role string, now time.Time) error + SetPassword(ctx context.Context, id int64, passwordHash string, now time.Time) error + MarkDeleted(ctx context.Context, id int64, now time.Time) error + ZoneExists(ctx context.Context, zone string) (bool, error) + GrantDelegation(ctx context.Context, zone string, userID, createdBy int64, now time.Time) (bool, error) + RevokeDelegation(ctx context.Context, zone string, userID int64) (bool, error) +} + +type webStore interface { + auditInserter + SessionByTokenHash(ctx context.Context, tokenHash []byte) (sessionWithUser, error) + TouchSession(ctx context.Context, tokenHash []byte, now time.Time) error + UserByUsername(ctx context.Context, username string) (userRow, error) + HasActiveAdmin(ctx context.Context) (bool, error) + HasDelegation(ctx context.Context, zone string, userID int64) (bool, error) + ListUsers(ctx context.Context, includeDeleted bool) ([]userSummary, error) + UserZones(ctx context.Context, userID int64) ([]userZone, error) + ZoneUsers(ctx context.Context, zone string) ([]userRow, error) + ZoneExists(ctx context.Context, zone string) (bool, error) + ListAudit(ctx context.Context, f auditFilter) ([]auditRow, error) + InTx(ctx context.Context, fn func(tx webTx) error) error +} + +type sqlWebTx struct { + userStore + sessionStore + delegationStore + auditStore + recordStore +} + +func newSQLWebTx(q dbtx, t tableNames) sqlWebTx { + return sqlWebTx{ + userStore: newUserStore(q, t), + sessionStore: newSessionStore(q, t), + delegationStore: newDelegationStore(q, t), + auditStore: newAuditStore(q, t), + recordStore: newRecordStore(q, t), + } +} + +type sqlWebStore struct { + sqlWebTx + db *sql.DB + tables tableNames +} + +func newSQLWebStore(db *sql.DB, t tableNames) *sqlWebStore { + return &sqlWebStore{sqlWebTx: newSQLWebTx(db, t), db: db, tables: t} +} + +func (s *sqlWebStore) InTx(ctx context.Context, fn func(tx webTx) error) error { + return runInTx(ctx, s.db, func(tx *sql.Tx) error { + return fn(newSQLWebTx(tx, s.tables)) + }) +} + +func (c *apiContext) writeChangeAudit(ctx context.Context, tx *sql.Tx, status int) error { + return c.writeChangeAuditWith(ctx, newAuditStore(tx, c.Server.tables), status) +} + +func (c *apiContext) writeChangeAuditWith(ctx context.Context, ins auditInserter, status int) error { + finishAuditEntry(c.Entry, status, "") + if _, err := ins.InsertAudit(ctx, *c.Entry); err != nil { + return err + } + c.auditDone = true + return nil +} + +func isJSONContentType(ct string) bool { + mt, _, err := mime.ParseMediaType(ct) + return err == nil && mt == "application/json" +} + +func jsonTypeMessage(e *json.UnmarshalTypeError) string { + if e.Type == nil { + return "has the wrong type" + } + switch e.Type.Kind() { + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, + reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: + if strings.HasPrefix(e.Value, "number") { + return "must be an integer in range" + } + return "must be a number" + case reflect.Float32, reflect.Float64: + return "must be a number" + case reflect.String: + return "must be a string" + case reflect.Bool: + return "must be a boolean" + case reflect.Slice, reflect.Array: + return "must be an array" + case reflect.Map, reflect.Struct: + return "must be an object" + } + return "has the wrong type" +} + +func (c *apiContext) decodeJSON(dst any) error { + limit := c.bodyLimit + if limit <= 0 { + limit = defaultBodyLimit + } + body, err := io.ReadAll(io.LimitReader(c.Request.Body, limit+1)) + if err != nil { + return &apiError{Status: http.StatusBadRequest, Message: "cannot read the request body"} + } + trimmed := bytes.TrimLeft(body, " \t\r\n") + if len(trimmed) == 0 { + return &apiError{Status: http.StatusBadRequest, Message: "request body is required"} + } + if !isJSONContentType(c.Request.Header.Get("Content-Type")) { + return &apiError{Status: http.StatusUnsupportedMediaType, Message: "content type must be application/json"} + } + if int64(len(body)) > limit { + return &apiError{Status: http.StatusRequestEntityTooLarge, Message: "request body too large"} + } + if trimmed[0] != '{' { + return &apiError{Status: http.StatusBadRequest, Message: "request body must be a JSON object"} + } + dec := json.NewDecoder(bytes.NewReader(body)) + dec.DisallowUnknownFields() + if err := dec.Decode(dst); err != nil { + var te *json.UnmarshalTypeError + if errors.As(err, &te) && te.Field != "" { + return &apiError{Status: http.StatusUnprocessableEntity, Message: "invalid field type", Fields: map[string]string{te.Field: jsonTypeMessage(te)}} + } + if strings.HasPrefix(err.Error(), "json: unknown field") { + return &apiError{Status: http.StatusBadRequest, Message: "request body has an unknown field"} + } + return &apiError{Status: http.StatusBadRequest, Message: "malformed JSON"} + } + if _, err := dec.Token(); !errors.Is(err, io.EOF) { + return &apiError{Status: http.StatusBadRequest, Message: "request body has trailing data"} + } + return nil +} + +func precheckBody(r *http.Request, limit int64) error { + if r.ContentLength <= 0 { + return nil + } + if !isJSONContentType(r.Header.Get("Content-Type")) { + return &apiError{Status: http.StatusUnsupportedMediaType, Message: "content type must be application/json"} + } + if r.ContentLength > limit { + return &apiError{Status: http.StatusRequestEntityTooLarge, Message: "request body too large"} + } + return nil +} + +func parseForwardedAddr(s string) (netip.Addr, error) { + s = strings.TrimSpace(s) + if ap, err := netip.ParseAddrPort(s); err == nil { + return ap.Addr(), nil + } + return netip.ParseAddr(strings.TrimSuffix(strings.TrimPrefix(s, "["), "]")) +} + +func clientOrigin(r *http.Request, trusted []netip.Prefix) string { + host, _, err := net.SplitHostPort(r.RemoteAddr) + if err != nil { + host = r.RemoteAddr + } + peer, err := netip.ParseAddr(host) + if err != nil { + return printableText(host, auditMaxOriginRunes) + } + origin := peer.Unmap().WithZone("") + if !addrTrusted(origin, trusted) { + return origin.String() + } + var hops []string + for _, v := range r.Header.Values("X-Forwarded-For") { + hops = append(hops, strings.Split(v, ",")...) + } + for i := len(hops) - 1; i >= 0; i-- { + hop, err := parseForwardedAddr(hops[i]) + if err != nil { + break + } + origin = hop.Unmap().WithZone("") + if !addrTrusted(origin, trusted) { + break + } + } + return origin.String() +} + +func addrTrusted(addr netip.Addr, trusted []netip.Prefix) bool { + for _, p := range trusted { + if p.Contains(addr) { + return true + } + } + return false +} + +type requestInfoKey struct{} + +type requestInfo struct { + user string + role string +} + +func setRequestUser(r *http.Request, p principal) { + if info, ok := r.Context().Value(requestInfoKey{}).(*requestInfo); ok { + info.user, info.role = p.User.Username, p.User.Role + } +} + +type statusRecorder struct { + http.ResponseWriter + status int +} + +func (s *statusRecorder) WriteHeader(code int) { + s.status = code + s.ResponseWriter.WriteHeader(code) +} + +func (s *statusRecorder) Unwrap() http.ResponseWriter { + return s.ResponseWriter +} + +func quietPath(path string) bool { + return path == "/health" || strings.HasPrefix(path, "/static/") +} + +func requestLogMiddleware(s *WebServer, next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + start := time.Now() + info := &requestInfo{} + r = r.WithContext(context.WithValue(r.Context(), requestInfoKey{}, info)) + rec := &statusRecorder{ResponseWriter: w, status: http.StatusOK} + next.ServeHTTP(rec, r) + level := slog.LevelInfo + if quietPath(r.URL.Path) { + level = slog.LevelDebug + } + s.log.Log(r.Context(), level, "request", "method", r.Method, "path", r.URL.Path, "status", rec.status, + "duration", time.Since(start), "user", info.user, "role", info.role, "origin", clientOrigin(r, s.cfg.TrustedProxies)) + }) +} + +func securityHeadersMiddleware(s *WebServer, next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + h := w.Header() + h.Set("Content-Security-Policy", contentSecurityPolicy) + h.Set("X-Content-Type-Options", "nosniff") + h.Set("Referrer-Policy", "no-referrer") + h.Set("Cache-Control", "no-store") + next.ServeHTTP(w, r) + }) +} + +func isAPIPath(path string) bool { + return path == "/api" || strings.HasPrefix(path, "/api/") +} + +func crossOriginMiddleware(s *WebServer, next http.Handler) http.Handler { + cop := http.NewCrossOriginProtection() + cop.SetDenyHandler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + s.log.WarnContext(r.Context(), "cross-origin request refused", "method", r.Method, "path", r.URL.Path, + "origin", clientOrigin(r, s.cfg.TrustedProxies)) + if isAPIPath(r.URL.Path) { + writeJSONError(w, http.StatusForbidden, msgCrossOrigin) + return + } + http.Error(w, msgCrossOrigin, http.StatusForbidden) + })) + return cop.Handler(next) +} + +func writeJSON(w http.ResponseWriter, status int, body []byte) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(status) + _, _ = w.Write(body) +} + +func errorBody(message string) []byte { + b, _ := json.Marshal(map[string]string{"error": message}) + return b +} + +func writeJSONError(w http.ResponseWriter, status int, message string) { + writeJSON(w, status, errorBody(message)) +} + +func isDatabaseUnavailable(err error) bool { + var ne net.Error + return errors.Is(err, errDatabase) || errors.Is(err, driver.ErrBadConn) || errors.Is(err, mysql.ErrInvalidConn) || + errors.Is(err, sql.ErrConnDone) || errors.As(err, &ne) +} + +func (s *WebServer) authenticate(r *http.Request) (principal, error) { + token, ok := requestSessionToken(r) + if !ok { + return principal{}, errNoSession + } + if s.store == nil { + return principal{}, errDatabase + } + ctx := r.Context() + hash := sessionTokenHash(token) + sw, err := s.store.SessionByTokenHash(ctx, hash) + if errors.Is(err, errRowNotFound) { + return principal{}, errNoSession + } + if err != nil { + return principal{}, err + } + now := s.now() + if !sessionValid(sw.Session, sw.User, now, s.cfg.SessionIdleTimeout, s.cfg.SessionMaxAge) { + return principal{}, errNoSession + } + if sessionTouchDue(sw.Session, now) { + if err := s.store.TouchSession(ctx, hash, now); err != nil { + s.log.ErrorContext(ctx, "session touch failed", "error", err) + } + } + p := principal{User: sw.User, TokenHash: hash} + setRequestUser(r, p) + return p, nil +} + +func failureStatus(err error) (int, string) { + if isDatabaseUnavailable(err) { + return http.StatusServiceUnavailable, msgDatabaseDown + } + return http.StatusInternalServerError, msgInternalError +} + +func (s *WebServer) apiHandlers() map[string]apiHandler { + if s.apiHandlerSet != nil { + return s.apiHandlerSet + } + handlers, duplicates := mergeAPIHandlers(frameworkAPIHandlers(s), zoneAPIHandlers(s)) + for _, op := range duplicates { + s.log.Error("API operation has two handlers", "operation", op) + } + return handlers +} + +func mergeAPIHandlers(sets ...map[string]apiHandler) (map[string]apiHandler, []string) { + merged := map[string]apiHandler{} + var duplicates []string + for _, set := range sets { + for _, op := range slices.Sorted(maps.Keys(set)) { + if _, dup := merged[op]; dup { + duplicates = append(duplicates, op) + continue + } + merged[op] = set[op] + } + } + return merged, duplicates +} + +func missingAPIHandlers(handlers map[string]apiHandler) []string { + var missing []string + for _, route := range apiRoutes { + if handlers[route.Operation] == nil { + missing = append(missing, route.Operation) + } + } + return missing +} + +func (s *WebServer) checkAPIHandlers() error { + if missing := missingAPIHandlers(s.apiHandlers()); len(missing) > 0 { + return fmt.Errorf("API operations without a handler: %s", strings.Join(missing, ", ")) + } + return nil +} + +func notImplementedHandler(ctx context.Context, c *apiContext) (apiResponse, error) { + return apiResponse{}, &apiError{Status: http.StatusNotImplemented, Message: msgNotImplemented} +} + +func routeVariables(path string) int { + return strings.Count(path, "{") +} + +func (s *WebServer) apiRouter(handlers map[string]apiHandler) http.Handler { + for _, op := range missingAPIHandlers(handlers) { + s.log.Error("API route has no handler", "operation", op) + } + r := mux.NewRouter() + r.NotFoundHandler = http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + writeJSONError(w, http.StatusNotFound, msgNotFound) + }) + byPath := map[string]map[string]apiRoute{} + var paths []string + for _, route := range apiRoutes { + if byPath[route.Path] == nil { + byPath[route.Path] = map[string]apiRoute{} + paths = append(paths, route.Path) + } + byPath[route.Path][route.Method] = route + } + slices.SortStableFunc(paths, func(a, b string) int { return cmp.Compare(routeVariables(a), routeVariables(b)) }) + for _, path := range paths { + methods := byPath[path] + allow := strings.Join(slices.Sorted(maps.Keys(methods)), ", ") + served := map[string]http.HandlerFunc{} + for method, route := range methods { + h := handlers[route.Operation] + if h == nil { + h = notImplementedHandler + } + served[method] = s.serveAPI(route, h) + } + r.HandleFunc(apiPrefix+path, func(w http.ResponseWriter, req *http.Request) { + if h, ok := served[req.Method]; ok { + h(w, req) + return + } + w.Header().Set("Allow", allow) + writeJSONError(w, http.StatusMethodNotAllowed, msgMethodNotAllowed) + }) + } + return r +} + +func (s *WebServer) serveAPI(route apiRoute, h apiHandler) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + ctx := r.Context() + p, err := s.authenticate(r) + if err != nil { + if errors.Is(err, errNoSession) { + writeJSONError(w, http.StatusUnauthorized, msgAuthRequired) + return + } + s.log.ErrorContext(ctx, "session lookup failed", "error", err) + status, msg := failureStatus(err) + writeJSONError(w, status, msg) + return + } + now := s.now().UTC() + entry := apiAuditEntry(now, p, clientOrigin(r, s.cfg.TrustedProxies), route.Operation, "") + c := &apiContext{Request: r, Principal: p, Vars: mux.Vars(r), Now: now, Entry: &entry, Server: s, bodyLimit: route.BodyLimit} + resp, err := s.authorizeAPI(ctx, c, route) + if err == nil { + err = precheckBody(r, route.BodyLimit) + } + if err == nil { + resp, err = h(ctx, c) + } + s.finishAPI(ctx, w, c, resp, err) + } +} + +func (s *WebServer) authorizeAPI(ctx context.Context, c *apiContext, route apiRoute) (apiResponse, error) { + if authorize(route.Access, &c.Principal, true) == accessForbidden { + s.log.WarnContext(ctx, "admin route refused", "operation", route.Operation, "user", c.Principal.User.Username) + return apiResponse{}, &apiError{Status: http.StatusForbidden, Message: msgAdminRequired} + } + if !routeHasZone(route.Path) { + return apiResponse{}, nil + } + zone, err := normalizeZone(c.Vars["zone"]) + if err != nil { + return apiResponse{}, errZoneNotFound() + } + c.Zone = zone + c.Entry.Zone = sql.NullString{String: zone, Valid: true} + if !needsDelegation(route.Access, c.Principal) { + return apiResponse{}, nil + } + delegated, err := s.store.HasDelegation(ctx, zone, c.Principal.User.ID) + if err != nil { + return apiResponse{}, err + } + if authorize(route.Access, &c.Principal, delegated) == accessNotFound { + s.log.WarnContext(ctx, "zone not delegated", "operation", route.Operation, "zone", zone, "user", c.Principal.User.Username) + return apiResponse{}, errZoneNotFound() + } + return apiResponse{}, nil +} + +func (s *WebServer) errorResponse(ctx context.Context, c *apiContext, err error) (apiResponse, string) { + var ae *apiError + switch { + case errors.As(err, &ae): + body := map[string]any{} + for k, v := range ae.Extra { + body[k] = v + } + body["error"] = ae.Message + if ae.Fields != nil { + body["fields"] = ae.Fields + } + switch ae.Status { + case http.StatusForbidden, http.StatusConflict, http.StatusPreconditionFailed, http.StatusTooManyRequests: + s.log.WarnContext(ctx, "request refused", "operation", c.Entry.Operation, "status", ae.Status, "error", ae.Message) + default: + s.log.DebugContext(ctx, "request failed", "operation", c.Entry.Operation, "status", ae.Status, "error", ae.Message) + } + return apiResponse{Status: ae.Status, Body: body}, ae.Message + case errors.Is(err, errLockTimeout): + s.log.WarnContext(ctx, "zone lock timeout", "operation", c.Entry.Operation, "zone", c.Zone) + return apiResponse{Status: http.StatusServiceUnavailable, Body: map[string]any{"error": msgZoneBusy}}, msgZoneBusy + } + s.log.ErrorContext(ctx, "request failed", "operation", c.Entry.Operation, "error", err) + status, msg := failureStatus(err) + return apiResponse{Status: status, Body: map[string]any{"error": msg}}, msg +} + +type preparedResponse struct { + status int + contentType string + header http.Header + body []byte +} + +func prepareResponse(resp apiResponse) (preparedResponse, error) { + p := preparedResponse{status: cmp.Or(resp.Status, http.StatusOK), header: resp.Header} + switch { + case p.status == http.StatusNoContent: + case resp.Raw != nil: + p.contentType, p.body = resp.ContentType, resp.Raw + default: + b, err := json.Marshal(resp.Body) + if err != nil { + return preparedResponse{}, err + } + p.contentType, p.body = "application/json", b + } + return p, nil +} + +func internalErrorResponse() preparedResponse { + return preparedResponse{status: http.StatusInternalServerError, contentType: "application/json", body: errorBody(msgInternalError)} +} + +func (s *WebServer) insertAudit(ctx context.Context, e auditEntry) error { + ctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), auditInsertTimeout) + defer cancel() + if s.store == nil { + return errDatabase + } + _, err := s.store.InsertAudit(ctx, e) + return err +} + +func (s *WebServer) finishAPI(ctx context.Context, w http.ResponseWriter, c *apiContext, resp apiResponse, err error) { + message := "" + if err != nil { + resp, message = s.errorResponse(ctx, c, err) + c.auditDone = false + } + out, perr := prepareResponse(resp) + if perr != nil { + s.log.ErrorContext(ctx, "encode response failed", "operation", c.Entry.Operation, "error", perr) + out, message, c.auditDone = internalErrorResponse(), msgInternalError, false + } + if c.auditDone { + s.log.InfoContext(ctx, "change committed", "operation", c.Entry.Operation, "zone", c.Entry.Zone.String, + "record_id", c.Entry.RecordID.Int64, "target_user_id", c.Entry.TargetUserID.Int64, "actor", c.Entry.Actor) + } else { + c.Entry.Before, c.Entry.After = nil, nil + finishAuditEntry(c.Entry, out.status, message) + if aerr := s.insertAudit(ctx, *c.Entry); aerr != nil { + s.log.ErrorContext(ctx, "audit insert failed", "operation", c.Entry.Operation, "status", out.status, "error", aerr) + out = internalErrorResponse() + } + } + for k, vs := range out.header { + for _, v := range vs { + w.Header().Add(k, v) + } + } + if out.contentType != "" { + w.Header().Set("Content-Type", out.contentType) + } + w.WriteHeader(out.status) + if out.body != nil { + _, _ = w.Write(out.body) + } +} + +func registerAppRoutes(s *WebServer, r *mux.Router) { + r.PathPrefix("/api/").Handler(s.apiRouter(s.apiHandlers())) + s.registerPageRoutes(r) +} diff --git a/middleware_test.go b/middleware_test.go new file mode 100644 index 0000000..ec6eca4 --- /dev/null +++ b/middleware_test.go @@ -0,0 +1,721 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright (C) 2026 Bryan Joshua Pedini + +package main + +import ( + "context" + "database/sql" + "database/sql/driver" + "encoding/json" + "errors" + "fmt" + "net" + "net/http" + "net/http/httptest" + "net/netip" + "reflect" + "slices" + "strings" + "testing" + "time" + + "github.com/go-sql-driver/mysql" +) + +func decodeRequest(body, contentType string, limit int64) *apiContext { + r := httptest.NewRequest("POST", "/api/v1/x", strings.NewReader(body)) + if contentType != "" { + r.Header.Set("Content-Type", contentType) + } + return &apiContext{Request: r, bodyLimit: limit} +} + +type decodeTarget struct { + Name string `json:"name"` + TTL int64 `json:"ttl"` + Flag bool `json:"flag"` + Items []int `json:"items"` +} + +func TestDecodeJSON(t *testing.T) { + cases := []struct { + body string + ctype string + limit int64 + status int + msg string + field string + }{ + {`{"name":"a","ttl":5}`, "application/json", 0, 0, "", ""}, + {`{"name":"a"}`, "application/json; charset=utf-8", 0, 0, "", ""}, + {" \n{} \n", "application/json", 0, 0, "", ""}, + {"", "application/json", 0, 400, "request body is required", ""}, + {" ", "", 0, 400, "request body is required", ""}, + {`{"name":"a"}`, "text/plain", 0, 415, "content type must be application/json", ""}, + {`{"name":"a"}`, "", 0, 415, "content type must be application/json", ""}, + {`{"name":"a"}`, "application/jsonx", 0, 415, "content type must be application/json", ""}, + {`{"name":"` + strings.Repeat("a", 70000) + `"}`, "application/json", 0, 413, "request body too large", ""}, + {`{"name":"abcdef"}`, "application/json", 10, 413, "request body too large", ""}, + {`{"name":"a"}`, "application/json", 12, 0, "", ""}, + {`[1,2]`, "application/json", 0, 400, "request body must be a JSON object", ""}, + {`"x"`, "application/json", 0, 400, "request body must be a JSON object", ""}, + {`{"name":`, "application/json", 0, 400, "malformed JSON", ""}, + {`{"name":"a",}`, "application/json", 0, 400, "malformed JSON", ""}, + {`{"other":1}`, "application/json", 0, 400, "request body has an unknown field", ""}, + {`{"name":"a"}{"name":"b"}`, "application/json", 0, 400, "request body has trailing data", ""}, + {`{"name":"a"} x`, "application/json", 0, 400, "request body has trailing data", ""}, + {`{"ttl":"3600"}`, "application/json", 0, 422, "invalid field type", "ttl"}, + {`{"ttl":1.5}`, "application/json", 0, 422, "invalid field type", "ttl"}, + {`{"ttl":99999999999999999999}`, "application/json", 0, 422, "invalid field type", "ttl"}, + {`{"name":5}`, "application/json", 0, 422, "invalid field type", "name"}, + {`{"flag":"yes"}`, "application/json", 0, 422, "invalid field type", "flag"}, + {`{"items":{}}`, "application/json", 0, 422, "invalid field type", "items"}, + } + for i, c := range cases { + var dst decodeTarget + err := decodeRequest(c.body, c.ctype, c.limit).decodeJSON(&dst) + if c.status == 0 { + if err != nil { + t.Errorf("case %d: %v", i, err) + } + continue + } + var ae *apiError + if !errors.As(err, &ae) || ae.Status != c.status || ae.Message != c.msg || (c.field != "" && ae.Fields[c.field] == "") { + t.Errorf("case %d: %#v", i, err) + } + } + var dst decodeTarget + if err := decodeRequest(`{"name":"x","ttl":7,"flag":true,"items":[1]}`, "application/json", 0).decodeJSON(&dst); err != nil || dst.Name != "x" || dst.TTL != 7 || !dst.Flag || dst.Items[0] != 1 { + t.Fatal(dst, err) + } + c := decodeRequest("{}", "application/json", 0) + c.Request.Body = errReadCloser{} + var ae *apiError + if err := c.decodeJSON(&dst); !errors.As(err, &ae) || ae.Status != 400 { + t.Fatal(err) + } +} + +type errReadCloser struct{} + +func (errReadCloser) Read([]byte) (int, error) { return 0, errors.New("broken body") } + +func (errReadCloser) Close() error { return nil } + +func TestJSONTypeMessages(t *testing.T) { + var s struct { + I int `json:"i"` + U uint8 `json:"u"` + F float64 `json:"f"` + S string `json:"s"` + B bool `json:"b"` + A []int `json:"a"` + M map[string]int + O struct{} `json:"o"` + P *int `json:"p"` + } + cases := map[string]string{ + `{"i":"x"}`: "must be a number", + `{"i":1.5}`: "must be an integer in range", + `{"u":300}`: "must be an integer in range", + `{"f":"x"}`: "must be a number", + `{"s":1}`: "must be a string", + `{"b":1}`: "must be a boolean", + `{"a":1}`: "must be an array", + `{"M":1}`: "must be an object", + `{"o":1}`: "must be an object", + `{"p":"x"}`: "must be a number", + `{"o":[1]}`: "must be an object", + `{"a":["x"]}`: "must be a number", + } + for body, want := range cases { + err := json.Unmarshal([]byte(body), &s) + var te *json.UnmarshalTypeError + if !errors.As(err, &te) { + t.Fatalf("%s: %v", body, err) + } + if got := jsonTypeMessage(te); got != want { + t.Errorf("%s: %q", body, got) + } + } + if jsonTypeMessage(&json.UnmarshalTypeError{}) != "has the wrong type" { + t.Fatal("nil type") + } + var ch chan int + if jsonTypeMessage(&json.UnmarshalTypeError{Type: reflect.TypeOf(ch)}) != "has the wrong type" { + t.Fatal("other kind") + } +} + +func TestClientOrigin(t *testing.T) { + trusted := []netip.Prefix{netip.MustParsePrefix("10.0.0.0/8"), netip.MustParsePrefix("fd00::/8")} + cases := []struct { + remote string + xff []string + trusted []netip.Prefix + want string + }{ + {"192.0.2.1:1234", nil, nil, "192.0.2.1"}, + {"192.0.2.1:1234", []string{"203.0.113.9"}, nil, "192.0.2.1"}, + {"192.0.2.1:1234", []string{"203.0.113.9"}, trusted, "192.0.2.1"}, + {"10.1.2.3:1234", []string{"203.0.113.9"}, trusted, "203.0.113.9"}, + {"10.1.2.3:1234", []string{"198.51.100.1, 203.0.113.9, 10.9.9.9"}, trusted, "203.0.113.9"}, + {"10.1.2.3:1234", []string{"198.51.100.1", "203.0.113.9, 10.9.9.9"}, trusted, "203.0.113.9"}, + {"10.1.2.3:1234", []string{"10.5.5.5, 10.6.6.6"}, trusted, "10.5.5.5"}, + {"10.1.2.3:1234", nil, trusted, "10.1.2.3"}, + {"10.1.2.3:1234", []string{"garbage"}, trusted, "10.1.2.3"}, + {"10.1.2.3:1234", []string{"203.0.113.7, garbage, 10.9.9.9"}, trusted, "10.9.9.9"}, + {"10.1.2.3:1234", []string{"203.0.113.9:5555"}, trusted, "203.0.113.9"}, + {"10.1.2.3:1234", []string{"[2001:db8::7]:443"}, trusted, "2001:db8::7"}, + {"10.1.2.3:1234", []string{"[2001:db8::8]"}, trusted, "2001:db8::8"}, + {"[2001:db8::1]:443", nil, nil, "2001:db8::1"}, + {"[fd00::1]:443", []string{"2001:db8::5"}, trusted, "2001:db8::5"}, + {"[fe80::1%eth0]:443", nil, nil, "fe80::1"}, + {"[::ffff:192.0.2.4]:443", nil, nil, "192.0.2.4"}, + {"[::ffff:10.0.0.4]:443", []string{"::ffff:203.0.113.4"}, trusted, "203.0.113.4"}, + {"pipe", nil, nil, "pipe"}, + {"bad\x00host", nil, nil, "bad host"}, + } + for _, c := range cases { + r := httptest.NewRequest("GET", "/", nil) + r.RemoteAddr = c.remote + for _, v := range c.xff { + r.Header.Add("X-Forwarded-For", v) + } + if got := clientOrigin(r, c.trusted); got != c.want { + t.Errorf("%s %v: %q, want %q", c.remote, c.xff, got, c.want) + } + } +} + +func TestSecurityHeadersEverywhere(t *testing.T) { + h := newWebHarness(t) + admin := h.user("admin", roleAdmin) + token := h.login(admin) + paths := []webRequest{ + {method: "GET", path: "/login"}, + {method: "GET", path: "/", token: token}, + {method: "GET", path: "/"}, + {method: "GET", path: "/version"}, + {method: "GET", path: "/missing"}, + {method: "GET", path: "/api/v1/account"}, + {method: "GET", path: "/api/v1/account", token: token}, + {method: "GET", path: "/api/v1/nothing"}, + {method: "POST", path: "/api/v1/users", header: map[string]string{"Sec-Fetch-Site": "cross-site"}}, + {method: "GET", path: h.s.pages.staticPrefix() + "css/app.css"}, + {method: "GET", path: "/health"}, + } + for _, p := range paths { + res := h.do(p) + hd := res.header + if hd.Get("Content-Security-Policy") != "default-src 'none'; script-src 'self'; style-src 'self'; img-src 'self' data:; connect-src 'self'; form-action 'self'; frame-ancestors 'none'; base-uri 'none'" || + hd.Get("X-Content-Type-Options") != "nosniff" || hd.Get("Referrer-Policy") != "no-referrer" { + t.Errorf("%s %s: %v", p.method, p.path, hd) + } + wantCache := "no-store" + if strings.HasPrefix(p.path, "/static/") { + wantCache = "public, max-age=31536000, immutable" + } + if hd.Get("Cache-Control") != wantCache { + t.Errorf("%s: cache %q", p.path, hd.Get("Cache-Control")) + } + } +} + +func TestCrossOriginProtection(t *testing.T) { + h := newWebHarness(t) + admin := h.user("admin", roleAdmin) + token := h.login(admin) + refused := []webRequest{ + {method: "POST", path: "/api/v1/users", token: token, body: `{}`, header: map[string]string{"Sec-Fetch-Site": "cross-site"}}, + {method: "PUT", path: "/api/v1/account/password", token: token, body: `{}`, header: map[string]string{"Sec-Fetch-Site": "same-site"}}, + {method: "DELETE", path: "/api/v1/users/bob", token: token, header: map[string]string{"Origin": "https://evil.example"}}, + {method: "POST", path: "/login", body: "username=admin&password=x", ctype: "application/x-www-form-urlencoded", header: map[string]string{"Sec-Fetch-Site": "cross-site"}}, + {method: "POST", path: "/logout", token: token, header: map[string]string{"Origin": "https://evil.example"}}, + } + for _, r := range refused { + res := h.do(r) + if res.status != http.StatusForbidden || len(res.audit) != 0 { + t.Fatalf("%s %s: %d %d", r.method, r.path, res.status, len(res.audit)) + } + if strings.HasPrefix(r.path, "/api/") && res.body != `{"error":"cross-origin request refused"}` { + t.Fatalf("%s", res.body) + } + } + if h.store.sessionCount(admin.ID) != 1 { + t.Fatal("refused logout ended the session") + } + if !strings.Contains(h.logs.String(), "cross-origin request refused") { + t.Fatal("refusal not logged") + } + res := h.do(webRequest{method: "GET", path: "/api/v1/account", token: token, header: map[string]string{"Sec-Fetch-Site": "cross-site"}}) + if res.status != 200 { + t.Fatalf("safe method refused: %d", res.status) + } + res = h.do(webRequest{method: "PUT", path: "/api/v1/users/admin/role", token: token, body: `{"role":"user"}`, header: map[string]string{"Sec-Fetch-Site": "same-origin"}}) + if res.status != http.StatusForbidden || res.body != `{"error":"use the account page to change your own account"}` || len(res.audit) != 1 { + t.Fatalf("same-origin request: %d %s", res.status, res.body) + } + res = h.do(webRequest{method: "POST", path: "/api/v1/users", token: token, body: `{"username":"x1","role":"user","password":"long-enough-pw"}`, header: map[string]string{"Origin": "http://example.com"}}) + if res.status != http.StatusCreated { + t.Fatalf("matching origin refused: %d %s", res.status, res.body) + } +} + +func TestAPIRouterNotFoundAndMethods(t *testing.T) { + h := newWebHarness(t) + token := h.login(h.user("admin", roleAdmin)) + for _, p := range []string{"/api/v1/nothing", "/api/v1/", "/api/v2/account", "/api/v1/zones/a/b/c/d/e", "/api/v1/account/password/x"} { + res := h.do(webRequest{method: "GET", path: p, token: token}) + if res.status != 404 || res.body != `{"error":"not found"}` || res.header.Get("Content-Type") != "application/json" || len(res.audit) != 0 { + t.Errorf("%s: %d %s", p, res.status, res.body) + } + } + cases := map[string]string{ + "PATCH /api/v1/account": "GET", + "POST /api/v1/account": "GET", + "GET /api/v1/account/password": "PUT", + "PUT /api/v1/users": "GET, POST", + "POST /api/v1/zones/example.org.": "DELETE, GET", + "GET /api/v1/zones/example.org./records/delete": "POST", + "PATCH /api/v1/zones/example.org./records/1": "DELETE, PUT", + "POST /api/v1/zones/example.org./users/bob": "DELETE, PUT", + "HEAD /api/v1/audit": "GET", + } + for req, allow := range cases { + method, path, _ := strings.Cut(req, " ") + res := h.do(webRequest{method: method, path: path, token: token}) + if res.status != 405 || res.header.Get("Allow") != allow || len(res.audit) != 0 { + t.Errorf("%s: %d %q", req, res.status, res.header.Get("Allow")) + } + if method != "HEAD" && res.body != `{"error":"method not allowed"}` { + t.Errorf("%s: %s", req, res.body) + } + } +} + +func TestAPIAuthentication(t *testing.T) { + h := newWebHarness(t) + alice := h.user("alice", roleUser) + gone := h.user("gone", roleUser) + goneToken := h.login(gone) + gone.DeletedAt = sql.NullTime{Time: webNow, Valid: true} + h.store.setUser(gone) + fresh := h.login(alice) + stale := h.store.addSession(alice, webNow.Add(-2*time.Hour), webNow.Add(-time.Hour)) + old := h.store.addSession(alice, webNow.Add(-12*time.Hour), webNow.Add(-time.Minute)) + unknown, _, _ := newSessionToken(strings.NewReader(strings.Repeat("u", 32))) + for name, token := range map[string]string{"none": "", "malformed": "abc", "unknown": unknown, "idle": stale, "max age": old, "deleted user": goneToken} { + res := h.api("GET", "/account", token, "") + if res.status != 401 || res.body != `{"error":"authentication required"}` || len(res.audit) != 0 { + t.Errorf("%s: %d %s %d", name, res.status, res.body, len(res.audit)) + } + } + if res := h.api("GET", "/account", fresh, ""); res.status != 200 { + t.Fatal(res.status) + } + h.store.failOn["SessionByTokenHash"] = errDatabase + res := h.api("GET", "/account", fresh, "") + if res.status != 503 || res.body != `{"error":"database unavailable"}` || len(res.audit) != 0 { + t.Fatalf("%d %s", res.status, res.body) + } + h.store.failOn["SessionByTokenHash"] = errors.New("syntax error near SELECT") + res = h.api("GET", "/account", fresh, "") + if res.status != 500 || res.body != `{"error":"internal error"}` { + t.Fatalf("%d %s", res.status, res.body) + } + h.s.store = nil + if res := h.api("GET", "/account", fresh, ""); res.status != 503 { + t.Fatal(res.status) + } + if res := h.api("GET", "/account", "", ""); res.status != 401 { + t.Fatal(res.status) + } +} + +func TestSessionTouchedAtMostOncePerMinute(t *testing.T) { + h := newWebHarness(t) + alice := h.user("alice", roleUser) + token := h.login(alice) + h.clock.advance(30 * time.Second) + h.api("GET", "/account", token, "") + if h.store.called("TouchSession") != 0 { + t.Fatal("touched within a minute") + } + h.clock.advance(31 * time.Second) + h.api("GET", "/account", token, "") + h.api("GET", "/account", token, "") + if h.store.called("TouchSession") != 1 { + t.Fatal(h.store.called("TouchSession")) + } + h.clock.advance(59 * time.Minute) + if res := h.api("GET", "/account", token, ""); res.status != 200 { + t.Fatal("touch did not extend the idle timeout") + } + h.clock.advance(time.Hour) + if res := h.api("GET", "/account", token, ""); res.status != 401 { + t.Fatal("idle session accepted") + } + token = h.login(alice) + h.clock.advance(2 * time.Minute) + h.store.failOn["TouchSession"] = errors.New("touch failed") + if res := h.api("GET", "/account", token, ""); res.status != 200 || !strings.Contains(h.logs.String(), "session touch failed") { + t.Fatal("touch failure must not fail the request") + } +} + +func TestRoleReadOnEveryRequest(t *testing.T) { + h := newWebHarness(t) + h.user("root", roleAdmin) + bob := h.user("bob", roleUser) + token := h.login(bob) + if res := h.api("GET", "/users", token, ""); res.status != 403 { + t.Fatal(res.status) + } + bob.Role = roleAdmin + h.store.setUser(bob) + if res := h.api("GET", "/users", token, ""); res.status != 200 { + t.Fatal("promotion not applied on the next request") + } + bob.Role = roleUser + h.store.setUser(bob) + if res := h.api("GET", "/users", token, ""); res.status != 403 { + t.Fatal("demotion not applied on the next request") + } +} + +func frameworkTestHandlers(extra map[string]apiHandler) map[string]apiHandler { + m := map[string]apiHandler{} + for _, r := range apiRoutes { + m[r.Operation] = func(ctx context.Context, c *apiContext) (apiResponse, error) { + return okJSON(map[string]string{"zone": c.Zone}), nil + } + } + for k, v := range extra { + m[k] = v + } + return m +} + +func TestFrameworkErrorMapping(t *testing.T) { + var lastCtx *apiContext + handlers := frameworkTestHandlers(map[string]apiHandler{ + opZoneList: func(ctx context.Context, c *apiContext) (apiResponse, error) { + lastCtx = c + switch c.Request.URL.Query().Get("case") { + case "fields": + return apiResponse{}, &apiError{Status: 422, Message: "invalid record", Fields: map[string]string{"ttl": "out of range"}} + case "extra": + return apiResponse{}, &apiError{Status: 422, Message: "the file has errors", Extra: map[string]any{"errors": []map[string]any{{"line": 3, "message": "bad"}}}} + case "conflict": + return apiResponse{}, fmt.Errorf("wrapped: %w", &apiError{Status: 409, Message: "zone already exists"}) + case "lock": + return apiResponse{}, fmt.Errorf("write: %w", errLockTimeout) + case "db": + return apiResponse{}, fmt.Errorf("query: %w", errDatabase) + case "badconn": + return apiResponse{}, driver.ErrBadConn + case "invalidconn": + return apiResponse{}, mysql.ErrInvalidConn + case "connerr": + return apiResponse{}, &net.OpError{Op: "dial", Err: errors.New("refused")} + case "sql": + return apiResponse{}, errors.New("Error 1064: You have an error in your SQL syntax near 'SELECT password_hash'") + case "encode": + return apiResponse{Status: 200, Body: map[string]any{"x": func() {}}}, nil + case "raw": + return apiResponse{Status: 200, Raw: []byte("$ORIGIN example.org.\n"), ContentType: "text/plain; charset=utf-8", + Header: http.Header{"Content-Disposition": {`attachment; filename="example.org.zone"`}, "Etag": {`"abc"`}}}, nil + case "created": + return apiResponse{Status: 201, Body: map[string]int{"id": 1}, Header: http.Header{"ETag": {`"e1"`}}}, nil + case "nocontent": + return apiResponse{Status: 204, Body: map[string]int{"ignored": 1}}, nil + case "default": + return apiResponse{Body: []int{}}, nil + } + return okJSON(map[string]string{}), nil + }, + }) + h := newWebHarness(t) + h.withHandlers(handlers) + admin := h.user("admin", roleAdmin) + token := h.login(admin) + cases := []struct { + name string + status int + body string + }{ + {"fields", 422, `{"error":"invalid record","fields":{"ttl":"out of range"}}`}, + {"extra", 422, `{"error":"the file has errors","errors":[{"line":3,"message":"bad"}]}`}, + {"conflict", 409, `{"error":"zone already exists"}`}, + {"lock", 503, `{"error":"zone busy"}`}, + {"db", 503, `{"error":"database unavailable"}`}, + {"badconn", 503, `{"error":"database unavailable"}`}, + {"invalidconn", 503, `{"error":"database unavailable"}`}, + {"connerr", 503, `{"error":"database unavailable"}`}, + {"sql", 500, `{"error":"internal error"}`}, + {"encode", 500, `{"error":"internal error"}`}, + {"created", 201, `{"id":1}`}, + {"nocontent", 204, ``}, + {"default", 200, `[]`}, + } + for _, c := range cases { + res := h.api("GET", "/zones?case="+c.name, token, "") + if res.status != c.status || res.body != c.body { + t.Errorf("%s: %d %s", c.name, res.status, res.body) + continue + } + e := expectOneAudit(t, res, opZoneList, c.status) + if e.Before != nil || e.After != nil { + t.Errorf("%s: before/after on a read", c.name) + } + if c.status != 204 && res.header.Get("Content-Type") != "application/json" { + t.Errorf("%s: content type %q", c.name, res.header.Get("Content-Type")) + } + } + res := h.api("GET", "/zones?case=created", token, "") + if res.header.Get("ETag") != `"e1"` { + t.Fatal(res.header) + } + res = h.api("GET", "/zones?case=raw", token, "") + if res.status != 200 || res.body != "$ORIGIN example.org.\n" || res.header.Get("Content-Type") != "text/plain; charset=utf-8" || + res.header.Get("Content-Disposition") != `attachment; filename="example.org.zone"` || res.header.Get("ETag") != `"abc"` { + t.Fatalf("%d %v %q", res.status, res.header, res.body) + } + logs := h.logs.String() + if !strings.Contains(logs, "password_hash'") || !strings.Contains(logs, "level=ERROR msg=\"request failed\"") { + t.Fatal("500 not logged at ERROR with its cause") + } + if !strings.Contains(logs, "level=WARN msg=\"zone lock timeout\"") || !strings.Contains(logs, "level=WARN msg=\"request refused\" operation=zone_list status=409") { + t.Fatal("warnings missing") + } + if lastCtx.Zone != "" || lastCtx.Server != h.s || lastCtx.Principal.User.ID != admin.ID || !lastCtx.Now.Equal(webNow) || lastCtx.Entry.Actor != "admin" { + t.Fatalf("%+v", lastCtx) + } +} + +func TestZoneRouteNormalizationAndDelegation(t *testing.T) { + var seen []string + handlers := frameworkTestHandlers(map[string]apiHandler{ + opZoneRead: func(ctx context.Context, c *apiContext) (apiResponse, error) { + seen = append(seen, c.Zone+"|"+c.Entry.Zone.String+"|"+c.Vars["zone"]) + if c.Zone == otherZone { + return apiResponse{}, errZoneNotFound() + } + return okJSON(map[string]string{"zone": c.Zone}), nil + }, + }) + h := newWebHarness(t) + h.withHandlers(handlers) + admin := h.user("admin", roleAdmin) + alice := h.user("alice", roleUser) + h.store.delegate(testZone, alice) + at, ut := h.login(admin), h.login(alice) + res := h.api("GET", "/zones/Example.ORG", ut, "") + if res.status != 200 || res.body != `{"zone":"example.org."}` { + t.Fatalf("%d %s", res.status, res.body) + } + e := expectOneAudit(t, res, opZoneRead, 200) + if e.Zone.String != testZone || e.UserID.Int64 != alice.ID || e.Actor != "alice" || e.Origin != "192.0.2.10" || !e.Time.Equal(webNow) { + t.Fatalf("%+v", e) + } + if seen[0] != "example.org.|example.org.|Example.ORG" { + t.Fatal(seen) + } + notDelegated := h.api("GET", "/zones/secret.org", ut, "") + missing := h.api("GET", "/zones/other.org.", at, "") + invalid := h.api("GET", "/zones/bad_zone!", ut, "") + invalidAdmin := h.api("GET", "/zones/a..b", at, "") + for name, r := range map[string]webResult{"not delegated": notDelegated, "missing": missing, "invalid": invalid, "invalid admin": invalidAdmin} { + if r.status != 404 || r.body != `{"error":"zone not found"}` || r.header.Get("Content-Type") != "application/json" { + t.Errorf("%s: %d %s", name, r.status, r.body) + } + expectOneAudit(t, r, opZoneRead, 404) + } + if notDelegated.audit[0].entry.Zone.String != "secret.org." || invalid.audit[0].entry.Zone.Valid { + t.Fatal("audit zone") + } + if len(seen) != 2 { + t.Fatal("handler ran for a refused zone", seen) + } + if !strings.Contains(h.logs.String(), `level=WARN msg="zone not delegated" operation=zone_read zone=secret.org. user=alice`) { + t.Fatal(h.logs.String()) + } + h.store.failOn["HasDelegation"] = errDatabase + if r := h.api("GET", "/zones/example.org", ut, ""); r.status != 503 { + t.Fatal(r.status) + } + if h.store.called("HasDelegation") != 3 { + t.Fatal("admins must not need a delegation lookup", h.store.called("HasDelegation")) + } +} + +func TestAdminRouteRefusedBeforeZone(t *testing.T) { + h := newWebHarness(t) + h.withHandlers(frameworkTestHandlers(nil)) + alice := h.user("alice", roleUser) + h.store.delegate(testZone, alice) + token := h.login(alice) + for _, r := range []struct{ method, path, op string }{ + {"GET", "/zones/example.org./users", opDelegationList}, + {"DELETE", "/zones/bad!/users/x", opDelegationRevoke}, + {"POST", "/zones", opZoneCreate}, + {"GET", "/users", opUserList}, + } { + res := h.api(r.method, r.path, token, "") + if res.status != 403 || res.body != `{"error":"admin role required"}` { + t.Fatalf("%s: %d %s", r.path, res.status, res.body) + } + if e := expectOneAudit(t, res, r.op, 403); e.Zone.Valid { + t.Fatal("zone recorded for a refused admin route") + } + } +} + +func TestBodyPrecheck(t *testing.T) { + h := newWebHarness(t) + h.withHandlers(frameworkTestHandlers(nil)) + token := h.login(h.user("admin", roleAdmin)) + res := h.do(webRequest{method: "PUT", path: "/api/v1/zones/example.org./users/bob", token: token, body: "x", ctype: "text/plain"}) + if res.status != 415 || res.body != `{"error":"content type must be application/json"}` { + t.Fatalf("%d %s", res.status, res.body) + } + expectOneAudit(t, res, opDelegationGrant, 415) + res = h.do(webRequest{method: "PUT", path: "/api/v1/zones/example.org./users/bob", token: token}) + if res.status != 200 { + t.Fatalf("body-less request refused: %d", res.status) + } + res = h.do(webRequest{method: "POST", path: "/api/v1/zones", token: token, body: `{"a":"` + strings.Repeat("x", 70000) + `"}`}) + if res.status != 413 || res.body != `{"error":"request body too large"}` { + t.Fatalf("%d %s", res.status, res.body) + } + res = h.do(webRequest{method: "POST", path: "/api/v1/zones/example.org./import/preview", token: token, body: `{"a":"` + strings.Repeat("x", 70000) + `"}`}) + if res.status != 200 { + t.Fatalf("import limit not applied: %d", res.status) + } + res = h.do(webRequest{method: "POST", path: "/api/v1/zones/example.org./import/apply", token: token, body: `{"a":"` + strings.Repeat("x", 2<<20) + `"}`}) + if res.status != 413 { + t.Fatalf("%d", res.status) + } +} + +func TestReadAuditFailureHidesData(t *testing.T) { + h := newWebHarness(t) + h.user("admin", roleAdmin) + token := h.login(h.store.user(1)) + h.store.failOn["InsertAudit"] = errors.New("audit table full") + res := h.api("GET", "/users", token, "") + if res.status != 500 || res.body != `{"error":"internal error"}` || strings.Contains(res.body, "admin") { + t.Fatalf("%d %s", res.status, res.body) + } + if !strings.Contains(h.logs.String(), `level=ERROR msg="audit insert failed" operation=user_list status=200`) { + t.Fatal(h.logs.String()) + } + res = h.api("GET", "/users/nobody", token, "") + if res.status != 500 || res.body != `{"error":"internal error"}` { + t.Fatalf("refusal with failing audit: %d %s", res.status, res.body) + } +} + +func TestChangeAuditFailureRollsBack(t *testing.T) { + h := newWebHarness(t) + h.user("admin", roleAdmin) + token := h.login(h.store.user(1)) + h.store.failOn["InsertAudit"] = errors.New("audit table full") + res := h.api("POST", "/users", token, `{"username":"newbie","role":"user","password":"long-enough-pw"}`) + if res.status != 500 || res.body != `{"error":"internal error"}` { + t.Fatalf("%d %s", res.status, res.body) + } + if _, err := h.store.UserByUsername(context.Background(), "newbie"); !errors.Is(err, errRowNotFound) { + t.Fatal("change survived a failed audit insert") + } + if h.store.rollbacks != 1 || h.store.commits != 0 { + t.Fatal(h.store.rollbacks, h.store.commits) + } + delete(h.store.failOn, "InsertAudit") + h.store.failOn["Commit"] = errors.New("commit failed") + res = h.api("POST", "/users", token, `{"username":"newbie","role":"user","password":"long-enough-pw"}`) + if res.status != 500 || len(res.audit) != 1 || res.audit[0].entry.Status.Int64 != 500 || res.audit[0].inTx || res.audit[0].entry.After != nil { + t.Fatalf("%d %+v", res.status, res.audit) + } +} + +func TestNotImplementedRoute(t *testing.T) { + h := newWebHarness(t) + handlers := frameworkTestHandlers(nil) + delete(handlers, opAuditRead) + h.withHandlers(handlers) + if err := h.s.checkAPIHandlers(); err == nil || err.Error() != "API operations without a handler: audit_read" { + t.Fatal(err) + } + if !strings.Contains(h.logs.String(), `msg="API route has no handler" operation=audit_read`) { + t.Fatal("missing handler not logged") + } + token := h.login(h.user("admin", roleAdmin)) + res := h.api("GET", "/audit", token, "") + if res.status != 501 || res.body != `{"error":"not implemented"}` { + t.Fatalf("%d %s", res.status, res.body) + } + expectOneAudit(t, res, opAuditRead, 501) +} + +func TestEveryRouteHasHandler(t *testing.T) { + h := newWebHarness(t) + handlers := h.s.apiHandlers() + if missing := missingAPIHandlers(handlers); len(missing) != 0 { + t.Fatalf("routes without handler: %v", missing) + } + if err := h.s.checkAPIHandlers(); err != nil { + t.Fatal(err) + } + framework := frameworkAPIHandlers(h.s) + for _, r := range apiRoutes { + _, own := framework[r.Operation] + if own == slices.Contains(zoneOperations, r.Operation) { + t.Errorf("%s: framework handler %v", r.Operation, own) + } + } +} + +func TestMergeAPIHandlers(t *testing.T) { + a := func(ctx context.Context, c *apiContext) (apiResponse, error) { return okJSON("a"), nil } + b := func(ctx context.Context, c *apiContext) (apiResponse, error) { return okJSON("b"), nil } + merged, dups := mergeAPIHandlers(map[string]apiHandler{"x": a, "y": a}, map[string]apiHandler{"y": b, "z": b}) + if len(merged) != 3 || !slices.Equal(dups, []string{"y"}) { + t.Fatal(merged, dups) + } + resp, _ := merged["y"](context.Background(), nil) + if resp.Body != "a" { + t.Fatal("first handler must win") + } +} + +func TestRequestLogging(t *testing.T) { + h := newWebHarness(t) + alice := h.user("alice", roleUser) + token := h.login(alice) + h.api("GET", "/account", token, "") + h.do(webRequest{method: "GET", path: "/health"}) + h.do(webRequest{method: "GET", path: h.s.pages.staticPrefix() + "css/app.css"}) + logs := h.logs.String() + if !strings.Contains(logs, `level=INFO msg=request method=GET path=/api/v1/account status=200`) || !strings.Contains(logs, "user=alice role=user origin=192.0.2.10") { + t.Fatal(logs) + } + if !strings.Contains(logs, `level=DEBUG msg=request method=GET path=/health status=503`) || !strings.Contains(logs, `level=DEBUG msg=request method=GET path=/static/`) { + t.Fatal(logs) + } + if strings.Contains(logs, token) { + t.Fatal("token logged") + } +} + +func TestIsAPIPath(t *testing.T) { + if !isAPIPath("/api") || !isAPIPath("/api/v1/x") || isAPIPath("/apix") || isAPIPath("/") { + t.Fatal("isAPIPath") + } + if !isDatabaseUnavailable(sql.ErrConnDone) || isDatabaseUnavailable(errors.New("x")) || isDatabaseUnavailable(nil) { + t.Fatal("isDatabaseUnavailable") + } +} diff --git a/ratelimit.go b/ratelimit.go new file mode 100644 index 0000000..0a1d053 --- /dev/null +++ b/ratelimit.go @@ -0,0 +1,155 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright (C) 2026 Bryan Joshua Pedini + +package main + +import ( + "sync" + "time" +) + +const ( + loginFailureLimit = 5 + loginFailureWindow = 15 * time.Minute + loginBlockDuration = 15 * time.Minute + loginLimiterMaxKeys = 10000 +) + +type limitEntry struct { + failures []time.Time + blockedUntil time.Time +} + +func (e *limitEntry) blocked(now time.Time) bool { + return now.Before(e.blockedUntil) +} + +func (e *limitEntry) prune(now time.Time) { + kept := e.failures[:0] + for _, t := range e.failures { + if now.Sub(t) < loginFailureWindow { + kept = append(kept, t) + } + } + e.failures = kept +} + +func (e *limitEntry) lastFailure() time.Time { + if len(e.failures) == 0 { + return time.Time{} + } + return e.failures[len(e.failures)-1] +} + +type limitTable struct { + max int + entries map[string]*limitEntry +} + +func newLimitTable(max int) *limitTable { + return &limitTable{max: max, entries: make(map[string]*limitEntry)} +} + +func (t *limitTable) prune(now time.Time) { + for key, e := range t.entries { + e.prune(now) + if len(e.failures) == 0 && !e.blocked(now) { + delete(t.entries, key) + } + } +} + +func (t *limitTable) evictOne(now time.Time) bool { + victim := "" + var oldest time.Time + for key, e := range t.entries { + if e.blocked(now) { + continue + } + if last := e.lastFailure(); victim == "" || last.Before(oldest) { + victim, oldest = key, last + } + } + if victim == "" { + return false + } + delete(t.entries, victim) + return true +} + +func (t *limitTable) full(now time.Time) bool { + if len(t.entries) < t.max { + return false + } + t.prune(now) + return len(t.entries) >= t.max +} + +func (t *limitTable) allows(key string, now time.Time) bool { + if e := t.entries[key]; e != nil { + return !e.blocked(now) + } + if !t.full(now) { + return true + } + for _, e := range t.entries { + if !e.blocked(now) { + return true + } + } + return false +} + +func (t *limitTable) fail(key string, now time.Time) { + e := t.entries[key] + if e == nil { + if t.full(now) && !t.evictOne(now) { + return + } + e = &limitEntry{} + t.entries[key] = e + } + if e.blocked(now) { + return + } + e.prune(now) + e.failures = append(e.failures, now) + if len(e.failures) >= loginFailureLimit { + e.blockedUntil = now.Add(loginBlockDuration) + e.failures = nil + } +} + +type loginLimiter struct { + mu sync.Mutex + now func() time.Time + users *limitTable + origins *limitTable +} + +func newLoginLimiter(now func() time.Time, maxKeys int) *loginLimiter { + return &loginLimiter{now: now, users: newLimitTable(maxKeys), origins: newLimitTable(maxKeys)} +} + +func (l *loginLimiter) allow(username, origin string) bool { + l.mu.Lock() + defer l.mu.Unlock() + now := l.now() + userOK := l.users.allows(username, now) + originOK := l.origins.allows(origin, now) + return userOK && originOK +} + +func (l *loginLimiter) fail(username, origin string) { + l.mu.Lock() + defer l.mu.Unlock() + now := l.now() + l.users.fail(username, now) + l.origins.fail(origin, now) +} + +func (l *loginLimiter) succeed(username string) { + l.mu.Lock() + defer l.mu.Unlock() + delete(l.users.entries, username) +} diff --git a/ratelimit_test.go b/ratelimit_test.go new file mode 100644 index 0000000..bee0a47 --- /dev/null +++ b/ratelimit_test.go @@ -0,0 +1,173 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright (C) 2026 Bryan Joshua Pedini + +package main + +import ( + "strconv" + "testing" + "time" +) + +func newTestLimiter(max int) (*loginLimiter, *testClock) { + c := &testClock{now: webNow} + return newLoginLimiter(c.Now, max), c +} + +func TestLimiterBlocksAfterFiveFailuresPerUsername(t *testing.T) { + l, c := newTestLimiter(100) + for i := range 4 { + l.fail("alice", "192.0.2."+strconv.Itoa(i)) + if !l.allow("alice", "192.0.2.99") { + t.Fatalf("blocked after %d failures", i+1) + } + } + l.fail("alice", "192.0.2.4") + if l.allow("alice", "192.0.2.99") { + t.Fatal("not blocked after five failures") + } + if !l.allow("bob", "192.0.2.99") { + t.Fatal("other username blocked") + } + c.advance(loginBlockDuration - time.Second) + if l.allow("alice", "192.0.2.99") { + t.Fatal("block shorter than 15 minutes") + } + l.fail("alice", "192.0.2.99") + c.advance(time.Second) + if !l.allow("alice", "192.0.2.99") { + t.Fatal("block longer than 15 minutes or extended by failures while blocked") + } +} + +func TestLimiterBlocksPerOrigin(t *testing.T) { + l, _ := newTestLimiter(100) + for i := range 5 { + l.fail("user"+strconv.Itoa(i), "198.51.100.7") + } + if l.allow("fresh", "198.51.100.7") { + t.Fatal("origin not blocked") + } + if !l.allow("fresh", "198.51.100.8") { + t.Fatal("other origin blocked") + } +} + +func TestLimiterWindow(t *testing.T) { + l, c := newTestLimiter(100) + for range 4 { + l.fail("alice", "192.0.2.1") + } + c.advance(loginFailureWindow) + l.fail("alice", "192.0.2.1") + if !l.allow("alice", "192.0.2.1") { + t.Fatal("failures older than the window counted") + } + c.advance(time.Minute) + for range 3 { + l.fail("alice", "192.0.2.2") + } + if !l.allow("alice", "192.0.2.3") { + t.Fatal("blocked after four failures in the window") + } + l.fail("alice", "192.0.2.2") + if l.allow("alice", "192.0.2.3") { + t.Fatal("five failures in the window not blocked") + } +} + +func TestLimiterSuccessResetsUsername(t *testing.T) { + l, _ := newTestLimiter(100) + for range 4 { + l.fail("alice", "192.0.2.1") + } + l.succeed("alice") + for range 4 { + l.fail("alice", "192.0.2.2") + } + if !l.allow("alice", "192.0.2.3") { + t.Fatal("success did not reset the username counter") + } + l.fail("alice", "192.0.2.1") + if l.allow("bob", "192.0.2.1") { + t.Fatal("success reset the origin counter") + } +} + +func TestLimiterBoundedMemory(t *testing.T) { + l, c := newTestLimiter(10) + for i := range 1000 { + l.fail("u"+strconv.Itoa(i), "192.0.2.1") + c.advance(time.Millisecond) + } + if len(l.users.entries) > 10 || len(l.origins.entries) > 10 { + t.Fatal(len(l.users.entries), len(l.origins.entries)) + } +} + +func TestLimiterCannotEvictBlockedKey(t *testing.T) { + l, c := newTestLimiter(3) + for range 5 { + l.fail("victim", "192.0.2.1") + } + if l.allow("victim", "192.0.2.200") { + t.Fatal("victim not blocked") + } + for i := range 50 { + l.fail("noise"+strconv.Itoa(i), "203.0.113."+strconv.Itoa(i)) + c.advance(time.Second) + } + if l.allow("victim", "192.0.2.200") { + t.Fatal("flooding freed a blocked username") + } + if l.allow("x", "192.0.2.1") { + t.Fatal("flooding freed a blocked origin") + } + if len(l.users.entries) > 3 || len(l.origins.entries) > 3 { + t.Fatal("table grew") + } +} + +func TestLimiterFullOfBlockedKeys(t *testing.T) { + l, c := newTestLimiter(2) + for _, u := range []string{"a", "b"} { + for range 5 { + l.fail(u, "192.0.2."+u) + } + } + if l.allow("c", "192.0.2.c") { + t.Fatal("new key admitted while the table holds only blocked keys") + } + l.fail("c", "192.0.2.c") + if _, ok := l.users.entries["c"]; ok { + t.Fatal("new key stored past the bound") + } + c.advance(loginBlockDuration) + if !l.allow("c", "192.0.2.c") { + t.Fatal("expired blocks not pruned") + } + l.fail("c", "192.0.2.c") + if len(l.users.entries) != 1 { + t.Fatal(len(l.users.entries)) + } +} + +func TestLimiterEvictsOldestUnblocked(t *testing.T) { + tbl := newLimitTable(2) + tbl.fail("old", webNow) + tbl.fail("new", webNow.Add(time.Second)) + tbl.fail("third", webNow.Add(2*time.Second)) + if _, ok := tbl.entries["old"]; ok { + t.Fatal("oldest entry kept") + } + if _, ok := tbl.entries["new"]; !ok { + t.Fatal("newer entry evicted") + } + if !tbl.allows("fourth", webNow.Add(3*time.Second)) { + t.Fatal("unblocked entries can make room") + } + empty := &limitEntry{} + if !empty.lastFailure().IsZero() { + t.Fatal("last failure of empty entry") + } +} diff --git a/routes.go b/routes.go index 9582d26..9ecd5e4 100644 --- a/routes.go +++ b/routes.go @@ -14,9 +14,9 @@ type routeRegistrar func(s *WebServer, r *mux.Router) type handlerMiddleware func(s *WebServer, next http.Handler) http.Handler -var appRouteRegistrars = []routeRegistrar{} +var appRouteRegistrars = []routeRegistrar{registerAppRoutes} -var appMiddlewares = []handlerMiddleware{} +var appMiddlewares = []handlerMiddleware{requestLogMiddleware, securityHeadersMiddleware, crossOriginMiddleware} func (s *WebServer) Handler() http.Handler { r := mux.NewRouter() diff --git a/stores_test.go b/stores_test.go index eb65d87..bdc4811 100644 --- a/stores_test.go +++ b/stores_test.go @@ -376,15 +376,12 @@ func TestUserStoreUpdates(t *testing.T) { func TestAuditUserJSON(t *testing.T) { u := userRow{ID: 7, Username: "alice", Role: "admin", PasswordHash: "$secret", CreatedAt: time.Date(2026, 1, 2, 3, 4, 5, 6000, time.UTC)} - b, err := auditUserJSON(u) - if err != nil { - t.Fatal(err) - } + b := auditUserJSON(u) if string(b) != `{"id":7,"username":"alice","role":"admin","created_at":"2026-01-02T03:04:05.000006Z","deleted_at":null}` { t.Fatal(string(b)) } u.DeletedAt = sql.NullTime{Time: time.Date(2026, 2, 3, 4, 5, 6, 0, time.FixedZone("x", 7200)), Valid: true} - b, _ = auditUserJSON(u) + b = auditUserJSON(u) if !strings.Contains(string(b), `"deleted_at":"2026-02-03T02:05:06.000000Z"`) || strings.Contains(string(b), "secret") { t.Fatal(string(b)) } @@ -636,7 +633,7 @@ func TestAuditFilterSQL(t *testing.T) { t.Fatalf("%q lacks %q", where, f) } } - if len(args) != 3+len(auditStoreChangeOperations)+3 || args[len(args)-1] != int64(5) || args[len(args)-3] != int64(99) { + if len(args) != 3+len(auditChangeOperations)+3 || args[len(args)-1] != int64(5) || args[len(args)-3] != int64(99) { t.Fatalf("args %v", args) } where, _, _ = auditFilterSQL(auditFilter{Kind: "change", Outcome: "success"}) diff --git a/stub_contracts.go b/stub_contracts.go deleted file mode 100644 index 7ebf6f1..0000000 --- a/stub_contracts.go +++ /dev/null @@ -1,113 +0,0 @@ -// SPDX-License-Identifier: GPL-2.0-or-later -// Copyright (C) 2026 Bryan Joshua Pedini - -package main - -import ( - "bytes" - "context" - "database/sql" - "encoding/json" - "errors" - "io" - "mime" - "net/http" - "time" -) - -type auditEntry struct { - ID int64 - Time time.Time - UserID sql.NullInt64 - Actor string - Origin string - Operation string - Status sql.NullInt64 - Error sql.NullString - Zone sql.NullString - RecordID sql.NullInt64 - TargetUserID sql.NullInt64 - Before []byte - After []byte -} - -func stubHashPassword(password string) (string, error) { - return "", errors.New("password hashing is not available") -} - -type principal struct { - User userRow - TokenHash []byte -} - -func (p principal) isAdmin() bool { return p.User.Role == "admin" } - -type apiContext struct { - Request *http.Request - Principal principal - Zone string - Vars map[string]string - Now time.Time - Entry *auditEntry - Server *WebServer - auditDone bool -} - -type apiResponse struct { - Status int - Body any - Raw []byte - ContentType string - Header http.Header -} - -type apiError struct { - Status int - Message string - Fields map[string]string - Extra map[string]any -} - -func (e *apiError) Error() string { return e.Message } - -type apiHandler func(ctx context.Context, c *apiContext) (apiResponse, error) - -func (c *apiContext) decodeJSON(dst any) error { - invalid := &apiError{Status: http.StatusBadRequest, Message: "invalid JSON"} - if c.Request.Body == nil || c.Request.Body == http.NoBody { - return invalid - } - limit := int64(64 << 10) - if c.Entry.Operation == "zone_import_preview" || c.Entry.Operation == "zone_import" { - limit = zoneFileMaxBytes - } - body, err := io.ReadAll(io.LimitReader(c.Request.Body, limit+1)) - if err != nil { - return invalid - } - if int64(len(body)) > limit { - return &apiError{Status: http.StatusRequestEntityTooLarge, Message: "request body too large"} - } - if len(body) == 0 { - return invalid - } - contentType, _, err := mime.ParseMediaType(c.Request.Header.Get("Content-Type")) - if err != nil || contentType != "application/json" { - return &apiError{Status: http.StatusUnsupportedMediaType, Message: "expected application/json"} - } - decoder := json.NewDecoder(bytes.NewReader(body)) - decoder.DisallowUnknownFields() - if bytes.Equal(bytes.TrimSpace(body), []byte("null")) || decoder.Decode(dst) != nil || decoder.Decode(new(any)) != io.EOF { - return invalid - } - return nil -} - -func (c *apiContext) writeChangeAudit(ctx context.Context, tx *sql.Tx, status int) error { - c.Entry.Status = sql.NullInt64{Int64: int64(status), Valid: true} - if _, err := newAuditStore(tx, c.Server.tables).InsertAudit(ctx, *c.Entry); err != nil { - return err - } - c.auditDone = true - return nil -} diff --git a/type_webserver.go b/type_webserver.go index 30336d4..50940f3 100644 --- a/type_webserver.go +++ b/type_webserver.go @@ -5,9 +5,11 @@ package main import ( "context" + "crypto/rand" "database/sql" "errors" "fmt" + "io" "log/slog" "net" "net/http" @@ -51,6 +53,9 @@ func (a *app) runServer(ctx context.Context, cfg Config, log *slog.Logger) (err log.DebugContext(ctx, "database closed") }() ws := newWebServer(cfg, log, db, t, a.now) + if err := ws.checkAPIHandlers(); err != nil { + return err + } ln, err := a.listen(listenNetwork(cfg.HTTPAddr), cfg.ListenAddress()) if err != nil { return fmt.Errorf("listen: %w", err) @@ -108,6 +113,13 @@ type WebServer struct { newTicker func(time.Duration) ticker sessions expiredSessionDeleter shutdownTimeout time.Duration + store webStore + pages *pageRenderer + limiter *loginLimiter + random io.Reader + hashPassword func(string) (string, error) + verifyPassword passwordVerifier + apiHandlerSet map[string]apiHandler } func newWebServer(cfg Config, log *slog.Logger, db *sql.DB, tables tableNames, now func() time.Time) *WebServer { @@ -119,11 +131,21 @@ func newWebServer(cfg Config, log *slog.Logger, db *sql.DB, tables tableNames, n now: now, newTicker: newTimeTicker, shutdownTimeout: shutdownTimeout, + limiter: newLoginLimiter(now, loginLimiterMaxKeys), + random: rand.Reader, + hashPassword: hashPassword, + verifyPassword: verifyPassword, } if db != nil { s.pinger = db s.sessions = newSessionStore(db, tables) + s.store = newSQLWebStore(db, tables) } + pages, err := newPageRenderer() + if err != nil { + log.Error("page templates unavailable", "error", err) + } + s.pages = pages s.HTTPServer = &http.Server{ Handler: s.Handler(), ReadHeaderTimeout: readHeaderTimeout, diff --git a/type_webserver_test.go b/type_webserver_test.go index 32aba26..654120f 100644 --- a/type_webserver_test.go +++ b/type_webserver_test.go @@ -442,11 +442,11 @@ func TestConnectDatabase(t *testing.T) { func TestNewApp(t *testing.T) { a := newApp(func(string) (string, bool) { return "", false }, nil, io.Discard, io.Discard) - if a.prepareDB == nil || a.openDB == nil || a.listen == nil || a.hashPassword == nil || a.normalizeZone == nil || a.newUserBackend == nil || a.healthClient == nil { + if a.prepareDB == nil || a.openDB == nil || a.listen == nil || a.hashPassword == nil || a.normalizeZone == nil || a.newUserBackend == nil || a.newReadBackend == nil || a.healthClient == nil { t.Fatal("dependencies missing") } - if _, err := a.hashPassword("x"); err == nil { - t.Fatal("stub hash succeeded") + if h, err := a.hashPassword("correct horse battery"); err != nil || !strings.HasPrefix(h, "$argon2id$v=19$m=65536,t=3,p=2$") || !verifyPassword("correct horse battery", h) { + t.Fatal("real password hash not wired", h, err) } if z, err := a.normalizeZone("Example.ORG"); err != nil || z != "example.org." { t.Fatal(z, err) diff --git a/user_store.go b/user_store.go index 4619f73..ade31b9 100644 --- a/user_store.go +++ b/user_store.go @@ -6,7 +6,6 @@ package main import ( "context" "database/sql" - "encoding/json" "errors" "fmt" "time" @@ -205,26 +204,3 @@ func (s userStore) TouchLastLogin(ctx context.Context, id int64, now time.Time) return s.exec(ctx, "touch last login", "UPDATE {users} SET `last_login_at` = ? WHERE `id` = ?", dbTime(now), id) } - -type auditUserValue struct { - ID int64 `json:"id"` - Username string `json:"username"` - Role string `json:"role"` - CreatedAt string `json:"created_at"` - DeletedAt *string `json:"deleted_at"` -} - -const auditTimeLayout = "2006-01-02T15:04:05.000000Z" - -func formatAuditTime(t time.Time) string { - return t.UTC().Format(auditTimeLayout) -} - -func auditUserJSON(u userRow) ([]byte, error) { - v := auditUserValue{ID: u.ID, Username: u.Username, Role: u.Role, CreatedAt: formatAuditTime(u.CreatedAt)} - if u.DeletedAt.Valid { - d := formatAuditTime(u.DeletedAt.Time) - v.DeletedAt = &d - } - return json.Marshal(v) -} diff --git a/webfake_test.go b/webfake_test.go new file mode 100644 index 0000000..b935717 --- /dev/null +++ b/webfake_test.go @@ -0,0 +1,779 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright (C) 2026 Bryan Joshua Pedini + +package main + +import ( + "bytes" + "context" + "crypto/rand" + "database/sql" + "encoding/json" + "io" + "maps" + "net/http" + "net/http/httptest" + "net/netip" + "slices" + "strings" + "sync" + "testing" + "time" +) + +var webNow = time.Date(2026, 11, 18, 12, 0, 0, 0, time.UTC) + +const ( + testPassword = "secret-password" + testZone = "example.org." + otherZone = "other.org." +) + +type delegationKey struct { + zone string + userID int64 +} + +type fakeAuditInsert struct { + entry auditEntry + inTx bool +} + +type fakeWebState struct { + users []userRow + sessions map[string]sessionRow + delegations map[delegationKey]delegationRow + zones map[string]bool + audit []fakeAuditInsert +} + +func (s fakeWebState) clone() fakeWebState { + return fakeWebState{ + users: slices.Clone(s.users), + sessions: maps.Clone(s.sessions), + delegations: maps.Clone(s.delegations), + zones: maps.Clone(s.zones), + audit: slices.Clone(s.audit), + } +} + +type fakeWebStore struct { + mu sync.Mutex + state fakeWebState + failOn map[string]error + onLock func(state *fakeWebState) + calls []string + commits int + rollbacks int +} + +func newFakeWebStore() *fakeWebStore { + return &fakeWebStore{ + state: fakeWebState{ + sessions: map[string]sessionRow{}, + delegations: map[delegationKey]delegationRow{}, + zones: map[string]bool{}, + }, + failOn: map[string]error{}, + } +} + +type fakeWebView struct { + store *fakeWebStore + state *fakeWebState + inTx bool +} + +func (f *fakeWebStore) view() *fakeWebView { + return &fakeWebView{store: f, state: &f.state} +} + +func (v *fakeWebView) call(name string) error { + v.store.calls = append(v.store.calls, name) + return v.store.failOn[name] +} + +func (f *fakeWebStore) called(name string) int { + f.mu.Lock() + defer f.mu.Unlock() + n := 0 + for _, c := range f.calls { + if c == name { + n++ + } + } + return n +} + +func (f *fakeWebStore) addUser(username, role string) userRow { + f.mu.Lock() + defer f.mu.Unlock() + u := userRow{ + ID: int64(len(f.state.users) + 1), + Username: username, + Role: role, + PasswordHash: fakeHash(testPassword), + CreatedAt: webNow.Add(-48 * time.Hour), + UpdatedAt: webNow.Add(-48 * time.Hour), + } + f.state.users = append(f.state.users, u) + return u +} + +func (f *fakeWebStore) user(id int64) userRow { + f.mu.Lock() + defer f.mu.Unlock() + return f.state.users[id-1] +} + +func (f *fakeWebStore) setUser(u userRow) { + f.mu.Lock() + defer f.mu.Unlock() + f.state.users[u.ID-1] = u +} + +func (f *fakeWebStore) addZone(zone string) { + f.mu.Lock() + defer f.mu.Unlock() + f.state.zones[zone] = true +} + +func (f *fakeWebStore) delegate(zone string, u userRow) { + f.mu.Lock() + defer f.mu.Unlock() + f.state.delegations[delegationKey{zone, u.ID}] = delegationRow{Zone: zone, UserID: u.ID, Username: u.Username, CreatedAt: webNow.Add(-time.Hour), CreatedBy: 1} +} + +func (f *fakeWebStore) hasDelegation(zone string, userID int64) bool { + f.mu.Lock() + defer f.mu.Unlock() + _, ok := f.state.delegations[delegationKey{zone, userID}] + return ok +} + +func (f *fakeWebStore) addSession(u userRow, created, lastSeen time.Time) string { + token, hash, err := newSessionToken(rand.Reader) + if err != nil { + panic(err) + } + f.mu.Lock() + defer f.mu.Unlock() + f.state.sessions[string(hash)] = sessionRow{TokenHash: hash, UserID: u.ID, CreatedAt: created, LastSeenAt: lastSeen, ExpiresAt: created.Add(12 * time.Hour), Origin: "192.0.2.1", UserAgent: "test"} + return token +} + +func (f *fakeWebStore) sessionCount(userID int64) int { + f.mu.Lock() + defer f.mu.Unlock() + n := 0 + for _, s := range f.state.sessions { + if s.UserID == userID { + n++ + } + } + return n +} + +func (f *fakeWebStore) auditRows() []fakeAuditInsert { + f.mu.Lock() + defer f.mu.Unlock() + return slices.Clone(f.state.audit) +} + +func (f *fakeWebStore) auditCount() int { + f.mu.Lock() + defer f.mu.Unlock() + return len(f.state.audit) +} + +func (v *fakeWebView) InsertAudit(ctx context.Context, e auditEntry) (int64, error) { + if err := v.call("InsertAudit"); err != nil { + return 0, err + } + e.ID = int64(len(v.state.audit) + 1) + v.state.audit = append(v.state.audit, fakeAuditInsert{entry: e, inTx: v.inTx}) + return e.ID, nil +} + +func (v *fakeWebView) userByUsername(username string) (userRow, error) { + for _, u := range v.state.users { + if u.Username == username { + return u, nil + } + } + return userRow{}, errRowNotFound +} + +func (v *fakeWebView) SessionByTokenHash(ctx context.Context, tokenHash []byte) (sessionWithUser, error) { + if err := v.call("SessionByTokenHash"); err != nil { + return sessionWithUser{}, err + } + s, ok := v.state.sessions[string(tokenHash)] + if !ok { + return sessionWithUser{}, errRowNotFound + } + return sessionWithUser{Session: s, User: v.state.users[s.UserID-1]}, nil +} + +func (v *fakeWebView) TouchSession(ctx context.Context, tokenHash []byte, now time.Time) error { + if err := v.call("TouchSession"); err != nil { + return err + } + if s, ok := v.state.sessions[string(tokenHash)]; ok { + s.LastSeenAt = now + v.state.sessions[string(tokenHash)] = s + } + return nil +} + +func (v *fakeWebView) UserByUsername(ctx context.Context, username string) (userRow, error) { + if err := v.call("UserByUsername"); err != nil { + return userRow{}, err + } + return v.userByUsername(username) +} + +func (v *fakeWebView) HasActiveAdmin(ctx context.Context) (bool, error) { + if err := v.call("HasActiveAdmin"); err != nil { + return false, err + } + return slices.ContainsFunc(v.state.users, func(u userRow) bool { return u.Role == roleAdmin && !u.DeletedAt.Valid }), nil +} + +func (v *fakeWebView) HasDelegation(ctx context.Context, zone string, userID int64) (bool, error) { + if err := v.call("HasDelegation"); err != nil { + return false, err + } + _, ok := v.state.delegations[delegationKey{zone, userID}] + return ok, nil +} + +func (v *fakeWebView) ListUsers(ctx context.Context, includeDeleted bool) ([]userSummary, error) { + if err := v.call("ListUsers"); err != nil { + return nil, err + } + var out []userSummary + for _, u := range v.state.users { + if u.DeletedAt.Valid && !includeDeleted { + continue + } + var n int64 + for k := range v.state.delegations { + if k.userID == u.ID { + n++ + } + } + out = append(out, userSummary{userRow: u, Zones: n}) + } + slices.SortFunc(out, func(a, b userSummary) int { return strings.Compare(a.Username, b.Username) }) + return out, nil +} + +func (v *fakeWebView) UserZones(ctx context.Context, userID int64) ([]userZone, error) { + if err := v.call("UserZones"); err != nil { + return nil, err + } + var out []userZone + for k, d := range v.state.delegations { + if k.userID == userID { + out = append(out, userZone{Zone: k.zone, CreatedAt: d.CreatedAt, ZoneExists: v.state.zones[k.zone]}) + } + } + slices.SortFunc(out, func(a, b userZone) int { return strings.Compare(a.Zone, b.Zone) }) + return out, nil +} + +func (v *fakeWebView) ZoneUsers(ctx context.Context, zone string) ([]userRow, error) { + if err := v.call("ZoneUsers"); err != nil { + return nil, err + } + var out []userRow + for k := range v.state.delegations { + u := v.state.users[k.userID-1] + if k.zone == zone && u.Role == roleUser && !u.DeletedAt.Valid { + out = append(out, u) + } + } + slices.SortFunc(out, func(a, b userRow) int { return strings.Compare(a.Username, b.Username) }) + return out, nil +} + +func (v *fakeWebView) ZoneExists(ctx context.Context, zone string) (bool, error) { + if err := v.call("ZoneExists"); err != nil { + return false, err + } + return v.state.zones[zone], nil +} + +func (v *fakeWebView) ListAudit(ctx context.Context, f auditFilter) ([]auditRow, error) { + if err := v.call("ListAudit"); err != nil { + return nil, err + } + var out []auditRow + for i := len(v.state.audit) - 1; i >= 0 && len(out) < f.Limit; i-- { + e := v.state.audit[i].entry + if f.BeforeID > 0 && e.ID >= f.BeforeID { + continue + } + if f.Operation != "" && e.Operation != f.Operation { + continue + } + if f.RestrictToUserID.Valid { + _, delegated := v.state.delegations[delegationKey{e.Zone.String, f.RestrictToUserID.Int64}] + if !(e.UserID.Valid && e.UserID.Int64 == f.RestrictToUserID.Int64) && !(e.Zone.Valid && delegated) { + continue + } + } + r := auditRow{auditEntry: e} + if e.TargetUserID.Valid { + r.TargetUsername = sql.NullString{String: v.state.users[e.TargetUserID.Int64-1].Username, Valid: true} + } + out = append(out, r) + } + return out, nil +} + +func (f *fakeWebStore) InTx(ctx context.Context, fn func(tx webTx) error) error { + f.mu.Lock() + defer f.mu.Unlock() + f.calls = append(f.calls, "InTx") + if err := f.failOn["InTx"]; err != nil { + return err + } + working := f.state.clone() + if err := fn(&fakeWebView{store: f, state: &working, inTx: true}); err != nil { + f.rollbacks++ + return err + } + if err := f.failOn["Commit"]; err != nil { + f.rollbacks++ + return err + } + f.state = working + f.commits++ + return nil +} + +func (f *fakeWebStore) InsertAudit(ctx context.Context, e auditEntry) (int64, error) { + f.mu.Lock() + defer f.mu.Unlock() + return f.view().InsertAudit(ctx, e) +} + +func (f *fakeWebStore) SessionByTokenHash(ctx context.Context, h []byte) (sessionWithUser, error) { + f.mu.Lock() + defer f.mu.Unlock() + return f.view().SessionByTokenHash(ctx, h) +} + +func (f *fakeWebStore) TouchSession(ctx context.Context, h []byte, now time.Time) error { + f.mu.Lock() + defer f.mu.Unlock() + return f.view().TouchSession(ctx, h, now) +} + +func (f *fakeWebStore) UserByUsername(ctx context.Context, username string) (userRow, error) { + f.mu.Lock() + defer f.mu.Unlock() + return f.view().UserByUsername(ctx, username) +} + +func (f *fakeWebStore) HasActiveAdmin(ctx context.Context) (bool, error) { + f.mu.Lock() + defer f.mu.Unlock() + return f.view().HasActiveAdmin(ctx) +} + +func (f *fakeWebStore) HasDelegation(ctx context.Context, zone string, userID int64) (bool, error) { + f.mu.Lock() + defer f.mu.Unlock() + return f.view().HasDelegation(ctx, zone, userID) +} + +func (f *fakeWebStore) ListUsers(ctx context.Context, includeDeleted bool) ([]userSummary, error) { + f.mu.Lock() + defer f.mu.Unlock() + return f.view().ListUsers(ctx, includeDeleted) +} + +func (f *fakeWebStore) UserZones(ctx context.Context, userID int64) ([]userZone, error) { + f.mu.Lock() + defer f.mu.Unlock() + return f.view().UserZones(ctx, userID) +} + +func (f *fakeWebStore) ZoneUsers(ctx context.Context, zone string) ([]userRow, error) { + f.mu.Lock() + defer f.mu.Unlock() + return f.view().ZoneUsers(ctx, zone) +} + +func (f *fakeWebStore) ZoneExists(ctx context.Context, zone string) (bool, error) { + f.mu.Lock() + defer f.mu.Unlock() + return f.view().ZoneExists(ctx, zone) +} + +func (f *fakeWebStore) ListAudit(ctx context.Context, filter auditFilter) ([]auditRow, error) { + f.mu.Lock() + defer f.mu.Unlock() + return f.view().ListAudit(ctx, filter) +} + +func (v *fakeWebView) CreateSession(ctx context.Context, row sessionRow) error { + if err := v.call("CreateSession"); err != nil { + return err + } + v.state.sessions[string(row.TokenHash)] = row + return nil +} + +func (v *fakeWebView) DeleteSession(ctx context.Context, tokenHash []byte) (bool, error) { + if err := v.call("DeleteSession"); err != nil { + return false, err + } + _, ok := v.state.sessions[string(tokenHash)] + delete(v.state.sessions, string(tokenHash)) + return ok, nil +} + +func (v *fakeWebView) deleteSessions(userID int64, keep []byte) int64 { + var n int64 + for k, s := range v.state.sessions { + if s.UserID == userID && k != string(keep) { + delete(v.state.sessions, k) + n++ + } + } + return n +} + +func (v *fakeWebView) DeleteUserSessions(ctx context.Context, userID int64) (int64, error) { + if err := v.call("DeleteUserSessions"); err != nil { + return 0, err + } + return v.deleteSessions(userID, nil), nil +} + +func (v *fakeWebView) DeleteUserSessionsExcept(ctx context.Context, userID int64, keep []byte) (int64, error) { + if err := v.call("DeleteUserSessionsExcept"); err != nil { + return 0, err + } + return v.deleteSessions(userID, keep), nil +} + +func (v *fakeWebView) TouchLastLogin(ctx context.Context, id int64, now time.Time) error { + if err := v.call("TouchLastLogin"); err != nil { + return err + } + v.state.users[id-1].LastLoginAt = sql.NullTime{Time: now, Valid: true} + return nil +} + +func (v *fakeWebView) CreateUser(ctx context.Context, username, role, passwordHash string, now time.Time) (userRow, error) { + if err := v.call("CreateUser"); err != nil { + return userRow{}, err + } + if _, err := v.userByUsername(username); err == nil { + return userRow{}, errUsernameTaken + } + u := userRow{ID: int64(len(v.state.users) + 1), Username: username, Role: role, PasswordHash: passwordHash, CreatedAt: dbTime(now), UpdatedAt: dbTime(now)} + v.state.users = append(v.state.users, u) + return u, nil +} + +func (v *fakeWebView) UserByIDForUpdate(ctx context.Context, id int64) (userRow, error) { + if err := v.call("UserByIDForUpdate"); err != nil { + return userRow{}, err + } + if id < 1 || int(id) > len(v.state.users) { + return userRow{}, errRowNotFound + } + return v.state.users[id-1], nil +} + +func (v *fakeWebView) UserByUsernameForUpdate(ctx context.Context, username string) (userRow, error) { + if err := v.call("UserByUsernameForUpdate"); err != nil { + return userRow{}, err + } + return v.userByUsername(username) +} + +func (v *fakeWebView) LockActiveAdmins(ctx context.Context) ([]userRow, error) { + if err := v.call("LockActiveAdmins"); err != nil { + return nil, err + } + if v.store.onLock != nil { + v.store.onLock(v.state) + } + var out []userRow + for _, u := range v.state.users { + if u.Role == roleAdmin && !u.DeletedAt.Valid { + out = append(out, u) + } + } + return out, nil +} + +func (v *fakeWebView) SetRole(ctx context.Context, id int64, role string, now time.Time) error { + if err := v.call("SetRole"); err != nil { + return err + } + v.state.users[id-1].Role = role + v.state.users[id-1].UpdatedAt = now + return nil +} + +func (v *fakeWebView) SetPassword(ctx context.Context, id int64, hash string, now time.Time) error { + if err := v.call("SetPassword"); err != nil { + return err + } + v.state.users[id-1].PasswordHash = hash + v.state.users[id-1].UpdatedAt = now + return nil +} + +func (v *fakeWebView) MarkDeleted(ctx context.Context, id int64, now time.Time) error { + if err := v.call("MarkDeleted"); err != nil { + return err + } + v.state.users[id-1].DeletedAt = sql.NullTime{Time: now, Valid: true} + return nil +} + +func (v *fakeWebView) GrantDelegation(ctx context.Context, zone string, userID, createdBy int64, now time.Time) (bool, error) { + if err := v.call("GrantDelegation"); err != nil { + return false, err + } + k := delegationKey{zone, userID} + if _, ok := v.state.delegations[k]; ok { + return false, nil + } + v.state.delegations[k] = delegationRow{Zone: zone, UserID: userID, Username: v.state.users[userID-1].Username, CreatedAt: now, CreatedBy: createdBy} + return true, nil +} + +func (v *fakeWebView) RevokeDelegation(ctx context.Context, zone string, userID int64) (bool, error) { + if err := v.call("RevokeDelegation"); err != nil { + return false, err + } + k := delegationKey{zone, userID} + _, ok := v.state.delegations[k] + delete(v.state.delegations, k) + return ok, nil +} + +func fakeHash(password string) string { + return "$fake$" + password +} + +func fakeVerify(password, encoded string) bool { + return encoded == fakeHash(password) +} + +type testClock struct { + mu sync.Mutex + now time.Time +} + +func (c *testClock) Now() time.Time { + c.mu.Lock() + defer c.mu.Unlock() + return c.now +} + +func (c *testClock) advance(d time.Duration) { + c.mu.Lock() + defer c.mu.Unlock() + c.now = c.now.Add(d) +} + +type lockedBuffer struct { + mu sync.Mutex + buf bytes.Buffer +} + +func (b *lockedBuffer) Write(p []byte) (int, error) { + b.mu.Lock() + defer b.mu.Unlock() + return b.buf.Write(p) +} + +func (b *lockedBuffer) String() string { + b.mu.Lock() + defer b.mu.Unlock() + return b.buf.String() +} + +type webHarness struct { + t *testing.T + s *WebServer + store *fakeWebStore + clock *testClock + logs *lockedBuffer + handler http.Handler + users map[string]userRow +} + +type webOption func(cfg *Config) + +func newWebHarness(t *testing.T, opts ...webOption) *webHarness { + t.Helper() + cfg := Config{AppName: "Test DNS", CookieSecure: true, SessionIdleTimeout: time.Hour, SessionMaxAge: 12 * time.Hour, LogLevel: LevelTrace} + for _, o := range opts { + o(&cfg) + } + h := &webHarness{t: t, store: newFakeWebStore(), clock: &testClock{now: webNow}, logs: &lockedBuffer{}, users: map[string]userRow{}} + h.s = newWebServer(cfg, newLogger(h.logs, LevelTrace), nil, tableNames{}, h.clock.Now) + h.s.store = h.store + h.s.hashPassword = func(p string) (string, error) { return fakeHash(p), nil } + h.s.verifyPassword = fakeVerify + h.handler = h.s.Handler() + return h +} + +func (h *webHarness) withHandlers(handlers map[string]apiHandler) { + h.s.apiHandlerSet = handlers + 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 + return u +} + +func (h *webHarness) login(u userRow) string { + return h.store.addSession(u, h.clock.Now(), h.clock.Now()) +} + +type webRequest struct { + method string + path string + token string + body string + ctype string + header map[string]string + remote string + rawBody io.Reader +} + +type webResult struct { + status int + header http.Header + body string + audit []fakeAuditInsert +} + +func (r webResult) json(t *testing.T) map[string]any { + t.Helper() + var m map[string]any + if err := json.Unmarshal([]byte(r.body), &m); err != nil { + t.Fatalf("invalid JSON %q: %v", r.body, err) + } + return m +} + +func (h *webHarness) do(req webRequest) webResult { + h.t.Helper() + var body io.Reader = strings.NewReader(req.body) + if req.rawBody != nil { + body = req.rawBody + } + r := httptest.NewRequest(req.method, req.path, body) + if req.body == "" && req.rawBody == nil { + r = httptest.NewRequest(req.method, req.path, nil) + } + r.RemoteAddr = "192.0.2.10:40000" + if req.remote != "" { + r.RemoteAddr = req.remote + } + if req.body != "" { + ct := req.ctype + if ct == "" { + ct = "application/json" + } + r.Header.Set("Content-Type", ct) + } + if req.token != "" { + r.AddCookie(&http.Cookie{Name: sessionCookieName, Value: req.token}) + } + for k, v := range req.header { + r.Header.Set(k, v) + } + before := h.store.auditCount() + w := httptest.NewRecorder() + h.handler.ServeHTTP(w, r) + rows := h.store.auditRows() + return webResult{status: w.Code, header: w.Header(), body: w.Body.String(), audit: rows[before:]} +} + +func (h *webHarness) api(method, path, token, body string) webResult { + h.t.Helper() + return h.do(webRequest{method: method, path: apiPrefix + path, token: token, body: body}) +} + +func trustProxies(prefixes ...string) webOption { + return func(cfg *Config) { + for _, p := range prefixes { + cfg.TrustedProxies = append(cfg.TrustedProxies, netip.MustParsePrefix(p)) + } + } +} + +func expectOneAudit(t *testing.T, res webResult, operation string, status int) auditEntry { + t.Helper() + if len(res.audit) != 1 { + t.Fatalf("%s: %d audit rows, want 1 (status %d body %s)", operation, len(res.audit), res.status, res.body) + } + e := res.audit[0].entry + if e.Operation != operation || !e.Status.Valid || e.Status.Int64 != int64(status) { + t.Fatalf("audit row %+v, want operation %s status %d", e, operation, status) + } + if status >= 400 { + var body map[string]any + _ = json.Unmarshal([]byte(res.body), &body) + msg, _ := body["error"].(string) + if !e.Error.Valid || (strings.HasPrefix(res.body, "{") && res.status == status && e.Error.String != msg) { + t.Fatalf("audit error %v, body %s", e.Error, res.body) + } + } else if e.Error.Valid { + t.Fatalf("audit error set on success: %v", e.Error) + } + return e +}