diff --git a/README.md b/README.md index f94064a..a687cfd 100644 --- a/README.md +++ b/README.md @@ -1 +1,6 @@ # coredns-web-ui + +## Audit + +An authenticated API request with an unknown path or an unsupported method is +recorded as an `api_unknown` read, with status `404` or `405` respectively. diff --git a/audit.go b/audit.go index b426551..5bb447c 100644 --- a/audit.go +++ b/audit.go @@ -57,6 +57,7 @@ const ( opUserPassword = "user_password" opUserDelete = "user_delete" opAuditRead = "audit_read" + opAPIUnknown = "api_unknown" ) const ( @@ -68,6 +69,7 @@ const ( apiPrefix = "/api/v1" auditDefaultLimit = 50 auditMaxLimit = 200 + auditMaxBeforeID = 1<<53 - 1 ) type auditOperation struct { @@ -105,6 +107,7 @@ var auditOperations = []auditOperation{ {opUserPassword, auditKindChange}, {opUserDelete, auditKindChange}, {opAuditRead, auditKindRead}, + {opAPIUnknown, auditKindRead}, } var auditChangeOperations = operationsOfKind(auditKindChange) diff --git a/audit_failure_test.go b/audit_failure_test.go new file mode 100644 index 0000000..649eb17 --- /dev/null +++ b/audit_failure_test.go @@ -0,0 +1,200 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright (C) 2026 Bryan Joshua Pedini + +package main + +import ( + "database/sql/driver" + "encoding/json" + "errors" + "net/http" + "strings" + "testing" +) + +func expectInternalErrorRow(t *testing.T, res webResult, operation string) auditEntry { + t.Helper() + e := expectOneAudit(t, res, operation, http.StatusInternalServerError) + if res.audit[0].inTx || e.Error.String != msgInternalError || e.Before != nil || e.After != nil { + t.Fatalf("%s: %+v", operation, res.audit[0]) + } + return e +} + +func TestAPIAuditFailureOnReadsAndRefusals(t *testing.T) { + h := newWebHarness(t) + admin := h.user("admin", roleAdmin) + alice := h.user("alice", roleUser) + at, ut := h.login(admin), h.login(alice) + h.store.failOn["InsertAudit"] = errors.New("audit down") + h.store.failTimes["InsertAudit"] = 1 + res := h.api("GET", "/account", at, "") + expectError(t, res, 500, `{"error":"internal error"}`) + expectInternalErrorRow(t, res, opAccountRead) + + h.store.failTimes["InsertAudit"] = 1 + res = h.api("PUT", "/zones/example.org./users/bob", ut, "") + expectError(t, res, 500, `{"error":"internal error"}`) + if e := expectInternalErrorRow(t, res, opDelegationGrant); e.Zone.String != testZone { + t.Fatalf("%+v", e) + } + + delete(h.store.failTimes, "InsertAudit") + res = h.api("GET", "/account", at, "") + expectError(t, res, 500, `{"error":"internal error"}`) + if len(res.audit) != 0 || strings.Contains(res.body, "admin") { + t.Fatal("persistent failure") + } + if !strings.Contains(h.logs.String(), "audit insert of the internal error failed") { + t.Fatal("second failure not logged") + } +} + +func TestAPIAuditWriteFailureIsAlwaysInternal(t *testing.T) { + h, token := usersHarness(t) + bob := h.users["bob"] + for _, cause := range []error{driver.ErrBadConn, errDatabase, errors.New("constraint")} { + h.store.failOn["InsertAudit"] = cause + h.store.failTimes["InsertAudit"] = 1 + res := h.api("PUT", "/users/bob/role", token, `{"role":"admin"}`) + expectError(t, res, 500, `{"error":"internal error"}`) + if e := expectInternalErrorRow(t, res, opUserRole); e.TargetUserID.Int64 != bob.ID { + t.Fatalf("%v: %+v", cause, e) + } + if h.stored("bob").Role != roleUser { + t.Fatalf("%v: change kept without its audit row", cause) + } + } + if status, msg := failureStatus(&auditWriteError{err: driver.ErrBadConn}); status != 500 || msg != msgInternalError { + t.Fatal(status, msg) + } + if status, _ := failureStatus(driver.ErrBadConn); status != 503 { + t.Fatal("operation connection errors must stay 503", status) + } + delete(h.store.failTimes, "InsertAudit") + calls := h.store.called("InsertAudit") + res := h.api("PUT", "/users/bob/role", token, `{"role":"admin"}`) + expectError(t, res, 500, `{"error":"internal error"}`) + if len(res.audit) != 0 || h.store.called("InsertAudit")-calls != 2 || h.stored("bob").Role != roleUser { + t.Fatal("transactional audit failure should attempt exactly one fallback") + } +} + +func TestAPIUserCreateRollbackClearsTheTarget(t *testing.T) { + h, token := usersHarness(t) + h.store.failOn["InsertAudit"] = errors.New("audit down") + h.store.failTimes["InsertAudit"] = 1 + res := h.api("POST", "/users", token, `{"username":"newbie","role":"user","password":"long-enough-pw"}`) + expectError(t, res, 500, `{"error":"internal error"}`) + if e := expectInternalErrorRow(t, res, opUserCreate); e.TargetUserID.Valid { + t.Fatalf("rolled back insert kept as target: %+v", e) + } + if _, err := h.store.UserByUsername(t.Context(), "newbie"); !errors.Is(err, errRowNotFound) { + t.Fatal("user kept") + } + h.store.failOn["CreateUser"] = errors.New("x") + res = h.api("POST", "/users", token, `{"username":"newbie","role":"user","password":"long-enough-pw"}`) + if e := expectNoChange(t, res, opUserCreate, 500); e.TargetUserID.Valid { + t.Fatal(e) + } +} + +func TestLoginAuditFailures(t *testing.T) { + h := newWebHarness(t) + alice := h.user("alice", roleUser) + h.store.failOn["InsertAudit"] = errors.New("audit down") + h.store.failTimes["InsertAudit"] = 1 + res := h.postLogin(loginForm("alice", "wrong-password", ""), "") + if res.status != 500 || !strings.Contains(res.body, msgLoginUnavailable) { + t.Fatal(res.status) + } + if e := expectInternalErrorRow(t, res, opLogin); e.UserID.Int64 != alice.ID { + t.Fatal(e) + } + + h.store.failTimes["InsertAudit"] = 1 + h.store.failOn["UserByUsername"] = errDatabase + res = h.postLogin(loginForm("alice", testPassword, ""), "") + if res.status != 500 { + t.Fatal("unavailable answered after the audit failed", res.status) + } + expectInternalErrorRow(t, res, opLogin) + delete(h.store.failOn, "UserByUsername") + + h.store.failOn["InsertAudit"] = driver.ErrBadConn + h.store.failTimes["InsertAudit"] = 1 + res = h.postLogin(loginForm("alice", testPassword, ""), "") + if res.status != 500 || len(res.header.Values("Set-Cookie")) != 0 || h.store.sessionCount(alice.ID) != 0 { + t.Fatal("transactional audit failure", res.status) + } + expectInternalErrorRow(t, res, opLogin) + delete(h.store.failTimes, "InsertAudit") + calls := h.store.called("InsertAudit") + res = h.postLogin(loginForm("alice", testPassword, ""), "") + if res.status != 500 || len(res.audit) != 0 || h.store.called("InsertAudit")-calls != 2 { + t.Fatal("transactional login audit failure should attempt exactly one fallback") + } + + for range 5 { + h.s.limiter.fail("alice", "192.0.2.10") + } + h.store.failOn["InsertAudit"] = errors.New("audit down") + h.store.failTimes["InsertAudit"] = 1 + res = h.postLogin(loginForm("alice", testPassword, ""), "") + if res.status != 500 || !strings.Contains(res.body, msgLoginUnavailable) { + t.Fatal("rate limited", res.status) + } + expectInternalErrorRow(t, res, opLogin) + delete(h.store.failTimes, "InsertAudit") + if res := h.postLogin(loginForm("alice", testPassword, ""), ""); res.status != 500 || len(res.audit) != 0 { + t.Fatal("persistent failure", res.status) + } + delete(h.store.failOn, "InsertAudit") + + token := h.login(alice) + h.store.failOn["InsertAudit"] = driver.ErrBadConn + h.store.failTimes["InsertAudit"] = 1 + res = h.do(webRequest{method: "POST", path: "/logout", token: token}) + if res.status != 500 || h.store.sessionCount(alice.ID) != 1 { + t.Fatal("logout", res.status) + } + expectInternalErrorRow(t, res, opLogout) +} + +func TestAuditReadHidesRefusedTargets(t *testing.T) { + h := newWebHarness(t) + admin := h.user("admin", roleAdmin) + alice := h.user("alice", roleUser) + h.user("bob", roleUser) + at, ut := h.login(admin), h.login(alice) + if res := h.api("GET", "/users/bob", ut, ""); res.status != 403 { + t.Fatal(res.status) + } + if res := h.api("PUT", "/account/password", ut, `{"current":"secret-password","password":"own-new-password"}`); res.status != 204 { + t.Fatal(res.status) + } + targets := func(token string) map[string]*string { + var body struct { + Entries []struct { + Operation string `json:"operation"` + TargetUser *string `json:"target_user"` + } `json:"entries"` + } + res := h.api("GET", "/audit", token, "") + if err := json.Unmarshal([]byte(res.body), &body); err != nil { + t.Fatal(err) + } + out := map[string]*string{} + for _, e := range body.Entries { + out[e.Operation] = e.TargetUser + } + return out + } + user, adm := targets(ut), targets(at) + if user[opUserRead] != nil || user[opPasswordChange] == nil || *user[opPasswordChange] != "alice" { + t.Fatalf("user view %v", user) + } + if adm[opUserRead] == nil || *adm[opUserRead] != "bob" { + t.Fatalf("admin view %v", adm) + } +} diff --git a/audit_store.go b/audit_store.go index 4ef2303..974eca8 100644 --- a/audit_store.go +++ b/audit_store.go @@ -70,6 +70,7 @@ func nullJSON(b []byte) any { } func (s auditStore) InsertAudit(ctx context.Context, e auditEntry) (int64, error) { + defer traceStore(ctx, "auditStore.InsertAudit")() if len(e.Operation) > auditMaxOperationLen { return 0, errors.New("insert audit: operation name too long") } @@ -77,7 +78,7 @@ func (s auditStore) InsertAudit(ctx context.Context, e auditEntry) (int64, error if errMsg.Valid { errMsg.String = cropRunes(errMsg.String, auditMaxErrorRunes) } - res, err := s.q.ExecContext(ctx, + res, err := s.q.ExecContext(privateSQLArgs(ctx, 7, 11, 12), s.t.sql("INSERT INTO {audit} (`time`, `user_id`, `actor`, `origin`, `operation`, `status`, `error`, `zone`, `record_id`, `target_user_id`, `before_value`, `after_value`) "+ "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"), dbTime(e.Time), e.UserID, cropRunes(e.Actor, auditMaxActorRunes), cropRunes(e.Origin, auditMaxOriginRunes), e.Operation, @@ -150,6 +151,7 @@ func auditFilterSQL(f auditFilter) (string, []any, error) { } func (s auditStore) ListAudit(ctx context.Context, f auditFilter) ([]auditRow, error) { + defer traceStore(ctx, "auditStore.ListAudit")() if f.Limit < 1 || f.Limit > auditMaxListLimit { return nil, errors.New("list audit: invalid limit") } @@ -161,7 +163,8 @@ func (s auditStore) ListAudit(ctx context.Context, f auditFilter) ([]auditRow, e return s.queryAudit(ctx, s.t.sql(auditSelect+where+"ORDER BY a.`id` DESC LIMIT ?"), args...) } -func (s auditStore) LatestAudit(ctx context.Context, n int) ([]auditRow, error) { +func (s auditStore) LatestAudit(ctx context.Context, n int64) ([]auditRow, error) { + defer traceStore(ctx, "auditStore.LatestAudit")() if n < 1 { return nil, errors.New("latest audit: invalid count") } diff --git a/audit_test.go b/audit_test.go index 0c727e4..47f38c0 100644 --- a/audit_test.go +++ b/audit_test.go @@ -67,7 +67,7 @@ func TestRouteTableMatchesSpec(t *testing.T) { } 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"} + 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", "api_unknown"} 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) diff --git a/cli.go b/cli.go index fcbd533..d00fb51 100644 --- a/cli.go +++ b/cli.go @@ -37,7 +37,6 @@ const usageText = `usage: const ( healthcheckTimeout = 3 * time.Second defaultAuditRows = 20 - maxAuditRows = 1000000 maxPasswordLineBytes = 4096 cliTimeLayout = "2006-01-02T15:04:05Z" ) @@ -108,6 +107,7 @@ func (a *app) runDatabaseCommand(ctx context.Context, args []string) (err error) return err } log := newLogger(a.stderr, cfg.LogLevel) + ctx = withTraceLogger(ctx, log) defer traceFunc(ctx, log, "app.runDatabaseCommand")() var cmd cliCommand switch args[0] { @@ -350,7 +350,7 @@ func (a *app) parseAuditCommand(args []string) (cliCommand, error) { if len(args) > 1 { return cliCommand{}, usageError("audit takes at most one count") } - n := defaultAuditRows + n := int64(defaultAuditRows) if len(args) == 1 { v, err := parseAuditCount(args[0]) if err != nil { @@ -363,12 +363,12 @@ func (a *app) parseAuditCommand(args []string) (cliCommand, error) { }}, nil } -func parseAuditCount(s string) (int, error) { - if s == "" || len(s) > 7 || strings.Trim(s, "0123456789") != "" { +func parseAuditCount(s string) (int64, error) { + if s == "" || strings.Trim(s, "0123456789") != "" { return 0, errors.New("invalid count") } - n, err := strconv.Atoi(s) - if err != nil || n < 1 || n > maxAuditRows { + n, err := strconv.ParseInt(s, 10, 64) + if err != nil || n < 1 { return 0, errors.New("invalid count") } return n, nil @@ -377,7 +377,7 @@ func parseAuditCount(s string) (int, error) { 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) + LatestAudit(ctx context.Context, n int64) ([]auditRow, error) } type sqlReadBackend struct { @@ -454,7 +454,7 @@ func (a *app) checkZones(ctx context.Context, b cliReadBackend, zone string) err return nil } -func (a *app) runAudit(ctx context.Context, db *sql.DB, t tableNames, log *slog.Logger, n int) error { +func (a *app) runAudit(ctx context.Context, db *sql.DB, t tableNames, log *slog.Logger, n int64) error { return a.printAudit(ctx, a.newReadBackend(db, t), n) } @@ -489,7 +489,7 @@ func auditRows(entries []auditRow) [][]string { return rows } -func (a *app) printAudit(ctx context.Context, b cliReadBackend, n int) error { +func (a *app) printAudit(ctx context.Context, b cliReadBackend, n int64) error { entries, err := b.LatestAudit(ctx, n) if err != nil { return err @@ -700,7 +700,7 @@ func (a *app) userRole(ctx context.Context, b cliUserBackend, log *slog.Logger, if u.Role == role { return nil } - if u.Role == roleAdmin && len(admins) <= 1 { + if leavesNoActiveAdmin(u, admins) { return errLastActiveAdmin } if err := tx.SetRole(ctx, u.ID, role, now); err != nil { @@ -732,7 +732,7 @@ func (a *app) userDelete(ctx context.Context, b cliUserBackend, log *slog.Logger if err != nil { return err } - if u.Role == roleAdmin && len(admins) <= 1 { + if leavesNoActiveAdmin(u, admins) { return errLastActiveAdmin } if err := tx.MarkDeleted(ctx, u.ID, now); err != nil { diff --git a/cli_test.go b/cli_test.go index d0c184a..f183daa 100644 --- a/cli_test.go +++ b/cli_test.go @@ -303,7 +303,7 @@ func TestUsageErrors(t *testing.T) { {[]string{"audit", "+5"}, "invalid audit count"}, {[]string{"audit", "5x"}, "invalid audit count"}, {[]string{"audit", "secretarg"}, "invalid audit count"}, - {[]string{"audit", "10000000"}, "invalid audit count"}, + {[]string{"audit", "9223372036854775808"}, "invalid audit count"}, } for _, c := range cases { h := newCLIHarness(t, "password-on-stdin\n") @@ -670,7 +670,7 @@ type fakeReadBackend struct { rows map[string][]recordRow audit []auditRow failOn string - auditN int + auditN int64 rowCalls []string } @@ -689,7 +689,7 @@ func (f *fakeReadBackend) ZoneRows(ctx context.Context, zone string) ([]recordRo return f.rows[zone], nil } -func (f *fakeReadBackend) LatestAudit(ctx context.Context, n int) ([]auditRow, error) { +func (f *fakeReadBackend) LatestAudit(ctx context.Context, n int64) ([]auditRow, error) { f.auditN = n if f.failOn == "LatestAudit" { return nil, errFakeStore @@ -815,7 +815,7 @@ func TestAuditCommand(t *testing.T) { 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} { + for args, n := range map[string]int64{"5": 5, "0001": 1, "1000000": 1000000, "1000001": 1000001, "9223372036854775807": 9223372036854775807} { b = &fakeReadBackend{} h = newCLIHarness(t, "") h.withReadBackend(b) @@ -828,7 +828,7 @@ func TestAuditCommand(t *testing.T) { 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"}} { + for _, args := range [][]string{{"audit", "0"}, {"audit", "-1"}, {"audit", "x"}, {"audit", "9223372036854775808"}, {"audit", "99999999999999999999"}, {"audit", "1", "2"}, {"audit", "+5"}, {"audit", "1e3"}, {"audit", " 5"}} { h = newCLIHarness(t, "") if code := h.run(args...); code != 2 || h.prepared != 0 { t.Fatalf("%v: %d", args, code) diff --git a/database.go b/database.go index 5ac86c0..56c18aa 100644 --- a/database.go +++ b/database.go @@ -7,11 +7,14 @@ import ( "context" "crypto/sha256" "database/sql" + "database/sql/driver" "encoding/hex" "errors" "fmt" "log/slog" "math" + "regexp" + "runtime" "strings" "time" @@ -130,7 +133,11 @@ func openDatabase(cfg Config, log *slog.Logger) (*sql.DB, error) { if err != nil { return nil, fmt.Errorf("%w: invalid connection settings", errDatabase) } - db := sql.OpenDB(connector) + var c driver.Connector = connector + if log.Enabled(context.Background(), LevelTrace) { + c = traceConnector{Connector: connector, log: log} + } + db := sql.OpenDB(c) db.SetMaxOpenConns(dbMaxOpenConns) db.SetMaxIdleConns(dbMaxIdleConns) db.SetConnMaxLifetime(dbConnMaxLifetime) @@ -196,40 +203,62 @@ func pingDatabase(ctx context.Context, p pinger, b backoff, log *slog.Logger) er } } -type contractColumn struct { - name string - types []string +type columnInfo struct { + dataType string + columnType string + maxLength int64 } -var integerTypes = []string{"tinyint", "smallint", "mediumint", "int", "bigint"} +type contractColumn struct { + name string + requirement string + accepts func(columnInfo) bool +} -var textTypes = []string{"char", "varchar", "tinytext", "text", "mediumtext", "longtext"} +func typeIn(types ...string) func(columnInfo) bool { + return func(c columnInfo) bool { + for _, t := range types { + if c.dataType == t { + return true + } + } + return false + } +} + +func varcharOrText(minLength int64) func(columnInfo) bool { + text := typeIn("text", "mediumtext", "longtext") + return func(c columnInfo) bool { + return (c.dataType == "varchar" && c.maxLength >= minLength) || text(c) + } +} var recordsContract = []contractColumn{ - {"id", integerTypes}, - {"zone", textTypes}, - {"name", textTypes}, - {"ttl", integerTypes}, - {"content", append(append([]string{}, textTypes...), "json")}, - {"record_type", textTypes}, + {"id", "INT or INT UNSIGNED", typeIn("int")}, + {"zone", "VARCHAR(255) or longer, TEXT, MEDIUMTEXT or LONGTEXT", varcharOrText(255)}, + {"name", "VARCHAR(255) or longer, TEXT, MEDIUMTEXT or LONGTEXT", varcharOrText(255)}, + {"ttl", "INT or BIGINT", typeIn("int", "bigint")}, + {"content", "TEXT, MEDIUMTEXT, LONGTEXT or JSON", typeIn("text", "mediumtext", "longtext", "json")}, + {"record_type", "VARCHAR(9) or longer, TEXT, MEDIUMTEXT or LONGTEXT", varcharOrText(9)}, } func verifyRecordsContract(ctx context.Context, q dbtx, t tableNames, log *slog.Logger) error { table := t.prefix + "records" rows, err := q.QueryContext(ctx, - "SELECT COLUMN_NAME, DATA_TYPE FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ?", + "SELECT COLUMN_NAME, DATA_TYPE, COLUMN_TYPE, CHARACTER_MAXIMUM_LENGTH FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ?", table) if err != nil { return fmt.Errorf("read records table columns: %w", err) } defer rows.Close() - columns := map[string]string{} + columns := map[string]columnInfo{} for rows.Next() { - var name, dataType string - if err := rows.Scan(&name, &dataType); err != nil { + var name, dataType, columnType string + var maxLength sql.NullInt64 + if err := rows.Scan(&name, &dataType, &columnType, &maxLength); err != nil { return fmt.Errorf("read records table columns: %w", err) } - columns[strings.ToLower(name)] = strings.ToLower(dataType) + columns[strings.ToLower(name)] = columnInfo{dataType: strings.ToLower(dataType), columnType: strings.ToLower(columnType), maxLength: maxLength.Int64} } if err := rows.Err(); err != nil { return fmt.Errorf("read records table columns: %w", err) @@ -241,24 +270,21 @@ func verifyRecordsContract(ctx context.Context, q dbtx, t tableNames, log *slog. return nil } -func checkRecordsColumns(table string, columns map[string]string) error { +func checkRecordsColumns(table string, columns map[string]columnInfo) error { if len(columns) == 0 { return fmt.Errorf("%w: table %s does not exist in the configured database", errContract, table) } for _, c := range recordsContract { - dataType, ok := columns[c.name] + info, ok := columns[c.name] if !ok { return fmt.Errorf("%w: table %s has no column %s", errContract, table, c.name) } - compatible := false - for _, allowed := range c.types { - if dataType == allowed { - compatible = true - break + if !c.accepts(info) { + shown := info.columnType + if shown == "" { + shown = info.dataType } - } - if !compatible { - return fmt.Errorf("%w: column %s of table %s has incompatible type %s", errContract, c.name, table, dataType) + return fmt.Errorf("%w: column %s of table %s has incompatible type %s, it must be %s", errContract, c.name, table, shown, c.requirement) } } return nil @@ -299,14 +325,23 @@ type connSource interface { Conn(ctx context.Context) (*sql.Conn, error) } -func withNamedLock(ctx context.Context, db connSource, name string, timeout time.Duration, log *slog.Logger, fn func(conn *sql.Conn) error) (err error) { +func discardConn(conn *sql.Conn) { + _ = conn.Raw(func(any) error { return driver.ErrBadConn }) +} + +func withNamedLock(ctx context.Context, db connSource, name string, timeout time.Duration, log *slog.Logger, fn func(conn *sql.Conn) error) error { conn, err := db.Conn(ctx) if err != nil { return fmt.Errorf("dedicated connection: %w", err) } + discard := false defer func() { - if cerr := conn.Close(); cerr != nil && err == nil { - err = fmt.Errorf("close dedicated connection: %w", cerr) + if discard { + discardConn(conn) + return + } + if cerr := conn.Close(); cerr != nil { + log.ErrorContext(ctx, "dedicated connection close failed", "lock", name, "error", cerr) } }() lock, err := acquireNamedLock(ctx, conn, name, timeout) @@ -321,10 +356,8 @@ func withNamedLock(ctx context.Context, db connSource, name string, timeout time releaseCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), dbPingAttemptTimeout) defer cancel() if rerr := lock.release(releaseCtx); rerr != nil { - log.ErrorContext(ctx, "named lock release failed", "lock", name, "error", rerr) - if err == nil { - err = rerr - } + log.ErrorContext(ctx, "named lock release failed, discarding the connection", "lock", name, "error", rerr) + discard = true return } log.DebugContext(ctx, "named lock released", "lock", name) @@ -375,3 +408,144 @@ func scanNullUTC(t *sql.NullTime) { t.Time = t.Time.UTC() } } + +type traceConnector struct { + driver.Connector + log *slog.Logger +} + +func (c traceConnector) Connect(ctx context.Context) (driver.Conn, error) { + conn, err := c.Connector.Connect(ctx) + if err != nil { + return nil, err + } + return &traceConn{Conn: conn, log: c.log}, nil +} + +type traceConn struct { + driver.Conn + log *slog.Logger +} + +var errNoBeginTx = errors.New("driver connection does not support BeginTx") + +func (c *traceConn) BeginTx(ctx context.Context, opts driver.TxOptions) (driver.Tx, error) { + b, ok := c.Conn.(driver.ConnBeginTx) + if !ok { + return nil, errNoBeginTx + } + return b.BeginTx(ctx, opts) +} + +func (c *traceConn) PrepareContext(ctx context.Context, query string) (driver.Stmt, error) { + if p, ok := c.Conn.(driver.ConnPrepareContext); ok { + return p.PrepareContext(ctx, query) + } + return c.Conn.Prepare(query) +} + +func (c *traceConn) ExecContext(ctx context.Context, query string, args []driver.NamedValue) (driver.Result, error) { + traceSQL(ctx, c.log, query, args) + if e, ok := c.Conn.(driver.ExecerContext); ok { + return e.ExecContext(ctx, query, args) + } + return nil, driver.ErrSkip +} + +func (c *traceConn) QueryContext(ctx context.Context, query string, args []driver.NamedValue) (driver.Rows, error) { + traceSQL(ctx, c.log, query, args) + if q, ok := c.Conn.(driver.QueryerContext); ok { + return q.QueryContext(ctx, query, args) + } + return nil, driver.ErrSkip +} + +func (c *traceConn) Ping(ctx context.Context) error { + if p, ok := c.Conn.(driver.Pinger); ok { + return p.Ping(ctx) + } + return nil +} + +func (c *traceConn) ResetSession(ctx context.Context) error { + if r, ok := c.Conn.(driver.SessionResetter); ok { + return r.ResetSession(ctx) + } + return nil +} + +func (c *traceConn) IsValid() bool { + if v, ok := c.Conn.(driver.Validator); ok { + return v.IsValid() + } + return true +} + +func (c *traceConn) CheckNamedValue(nv *driver.NamedValue) error { + if n, ok := c.Conn.(driver.NamedValueChecker); ok { + return n.CheckNamedValue(nv) + } + return driver.ErrSkip +} + +var traceIdentifier = regexp.MustCompile(`^[A-Za-z0-9_.*:@-]{0,255}$`) + +type privateSQLArgsKey struct{} + +func privateSQLArgs(ctx context.Context, ordinals ...int) context.Context { + var mask uint64 + for _, ordinal := range ordinals { + mask |= 1 << ordinal + } + return context.WithValue(ctx, privateSQLArgsKey{}, mask) +} + +func traceValue(v driver.Value) any { + switch x := v.(type) { + case nil, int64, uint64, float64, bool, time.Time: + return x + case string: + if traceIdentifier.MatchString(x) { + return x + } + } + return redactedLogValue +} + +func ownFunction(full string) (string, bool) { + pkg, name, ok := strings.Cut(full[strings.LastIndex(full, "/")+1:], ".") + return name, ok && (pkg == "main" || pkg == "coredns-web-ui") +} + +func sqlCaller() string { + pcs := make([]uintptr, 48) + frames := runtime.CallersFrames(pcs[:runtime.Callers(3, pcs)]) + var callers []string + for len(callers) < 2 { + f, more := frames.Next() + name, ok := ownFunction(f.Function) + if ok && !strings.HasPrefix(name, "(*traceConn)") && !strings.HasPrefix(name, "traceSQL") { + callers = append(callers, name) + } + if !more { + break + } + } + return strings.Join(callers, " < ") +} + +func traceSQL(ctx context.Context, log *slog.Logger, query string, args []driver.NamedValue) { + if !log.Enabled(ctx, LevelTrace) { + return + } + values := make([]any, len(args)) + private, _ := ctx.Value(privateSQLArgsKey{}).(uint64) + for i, a := range args { + if private&(1< [redacted]", "42]", + } { + if !strings.Contains(out, want) { + t.Errorf("trace lacks %q:\n%s", want, out) + } + } + for _, secret := range []string{secretHash, "c2VjcmV0", string(tokenHash), hex.EncodeToString(tokenHash), "private-user-agent", + "secret-session-token", unstructuredHash, "private-record-content", "private-audit-error", "987654321"} { + if strings.Contains(out, secret) { + t.Fatalf("trace contains a secret %q", secret) + } + } + logs.Reset() + quiet := sql.OpenDB(traceConnector{Connector: fdbConnector{s: st}, log: newLogger(&logs, slog.LevelDebug)}) + defer quiet.Close() + if _, err := quiet.ExecContext(ctx, "UPDATE x SET y = ?", 1); err != nil || logs.Len() != 0 { + t.Fatalf("%v %s", err, logs.String()) + } + for v, want := range map[driver.Value]any{nil: nil, int64(5): int64(5), uint64(5): uint64(5), 1.5: 1.5, true: true, "example.org.": "example.org.", + "*.dev": "*.dev", "with space": redactedLogValue, `{"ip":"192.0.2.1"}`: redactedLogValue, "$fake$pw": redactedLogValue} { + if got := traceValue(v); got != want { + t.Errorf("%v: %v", v, got) + } + } + if traceValue([]byte("x")) != redactedLogValue { + t.Error("bytes not redacted") + } +} + +type bareConn struct{} + +func (bareConn) Prepare(string) (driver.Stmt, error) { return nil, errors.New("prepare") } +func (bareConn) Close() error { return nil } +func (bareConn) Begin() (driver.Tx, error) { return nil, errors.New("begin") } + +func TestTraceConnForwarding(t *testing.T) { + ctx := context.Background() + c := &traceConn{Conn: bareConn{}, log: discardLogger()} + if _, err := c.BeginTx(ctx, driver.TxOptions{}); !errors.Is(err, errNoBeginTx) { + t.Fatal(err) + } + if _, err := c.PrepareContext(ctx, "x"); err == nil || err.Error() != "prepare" { + t.Fatal(err) + } + if _, err := c.ExecContext(ctx, "x", nil); !errors.Is(err, driver.ErrSkip) { + t.Fatal(err) + } + if _, err := c.QueryContext(ctx, "x", nil); !errors.Is(err, driver.ErrSkip) { + t.Fatal(err) + } + if c.Ping(ctx) != nil || c.ResetSession(ctx) != nil || !c.IsValid() || c.CheckNamedValue(&driver.NamedValue{}) != driver.ErrSkip { + t.Fatal("bare forwarding") + } + mc, err := mysql.NewConnector(mysql.NewConfig()) + if err != nil { + t.Fatal(err) + } + if (traceConnector{Connector: mc}).Driver() == nil { + t.Fatal("driver") + } + failing := traceConnector{Connector: failingConnector{}, log: discardLogger()} + if _, err := failing.Connect(ctx); err == nil { + t.Fatal("connect error lost") + } + db, err := openDatabase(Config{DBHost: "db", DBPort: 3306, DBUser: "u", DBPassword: "p", DBName: "n"}, newLogger(io.Discard, LevelTrace)) + if err != nil { + t.Fatal(err) + } + db.Close() +} + +type failingConnector struct{} + +func (failingConnector) Connect(context.Context) (driver.Conn, error) { return nil, errors.New("down") } +func (failingConnector) Driver() driver.Driver { return fdbDriver{} } diff --git a/delegation_store.go b/delegation_store.go index 69f6049..d2402f1 100644 --- a/delegation_store.go +++ b/delegation_store.go @@ -35,6 +35,7 @@ func newDelegationStore(q dbtx, t tableNames) delegationStore { } func (s delegationStore) GrantDelegation(ctx context.Context, zone string, userID, createdBy int64, now time.Time) (bool, error) { + defer traceStore(ctx, "delegationStore.GrantDelegation")() _, err := s.q.ExecContext(ctx, s.t.sql("INSERT INTO {delegations} (`zone`, `user_id`, `created_at`, `created_by`) VALUES (?, ?, ?, ?)"), zone, userID, dbTime(now), createdBy) @@ -48,6 +49,7 @@ func (s delegationStore) GrantDelegation(ctx context.Context, zone string, userI } func (s delegationStore) RevokeDelegation(ctx context.Context, zone string, userID int64) (bool, error) { + defer traceStore(ctx, "delegationStore.RevokeDelegation")() res, err := s.q.ExecContext(ctx, s.t.sql("DELETE FROM {delegations} WHERE `zone` = ? AND `user_id` = ?"), zone, userID) if err != nil { return false, fmt.Errorf("revoke delegation: %w", err) @@ -60,6 +62,7 @@ func (s delegationStore) RevokeDelegation(ctx context.Context, zone string, user } func (s delegationStore) ZoneUsers(ctx context.Context, zone string) ([]userRow, error) { + defer traceStore(ctx, "delegationStore.ZoneUsers")() rows, err := s.q.QueryContext(ctx, s.t.sql("SELECT "+userColumns+" FROM {delegations} d JOIN {users} u ON u.`id` = d.`user_id` "+ "WHERE d.`zone` = ? AND u.`role` = 'user' AND u.`deleted_at` IS NULL ORDER BY u.`username`"), zone) @@ -70,6 +73,7 @@ func (s delegationStore) ZoneUsers(ctx context.Context, zone string) ([]userRow, } func (s delegationStore) UserZones(ctx context.Context, userID int64) ([]userZone, error) { + defer traceStore(ctx, "delegationStore.UserZones")() rows, err := s.q.QueryContext(ctx, s.t.sql("SELECT d.`zone`, d.`created_at`, EXISTS (SELECT 1 FROM {records} r WHERE r.`zone` = d.`zone`) "+ "FROM {delegations} d WHERE d.`user_id` = ? ORDER BY d.`zone`"), userID) @@ -93,6 +97,7 @@ func (s delegationStore) UserZones(ctx context.Context, userID int64) ([]userZon } func (s delegationStore) DeleteZoneDelegations(ctx context.Context, zone string) ([]delegationRow, error) { + defer traceStore(ctx, "delegationStore.DeleteZoneDelegations")() rows, err := s.q.QueryContext(ctx, s.t.sql("SELECT d.`zone`, d.`user_id`, u.`username`, d.`created_at`, d.`created_by` FROM {delegations} d "+ "JOIN {users} u ON u.`id` = d.`user_id` WHERE d.`zone` = ? ORDER BY u.`username` FOR UPDATE OF d"), zone) @@ -136,9 +141,11 @@ func (s delegationStore) hasDelegation(ctx context.Context, query, zone string, } func (s delegationStore) HasDelegation(ctx context.Context, zone string, userID int64) (bool, error) { + defer traceStore(ctx, "delegationStore.HasDelegation")() return s.hasDelegation(ctx, "SELECT 1 FROM {delegations} WHERE `zone` = ? AND `user_id` = ?", zone, userID) } func (s delegationStore) HasDelegationForShare(ctx context.Context, zone string, userID int64) (bool, error) { + defer traceStore(ctx, "delegationStore.HasDelegationForShare")() return s.hasDelegation(ctx, "SELECT 1 FROM {delegations} WHERE `zone` = ? AND `user_id` = ? FOR SHARE", zone, userID) } diff --git a/handlers_api.go b/handlers_api.go index aa31398..9de31fd 100644 --- a/handlers_api.go +++ b/handlers_api.go @@ -25,6 +25,7 @@ const ( msgDelegationAbsent = "delegation not found" msgWrongPassword = "current password is wrong" msgConfirmMismatch = "confirmation does not match" + msgPasswordChanged = "the password was changed by another request" ) func frameworkAPIHandlers(s *WebServer) map[string]apiHandler { @@ -123,6 +124,18 @@ func activeTargetForUpdate(ctx context.Context, c *apiContext, tx webTx, usernam return u, nil } +func lockActingAdmin(ctx context.Context, c *apiContext, tx webTx) ([]userRow, error) { + admins, err := tx.LockActiveAdmins(ctx) + if err != nil { + return nil, err + } + if !slices.ContainsFunc(admins, func(u userRow) bool { return u.ID == c.Principal.User.ID }) { + c.Server.log.WarnContext(ctx, "actor is no longer an active admin", "operation", c.Entry.Operation, "user", c.Principal.User.Username) + return nil, &apiError{Status: http.StatusForbidden, Message: msgAdminRequired} + } + return admins, nil +} + func (c *apiContext) recordChange(before, after []byte) { c.Entry.Before, c.Entry.After = before, after } @@ -182,11 +195,14 @@ func handlePasswordChange(ctx context.Context, c *apiContext) (apiResponse, erro c.setTargetUser(c.Principal.User) err = s.store.InTx(ctx, func(tx webTx) error { u, err := tx.UserByIDForUpdate(ctx, c.Principal.User.ID) + if errors.Is(err, errRowNotFound) || (err == nil && u.DeletedAt.Valid) { + return &apiError{Status: http.StatusUnauthorized, Message: msgAuthRequired} + } if err != nil { return err } - if u.DeletedAt.Valid { - return errUserNotFound() + if u.PasswordHash != c.Principal.User.PasswordHash { + return &apiError{Status: http.StatusConflict, Message: msgPasswordChanged} } if err := tx.SetPassword(ctx, u.ID, hash, c.Now); err != nil { return err @@ -242,6 +258,9 @@ func handleDelegationGrant(ctx context.Context, c *apiContext) (apiResponse, err return apiResponse{}, err } err = c.Server.store.InZoneTx(ctx, c.Zone, c.Server.log, func(tx webTx) error { + if _, err := lockActingAdmin(ctx, c, tx); err != nil { + return err + } if err := requireZone(ctx, tx.ZoneExists, c.Zone); err != nil { return err } @@ -275,6 +294,9 @@ func handleDelegationRevoke(ctx context.Context, c *apiContext) (apiResponse, er return apiResponse{}, err } err = c.Server.store.InZoneTx(ctx, c.Zone, c.Server.log, func(tx webTx) error { + if _, err := lockActingAdmin(ctx, c, tx); err != nil { + return err + } u, err := activeTargetForUpdate(ctx, c, tx, username) if err != nil { return err @@ -379,6 +401,9 @@ func handleUserCreate(ctx context.Context, c *apiContext) (apiResponse, error) { } var created userRow err = s.store.InTx(ctx, func(tx webTx) error { + if _, err := lockActingAdmin(ctx, c, tx); err != nil { + return err + } u, err := tx.CreateUser(ctx, req.Username, req.Role, hash, c.Now) if errors.Is(err, errUsernameTaken) { return &apiError{Status: http.StatusConflict, Message: msgUsernameTaken} @@ -392,6 +417,7 @@ func handleUserCreate(ctx context.Context, c *apiContext) (apiResponse, error) { return c.commitChange(ctx, tx, http.StatusCreated) }) if err != nil { + c.Entry.TargetUserID = sql.NullInt64{} return apiResponse{}, err } return apiResponse{Status: http.StatusCreated, Body: userListItemOf(created, 0)}, nil @@ -451,7 +477,7 @@ type userRoleRequest struct { } func lockAdminsAndTarget(ctx context.Context, c *apiContext, tx webTx, username string) (userRow, []userRow, error) { - admins, err := tx.LockActiveAdmins(ctx) + admins, err := lockActingAdmin(ctx, c, tx) if err != nil { return userRow{}, nil, err } @@ -518,6 +544,9 @@ func handleUserPassword(ctx context.Context, c *apiContext) (apiResponse, error) return apiResponse{}, err } err = s.store.InTx(ctx, func(tx webTx) error { + if _, err := lockActingAdmin(ctx, c, tx); err != nil { + return err + } u, err := activeTargetForUpdate(ctx, c, tx, username) if err != nil { return err @@ -637,6 +666,15 @@ func auditItemOf(r auditRow) auditItem { } } +func auditItemFor(p principal, r auditRow) auditItem { + item := auditItemOf(r) + refused := !r.Status.Valid || r.Status.Int64 >= 400 + if !p.isAdmin() && r.TargetUserID.Valid && r.TargetUserID.Int64 != p.User.ID && refused { + item.TargetUser = nil + } + return item +} + func parseAuditFilter(q url.Values) (auditFilter, error) { f := auditFilter{Limit: auditDefaultLimit} if v := q.Get("zone"); v != "" { @@ -671,7 +709,7 @@ func parseAuditFilter(q url.Values) (auditFilter, error) { return auditFilter{}, badParameter("outcome") } if v := q.Get("before_id"); v != "" { - n, err := parsePositive(v, 1<<62) + n, err := parsePositive(v, auditMaxBeforeID) if err != nil { return auditFilter{}, badParameter("before_id") } @@ -735,7 +773,7 @@ func handleAuditRead(ctx context.Context, c *apiContext) (apiResponse, error) { resp.NextBeforeID = &next break } - resp.Entries = append(resp.Entries, auditItemOf(r)) + resp.Entries = append(resp.Entries, auditItemFor(c.Principal, r)) } return okJSON(resp), nil } @@ -1100,7 +1138,7 @@ func (h zoneHandlers) createZone(ctx context.Context, c *apiContext) (apiRespons if err != nil { return apiResponse{}, err } - if err := zoneAPIAuditChange(c, nil, zoneAPIAuditRows(rows, deleted), true); err != nil { + if err := zoneAPIAuditChange(c, zoneAPIAuditRows(nil, deleted), zoneAPIAuditRows(rows, nil), true); err != nil { return apiResponse{}, err } return zoneAPISummary(zone, rows, c.Now, http.StatusCreated), nil diff --git a/handlers_api_test.go b/handlers_api_test.go index 7652fac..b5358ce 100644 --- a/handlers_api_test.go +++ b/handlers_api_test.go @@ -133,7 +133,7 @@ func TestPasswordChange(t *testing.T) { 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"}`) + expectError(t, res, 401, `{"error":"authentication required"}`) } type deletedDuringRequest struct { @@ -425,10 +425,10 @@ func TestAPIUserRole(t *testing.T) { } } 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") + expectError(t, res, 403, `{"error":"admin role required"}`) + expectNoChange(t, res, opUserRole, 403) + if h.stored("root").Role != roleAdmin || h.stored("admin").Role != roleAdmin { + t.Fatal("change by a demoted actor kept") } h.store.onLock = nil h.store.failOn["SetRole"] = errors.New("x") @@ -494,7 +494,8 @@ func TestAPIUserDelete(t *testing.T) { 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"}`) + expectError(t, res, 403, `{"error":"admin role required"}`) + expectNoChange(t, res, opUserDelete, 403) if h.stored("root").DeletedAt.Valid || h.stored("admin").DeletedAt.Valid { t.Fatal("rolled back state kept") } @@ -624,7 +625,7 @@ func TestAuditFilterParsing(t *testing.T) { "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}, + "before_id=9007199254740991&limit=200": {BeforeID: 9007199254740991, Limit: 200}, "limit=1": {Limit: 1}, } for q, want := range good { @@ -644,6 +645,7 @@ func TestAuditFilterParsing(t *testing.T) { "before_id=-1": "before_id", "before_id=1e3": "before_id", "before_id=99999999999999999999": "before_id", + "before_id=9007199254740992": "before_id", "limit=0": "limit", "limit=201": "limit", "limit=+5": "limit", @@ -1174,7 +1176,7 @@ func TestZoneAPIWriteHandlers(t *testing.T) { recordID int64 serial bool }{ - {"zone_create", "", "", zoneAPITestCreate, 201, nil, []int64{1, 2, 3}, 0, false}, + {"zone_create", "", "", zoneAPITestCreate, 201, []int64{}, []int64{1, 2, 3}, 0, false}, {"zone_delete", "", "", `{"confirm":"EXAMPLE.ORG"}`, 204, []int64{1, 2, 3, 4}, nil, 0, false}, {"record_create", "", "", zoneAPITestRecord, 201, []int64{1}, []int64{1, 5}, 5, true}, {"record_update", "3", recordETag(rows[2]), zoneAPITestRecord, 200, []int64{1, 3}, []int64{1, 3}, 3, true}, diff --git a/handlers_pages.go b/handlers_pages.go index df5cf6e..a35530d 100644 --- a/handlers_pages.go +++ b/handlers_pages.go @@ -268,13 +268,28 @@ func (s *WebServer) renderPage(w http.ResponseWriter, status int, page string, d 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) + status, _ := failureStatus(err) + pageError(w, status) +} + +func pageError(w http.ResponseWriter, status int) { + if status == http.StatusServiceUnavailable { + http.Error(w, msgPageUnavailable, status) return } http.Error(w, msgPageInternalError, http.StatusInternalServerError) } +func (s *WebServer) pageZoneExists(ctx context.Context, zone string) (bool, error) { + for _, stored := range []string{zone, strings.TrimSuffix(zone, ".")} { + ok, err := s.store.ZoneExists(ctx, stored) + if err != nil || ok { + return ok, err + } + } + return false, nil +} + func (s *WebServer) optionalPageData(r *http.Request) pageData { data := s.basePageData() if p, err := s.authenticate(r); err == nil { @@ -297,6 +312,7 @@ func (s *WebServer) handleMethodNotAllowed(allow string) http.HandlerFunc { func (s *WebServer) servePage(route pageRoute) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { ctx := r.Context() + defer traceFunc(ctx, s.log, "page."+route.Page)() p, err := s.authenticate(r) if errors.Is(err, errNoSession) { http.Redirect(w, r, loginLocation(r), http.StatusSeeOther) @@ -338,6 +354,15 @@ func (s *WebServer) servePage(route pageRoute) http.HandlerFunc { s.renderPage(w, http.StatusNotFound, "not_found", data) return } + exists, err := s.pageZoneExists(ctx, zone) + if err != nil { + s.pageFailure(w, r, err) + return + } + if !exists { + s.renderPage(w, http.StatusNotFound, "not_found", data) + return + } data.Zone = zone } s.renderPage(w, http.StatusOK, route.Page, data) @@ -359,20 +384,32 @@ func (s *WebServer) renderLogin(w http.ResponseWriter, r *http.Request, status i } func (s *WebServer) handleLoginPage(w http.ResponseWriter, r *http.Request) { + defer traceFunc(r.Context(), s.log, "page.login.get")() 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 { +var errLoginStale = errors.New("account changed during login") + +func (s *WebServer) loginAttemptAudit(ctx context.Context, e auditEntry, status int, message string) int { 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 + if !s.recordAudit(ctx, e) { + return http.StatusInternalServerError } - return nil + return status +} + +func (s *WebServer) sessionOperationFailure(ctx context.Context, e auditEntry, err error) int { + if isAuditWriteError(err) { + s.recordInternalAudit(ctx, e) + return http.StatusInternalServerError + } + status, msg := failureStatus(err) + return s.loginAttemptAudit(ctx, e, status, msg) } func (s *WebServer) handleLogin(w http.ResponseWriter, r *http.Request) { ctx := r.Context() + defer traceFunc(ctx, s.log, "page.login.post")() r.Body = http.MaxBytesReader(w, r.Body, loginFormLimit) if err := r.ParseForm(); err != nil { s.log.DebugContext(ctx, "invalid login form", "error", err) @@ -396,7 +433,7 @@ func (s *WebServer) handleLogin(w http.ResponseWriter, r *http.Request) { 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) + status = s.loginAttemptAudit(ctx, loginAuditEntry(now, opLogin, username, nil, origin), status, msg) s.renderLogin(w, r, status, next, msgLoginUnavailable) return } @@ -404,26 +441,28 @@ func (s *WebServer) handleLogin(w http.ResponseWriter, r *http.Request) { 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) + s.renderLoginResult(w, r, s.loginAttemptAudit(ctx, entry, http.StatusTooManyRequests, msgTooManyLogins), 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) + s.renderLoginResult(w, r, s.loginAttemptAudit(ctx, entry, http.StatusUnauthorized, msgInvalidLogin), next, msgInvalidLogin) return } token, hash, err := newSessionToken(s.random) if err == nil { err = s.store.InTx(ctx, func(tx webTx) error { + current, err := tx.UserByIDForUpdate(ctx, user.ID) + if errors.Is(err, errRowNotFound) { + return errLoginStale + } + if err != nil { + return err + } + if current.DeletedAt.Valid || current.PasswordHash != user.PasswordHash { + return errLoginStale + } if old, ok := requestSessionToken(r); ok { if _, err := tx.DeleteSession(ctx, sessionTokenHash(old)); err != nil { return err @@ -437,15 +476,18 @@ func (s *WebServer) handleLogin(w http.ResponseWriter, r *http.Request) { } e := entry finishAuditEntry(&e, http.StatusSeeOther, "") - _, err := tx.InsertAudit(ctx, e) - return err + return insertAuditRow(ctx, tx, e) }) } + if errors.Is(err, errLoginStale) { + s.limiter.fail(actor, origin) + s.log.WarnContext(ctx, "login failed", "actor", actor, "origin", origin, "reason", "account changed during login") + s.renderLoginResult(w, r, s.loginAttemptAudit(ctx, entry, http.StatusUnauthorized, msgInvalidLogin), next, msgInvalidLogin) + return + } 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) + s.renderLogin(w, r, s.sessionOperationFailure(ctx, entry, err), next, msgLoginUnavailable) return } s.limiter.succeed(actor) @@ -455,8 +497,16 @@ func (s *WebServer) handleLogin(w http.ResponseWriter, r *http.Request) { http.Redirect(w, r, next, http.StatusSeeOther) } +func (s *WebServer) renderLoginResult(w http.ResponseWriter, r *http.Request, status int, next, message string) { + if status == http.StatusInternalServerError { + message = msgLoginUnavailable + } + s.renderLogin(w, r, status, next, message) +} + func (s *WebServer) handleLogout(w http.ResponseWriter, r *http.Request) { ctx := r.Context() + defer traceFunc(ctx, s.log, "page.logout")() p, err := s.authenticate(r) if errors.Is(err, errNoSession) { http.SetCookie(w, expiredSessionCookie(s.cfg.CookieSecure)) @@ -474,13 +524,11 @@ func (s *WebServer) handleLogout(w http.ResponseWriter, r *http.Request) { } e := entry finishAuditEntry(&e, http.StatusSeeOther, "") - _, err := tx.InsertAudit(ctx, e) - return err + return insertAuditRow(ctx, tx, e) }) if err != nil { - status, msg := failureStatus(err) - _ = s.loginAttemptAudit(ctx, entry, status, msg) - s.pageFailure(w, r, err) + s.log.ErrorContext(ctx, "logout failed", "error", err) + pageError(w, s.sessionOperationFailure(ctx, entry, err)) return } s.log.InfoContext(ctx, "change committed", "operation", opLogout, "actor", p.User.Username) @@ -495,7 +543,11 @@ func (s *WebServer) registerPageRoutes(r *mux.Router) { "POST /logout": s.handleLogout, } if s.pages != nil { - r.PathPrefix("/static/").Handler(s.pages.staticHandler()) + static := s.pages.staticHandler() + r.PathPrefix("/static/").HandlerFunc(func(w http.ResponseWriter, req *http.Request) { + defer traceFunc(req.Context(), s.log, "page.static")() + static.ServeHTTP(w, req) + }) } byPath := map[string]map[string]http.HandlerFunc{} var paths []string diff --git a/handlers_pages_test.go b/handlers_pages_test.go index 15cc862..87e1b1f 100644 --- a/handlers_pages_test.go +++ b/handlers_pages_test.go @@ -246,7 +246,7 @@ func TestEmbeddedFilesRules(t *testing.T) { return err } text := string(data) - if strings.Contains(text, "—") { + if strings.Contains(text, "\u2014") { t.Errorf("%s/%s contains an em dash", name, p) } if strings.HasSuffix(p, ".js") || strings.HasSuffix(p, ".css") { @@ -653,3 +653,49 @@ func TestRenderEscaping(t *testing.T) { t.Error("login: escaped error missing") } } + +func TestZonePagesRequireAnExistingZone(t *testing.T) { + h := newWebHarness(t) + admin := h.user("admin", roleAdmin) + alice := h.user("alice", roleUser) + h.store.addZone(testZone) + h.store.addZone(otherZone) + h.store.addZone("undotted.org") + h.store.delegate(testZone, alice) + h.store.delegate("stale.org.", alice) + at, ut := h.login(admin), h.login(alice) + for _, suffix := range []string{"", "/import"} { + page := func(token, zone string) webResult { + return h.do(webRequest{method: "GET", path: "/zones/" + zone + suffix, token: token}) + } + for _, c := range []struct { + token, zone string + status int + }{ + {at, "example.org.", 200}, + {at, "Example.ORG", 200}, + {at, "undotted.org", 200}, + {at, "missing.org", 404}, + {at, "stale.org.", 404}, + {ut, "example.org", 200}, + {ut, "stale.org.", 404}, + {ut, "other.org.", 404}, + {ut, "missing.org", 404}, + } { + if res := page(c.token, c.zone); res.status != c.status || len(res.audit) != 0 { + t.Errorf("%s%s: %d, want %d", c.zone, suffix, res.status, c.status) + } + } + missing, stale, other := page(ut, "missing.org"), page(ut, "stale.org"), page(ut, "other.org") + if missing.body != stale.body || missing.body != other.body || !strings.Contains(missing.body, "alice") { + t.Errorf("%s: not found pages differ", suffix) + } + if adminMissing := page(at, "missing.org"); !strings.Contains(adminMissing.body, "admin") { + t.Errorf("%s: admin not found page", suffix) + } + } + h.store.failOn["ZoneExists"] = errDatabase + if res := h.do(webRequest{method: "GET", path: "/zones/example.org.", token: at}); res.status != 503 { + t.Fatal(res.status) + } +} diff --git a/handlers_race_test.go b/handlers_race_test.go new file mode 100644 index 0000000..3ddc197 --- /dev/null +++ b/handlers_race_test.go @@ -0,0 +1,181 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright (C) 2026 Bryan Joshua Pedini + +package main + +import ( + "database/sql" + "errors" + "testing" + "time" +) + +func TestLoginRechecksTheAccountInTheSessionTransaction(t *testing.T) { + h := newWebHarness(t) + alice := h.user("alice", roleUser) + bob := h.user("bob", roleUser) + resetHash := fakeHash("admin-reset-password") + for _, c := range []struct { + user userRow + mutate func(u *userRow) + }{ + {alice, func(u *userRow) { u.PasswordHash = resetHash }}, + {bob, func(u *userRow) { u.DeletedAt = sql.NullTime{Time: webNow, Valid: true} }}, + } { + h.store.onTx = func(st *fakeWebState) { c.mutate(&st.users[c.user.ID-1]) } + res := h.postLogin(loginForm(c.user.Username, testPassword, ""), "") + if res.status != 401 || len(res.header.Values("Set-Cookie")) != 0 || h.store.sessionCount(c.user.ID) != 0 { + t.Fatalf("%s: %d %v", c.user.Username, res.status, res.header) + } + e := expectOneAudit(t, res, opLogin, 401) + if res.audit[0].inTx || e.UserID.Int64 != c.user.ID || e.Error.String != msgInvalidLogin { + t.Fatalf("%s: %+v", c.user.Username, res.audit[0]) + } + if h.store.user(c.user.ID).LastLoginAt.Valid { + t.Fatalf("%s: last login touched", c.user.Username) + } + } + if h.store.user(alice.ID).PasswordHash != resetHash || !h.store.user(bob.ID).DeletedAt.Valid { + t.Fatal("the concurrent change was lost") + } + + admin := h.user("admin", roleAdmin) + carol := h.user("carol", roleUser) + dave := h.user("dave", roleUser) + at := h.login(admin) + for _, c := range []struct { + user userRow + method, path string + body string + wantHash string + wantDeletedAt bool + }{ + {carol, "PUT", "/users/carol/password", `{"password":"admin-reset-password"}`, resetHash, false}, + {dave, "DELETE", "/users/dave", `{"confirm":"dave"}`, fakeHash(testPassword), true}, + } { + res := h.postLogin(loginForm(c.user.Username, testPassword, ""), "") + if res.status != 303 { + t.Fatalf("%s: login %d", c.user.Username, res.status) + } + session := responseCookie(t, res).Value + if r := h.api(c.method, c.path, at, c.body); r.status != 204 { + t.Fatalf("%s: %d %s", c.path, r.status, r.body) + } + if h.api("GET", "/account", session, "").status != 401 || h.store.sessionCount(c.user.ID) != 0 { + t.Fatalf("%s: the session of the committed login survived", c.user.Username) + } + u := h.store.user(c.user.ID) + if u.PasswordHash != c.wantHash || u.DeletedAt.Valid != c.wantDeletedAt { + t.Fatalf("%s: %+v", c.user.Username, u) + } + } +} + +func TestOwnPasswordChangeRechecksTheStoredHash(t *testing.T) { + h := newWebHarness(t) + admin := h.user("admin", roleAdmin) + alice := h.user("alice", roleUser) + at := h.login(admin) + aliceSession := h.login(alice) + h.login(alice) + resetHash := fakeHash("admin-reset-password") + h.store.onTx = func(st *fakeWebState) { + st.users[alice.ID-1].PasswordHash = resetHash + for k, s := range st.sessions { + if s.UserID == alice.ID { + delete(st.sessions, k) + } + } + } + res := h.api("PUT", "/account/password", aliceSession, `{"current":"secret-password","password":"own-new-password"}`) + expectError(t, res, 409, `{"error":"the password was changed by another request"}`) + if e := expectNoChange(t, res, opPasswordChange, 409); e.TargetUserID.Int64 != alice.ID { + t.Fatalf("%+v", e) + } + if h.store.user(alice.ID).PasswordHash != resetHash || h.store.sessionCount(alice.ID) != 0 { + t.Fatal("own change overwrote the admin reset") + } + + bob := h.user("bob", roleUser) + own, other := h.login(bob), h.login(bob) + res = h.api("PUT", "/account/password", own, `{"current":"secret-password","password":"own-new-password"}`) + if res.status != 204 || h.store.user(bob.ID).PasswordHash != fakeHash("own-new-password") { + t.Fatalf("%d %s", res.status, res.body) + } + if h.api("GET", "/account", other, "").status != 401 || h.api("GET", "/account", own, "").status != 200 { + t.Fatal("own change sessions") + } + if r := h.api("PUT", "/users/bob/password", at, `{"password":"admin-reset-password"}`); r.status != 204 { + t.Fatal(r.status) + } + if h.store.user(bob.ID).PasswordHash != resetHash || h.store.sessionCount(bob.ID) != 0 { + t.Fatal("admin reset after the own change") + } + + carol := h.user("carol", roleUser) + carolSession := h.login(carol) + h.store.onTx = func(st *fakeWebState) { + st.users[carol.ID-1].DeletedAt = sql.NullTime{Time: webNow, Valid: true} + for k, session := range st.sessions { + if session.UserID == carol.ID { + delete(st.sessions, k) + } + } + } + res = h.api("PUT", "/account/password", carolSession, `{"current":"secret-password","password":"own-new-password"}`) + if e := expectNoChange(t, res, opPasswordChange, 401); e.Error.String != msgAuthRequired || e.TargetUserID.Int64 != carol.ID { + t.Fatalf("unexpected deletion race audit: %+v", e) + } + if h.store.user(carol.ID).PasswordHash != fakeHash(testPassword) || h.store.sessionCount(carol.ID) != 0 { + t.Fatal("password change survived a concurrent deletion") + } +} + +func TestAdminChangesRecheckTheActingAdmin(t *testing.T) { + mutations := map[string]func(st *fakeWebState){ + "demoted": func(st *fakeWebState) { st.users[0].Role = roleUser }, + "deleted": func(st *fakeWebState) { st.users[0].DeletedAt = sql.NullTime{Time: webNow, Valid: true} }, + } + requests := []struct{ method, path, body, op string }{ + {"PUT", "/zones/other.org./users/bob", "", opDelegationGrant}, + {"DELETE", "/zones/example.org./users/bob", "", opDelegationRevoke}, + {"POST", "/users", `{"username":"newbie","role":"user","password":"long-enough-pw"}`, opUserCreate}, + {"PUT", "/users/bob/role", `{"role":"admin"}`, opUserRole}, + {"PUT", "/users/bob/password", `{"password":"reset-password-1"}`, opUserPassword}, + {"DELETE", "/users/bob", `{"confirm":"bob"}`, opUserDelete}, + } + for name, mutate := range mutations { + for _, r := range requests { + h, token := usersHarness(t) + h.store.addZone(otherZone) + bob := h.store.user(h.users["bob"].ID) + h.store.onLock = mutate + res := h.api(r.method, r.path, token, r.body) + expectError(t, res, 403, `{"error":"admin role required"}`) + expectNoChange(t, res, r.op, 403) + if h.store.user(bob.ID) != bob || !h.store.hasDelegation(testZone, bob.ID) || h.store.hasDelegation(otherZone, bob.ID) { + t.Fatalf("%s %s: change kept", name, r.op) + } + if _, err := h.store.UserByUsername(t.Context(), "newbie"); !errors.Is(err, errRowNotFound) { + t.Fatalf("%s %s: user created", name, r.op) + } + if h.store.called("LockActiveAdmins") != 1 { + t.Fatalf("%s %s: actor not locked", name, r.op) + } + } + } + h, token := usersHarness(t) + h.store.addZone(otherZone) + for _, r := range requests[:2] { + if res := h.api(r.method, r.path, token, r.body); res.status != 204 { + t.Fatalf("%s: %d %s", r.op, res.status, res.body) + } + } + admin := h.stored("admin") + admin.Role = roleUser + admin.UpdatedAt = webNow.Add(time.Minute) + h.store.setUser(admin) + if !h.store.hasDelegation(otherZone, h.users["bob"].ID) || h.store.hasDelegation(testZone, h.users["bob"].ID) { + t.Fatal("changes committed before the demotion did not survive") + } +} diff --git a/handlers_session_test.go b/handlers_session_test.go index 1dd47b4..41b97d3 100644 --- a/handlers_session_test.go +++ b/handlers_session_test.go @@ -373,7 +373,7 @@ func TestPagesCarryNoData(t *testing.T) { } } for _, call := range h.store.calls { - if call != "SessionByTokenHash" && call != "HasDelegation" { + if call != "SessionByTokenHash" && call != "HasDelegation" && call != "ZoneExists" { t.Fatalf("page read %s", call) } } diff --git a/integration_db_test.go b/integration_db_test.go index 37e847a..37babef 100644 --- a/integration_db_test.go +++ b/integration_db_test.go @@ -9,6 +9,7 @@ import ( "context" "database/sql" "errors" + "fmt" "strconv" "strings" "sync" @@ -28,6 +29,11 @@ func TestIntegrationContractCheck(t *testing.T) { {"missing column", itOptions{prefix: "coredns_", recordDDL: strings.Replace(itRecordsDDL, " `ttl` INT DEFAULT NULL,\n", "", 1)}, "has no column ttl"}, {"incompatible type", itOptions{prefix: "coredns_", recordDDL: strings.Replace(itRecordsDDL, "`ttl` INT DEFAULT NULL", "`ttl` VARCHAR(10) DEFAULT NULL", 1)}, "column ttl of table coredns_records has incompatible type varchar"}, {"incompatible content", itOptions{prefix: "coredns_", recordDDL: strings.Replace(itRecordsDDL, "`content` TEXT", "`content` BLOB", 1)}, "column content of table coredns_records has incompatible type blob"}, + {"wide id", itOptions{prefix: "coredns_", recordDDL: strings.Replace(itRecordsDDL, "`id` INT", "`id` BIGINT", 1)}, "column id of table coredns_records has incompatible type bigint"}, + {"narrow ttl", itOptions{prefix: "coredns_", recordDDL: strings.Replace(itRecordsDDL, "`ttl` INT", "`ttl` MEDIUMINT", 1)}, "column ttl of table coredns_records has incompatible type mediumint"}, + {"short zone", itOptions{prefix: "coredns_", recordDDL: strings.Replace(itRecordsDDL, "`zone` VARCHAR(255)", "`zone` VARCHAR(254)", 1)}, "column zone of table coredns_records has incompatible type varchar(254)"}, + {"short name", itOptions{prefix: "coredns_", recordDDL: strings.Replace(itRecordsDDL, "`name` VARCHAR(255)", "`name` VARCHAR(254)", 1)}, "column name of table coredns_records has incompatible type varchar(254)"}, + {"short type", itOptions{prefix: "coredns_", recordDDL: strings.Replace(itRecordsDDL, "`record_type` VARCHAR(255)", "`record_type` VARCHAR(8)", 1)}, "column record_type of table coredns_records has incompatible type varchar(8)"}, } for _, c := range cases { d := newITDatabase(t, c.opts) @@ -58,13 +64,76 @@ func TestIntegrationContractCheck(t *testing.T) { t.Fatalf("prefix %q: %v", prefix, err) } } - bigint := strings.NewReplacer("`id` INT", "`id` BIGINT", "`zone` VARCHAR(255)", "`zone` TEXT", "`content` TEXT", "`content` JSON").Replace(itRecordsDDL) - d := newITDatabase(t, itOptions{prefix: "coredns_", recordDDL: bigint}) + compatible := strings.NewReplacer("`id` INT", "`id` INT UNSIGNED", "`ttl` INT", "`ttl` BIGINT", "`zone` VARCHAR(255)", "`zone` TEXT", + "`name` VARCHAR(255)", "`name` MEDIUMTEXT", "`content` TEXT", "`content` JSON", "`record_type` VARCHAR(255)", "`record_type` VARCHAR(9)").Replace(itRecordsDDL) + d := newITDatabase(t, itOptions{prefix: "coredns_", recordDDL: compatible}) if err := verifyRecordsContract(ctx, d.openApp(t), d.tables(t), discardLogger()); err != nil { t.Fatalf("compatible types refused: %v", err) } } +func TestIntegrationMigrationRestartsAfterEveryDDL(t *testing.T) { + const prefix = "resume_" + migrations, err := loadMigrations(migrationFiles, prefix) + if err != nil { + t.Fatal(err) + } + statements := migrations[0].statements + for boundary := 1; boundary <= len(statements); boundary++ { + t.Run(fmt.Sprintf("after_ddl_%d", boundary), func(t *testing.T) { + d := newITDatabase(t, itOptions{prefix: prefix}) + tn := d.tables(t) + db := d.openApp(t) + ctx := t.Context() + for _, stmt := range statements[:boundary] { + if _, err := db.ExecContext(ctx, stmt); err != nil { + t.Fatal(err) + } + } + if v, err := schemaVersion(ctx, db, tn); err != nil || v != 0 { + t.Fatalf("interrupted schema version = %d, %v", v, err) + } + if err := db.Close(); err != nil { + t.Fatal(err) + } + db, tn = d.migrated(t) + if v, err := schemaVersion(ctx, db, tn); err != nil || v != 1 { + t.Fatalf("restarted schema version = %d, %v", v, err) + } + if n := d.count(t, "SELECT COUNT(*) FROM information_schema.REFERENTIAL_CONSTRAINTS WHERE CONSTRAINT_SCHEMA = DATABASE()"); n != 5 { + t.Fatalf("restarted schema has %d foreign keys", n) + } + }) + } + t.Run("invalid_existing_table", func(t *testing.T) { + d := newITDatabase(t, itOptions{prefix: prefix}) + db, tn := d.migrated(t) + d.rootExec(t, tn.sql("ALTER TABLE {sessions} DROP COLUMN user_agent")) + err := migrateDatabase(t.Context(), db, tn, discardLogger()) + if err == nil || !strings.Contains(err.Error(), "has no column user_agent") { + t.Fatalf("accepted incomplete application schema: %v", err) + } + }) + t.Run("invalid_column_width", func(t *testing.T) { + d := newITDatabase(t, itOptions{prefix: prefix}) + db, tn := d.migrated(t) + d.rootExec(t, tn.sql("ALTER TABLE {users} MODIFY password_hash VARCHAR(15) NOT NULL")) + err := migrateDatabase(t.Context(), db, tn, discardLogger()) + if err == nil || !strings.Contains(err.Error(), "has type varchar(15), expected varchar(255)") { + t.Fatalf("accepted invalid column width: %v", err) + } + }) + t.Run("missing_foreign_key", func(t *testing.T) { + d := newITDatabase(t, itOptions{prefix: prefix}) + db, tn := d.migrated(t) + d.rootExec(t, tn.sql("ALTER TABLE {audit} DROP FOREIGN KEY resume_webui_audit_ibfk_2")) + err := migrateDatabase(t.Context(), db, tn, discardLogger()) + if err == nil || !strings.Contains(err.Error(), "expected 5 foreign keys") { + t.Fatalf("accepted missing audit foreign key: %v", err) + } + }) +} + func TestIntegrationMigrations(t *testing.T) { t.Parallel() ctx := context.Background() diff --git a/integration_helpers_test.go b/integration_helpers_test.go index a46f087..2a75722 100644 --- a/integration_helpers_test.go +++ b/integration_helpers_test.go @@ -115,13 +115,13 @@ func newITDatabase(t *testing.T, opts itOptions) *itDatabase { } admin := srv.open(t, "root", srv.rootPassword, "") ctx := context.Background() - exec := func(q string, args ...any) { + exec := func(operation, query string) { t.Helper() - if _, err := admin.ExecContext(ctx, q, args...); err != nil { - t.Fatalf("%s: %v", q, err) + if err := itExecSetup(ctx, admin, operation, query); err != nil { + t.Fatal(err) } } - exec("CREATE DATABASE `" + d.name + "` DEFAULT CHARSET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci") + exec("create database", "CREATE DATABASE `"+d.name+"` DEFAULT CHARSET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci") t.Cleanup(func() { _, _ = admin.ExecContext(ctx, "DROP DATABASE IF EXISTS `"+d.name+"`") _, _ = admin.ExecContext(ctx, "DROP USER IF EXISTS '"+d.appUser+"'@'%'") @@ -132,23 +132,42 @@ func newITDatabase(t *testing.T, opts itOptions) *itDatabase { if ddl == "" { ddl = itRecordsDDL } - exec(fmt.Sprintf(ddl, d.name, d.prefix)) + exec("create records table", fmt.Sprintf(ddl, d.name, d.prefix)) } - exec("CREATE USER '" + d.appUser + "'@'%' IDENTIFIED BY '" + d.appPassword + "'") - exec("CREATE USER '" + d.dnsUser + "'@'%' IDENTIFIED BY '" + d.dnsPassword + "'") + exec("create application user", "CREATE USER '"+d.appUser+"'@'%' IDENTIFIED BY '"+d.appPassword+"'") + exec("create dns user", "CREATE USER '"+d.dnsUser+"'@'%' IDENTIFIED BY '"+d.dnsPassword+"'") for _, g := range itAppGrants { if !g.create && opts.noRecords { continue } - exec(fmt.Sprintf("GRANT %s ON `%s`.`%s%s` TO '%s'@'%%'", g.privs, d.name, d.prefix, g.table, d.appUser)) + exec("grant application privileges on "+g.table, fmt.Sprintf("GRANT %s ON `%s`.`%s%s` TO '%s'@'%%'", g.privs, d.name, d.prefix, g.table, d.appUser)) } if !opts.noRecords { - exec(fmt.Sprintf("GRANT SELECT ON `%s`.`%srecords` TO '%s'@'%%'", d.name, d.prefix, d.dnsUser)) + exec("grant dns read privileges", fmt.Sprintf("GRANT SELECT ON `%s`.`%srecords` TO '%s'@'%%'", d.name, d.prefix, d.dnsUser)) } d.root = srv.open(t, "root", srv.rootPassword, d.name) return d } +func itExecSetup(ctx context.Context, db dbtx, operation, query string) error { + if _, err := db.ExecContext(ctx, query); err != nil { + if n := mysqlErrNumber(err); n != 0 { + return fmt.Errorf("%s: mysql error %d", operation, n) + } + return fmt.Errorf("%s: database error (%T)", operation, err) + } + return nil +} + +func TestIntegrationSetupErrorRedactsSQL(t *testing.T) { + const sentinel = "setup-password-sentinel" + db := newITDatabase(t, itOptions{noRecords: true}) + err := itExecSetup(t.Context(), db.root, "create test user", "CREATE USER IDENTIFIED BY '"+sentinel+"'") + if err == nil || strings.Contains(err.Error(), sentinel) || err.Error() != "create test user: mysql error 1064" { + t.Fatalf("unexpected setup diagnostic: %v", err) + } +} + func (d *itDatabase) env() map[string]string { return map[string]string{ "DB_HOST": d.server.host, diff --git a/integration_http_race_test.go b/integration_http_race_test.go new file mode 100644 index 0000000..a3d6dbf --- /dev/null +++ b/integration_http_race_test.go @@ -0,0 +1,348 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright (C) 2026 Bryan Joshua Pedini + +//go:build integration + +package main + +import ( + "context" + "database/sql" + "fmt" + "log/slog" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" +) + +type itHTTP struct { + database *itDatabase + server *WebServer + handler http.Handler +} + +func newITHTTP(t *testing.T) itHTTP { + t.Helper() + d := newITDatabase(t, itOptions{prefix: "http_"}) + db, tables := d.migrated(t) + s := newWebServer(d.config(t), discardLogger(), db, tables, func() time.Time { return webNow }) + s.hashPassword = func(password string) (string, error) { return fakeHash(password), nil } + s.verifyPassword = func(password, hash string) bool { return fakeHash(password) == hash } + s.store = itCommitGateStore{s.store} + return itHTTP{d, s, s.Handler()} +} + +func (it itHTTP) createUser(t *testing.T, username, role string) userRow { + t.Helper() + u, err := newUserStore(it.server.db, it.server.tables).CreateUser(t.Context(), username, role, fakeHash(testPassword), webNow) + if err != nil { + t.Fatal(err) + } + return u +} + +func (it itHTTP) token(t *testing.T, user userRow) string { + t.Helper() + token, hash, err := newSessionToken(it.server.random) + if err != nil { + t.Fatal(err) + } + session := newSessionRow(hash, user.ID, webNow, it.server.cfg.SessionMaxAge, "192.0.2.1", "") + if err := newSessionStore(it.server.db, it.server.tables).CreateSession(t.Context(), session); err != nil { + t.Fatal(err) + } + return token +} + +func (it itHTTP) do(ctx context.Context, req webRequest) *httptest.ResponseRecorder { + r := httptest.NewRequestWithContext(ctx, req.method, req.path, strings.NewReader(req.body)) + r.RemoteAddr = "192.0.2.1:12345" + if req.ctype != "" { + r.Header.Set("Content-Type", req.ctype) + } else if req.body != "" { + r.Header.Set("Content-Type", "application/json") + } + if req.token != "" { + r.AddCookie(sessionCookie(req.token, false)) + } + w := httptest.NewRecorder() + it.handler.ServeHTTP(w, r) + return w +} + +func (it itHTTP) audit(t *testing.T, operation string, status int, actor userRow) auditRow { + t.Helper() + rows, err := newAuditStore(it.server.db, it.server.tables).ListAudit(t.Context(), auditFilter{Operation: operation, Limit: 20}) + if err != nil || len(rows) != 1 { + t.Fatalf("%s audit: got %d rows, want 1, error %v", operation, len(rows), err) + } + e := rows[0] + if !e.Status.Valid || e.Status.Int64 != int64(status) || !e.UserID.Valid || e.UserID.Int64 != actor.ID || + e.Actor != actor.Username || !e.Time.Equal(webNow) || e.Origin != "192.0.2.1" || e.Error.Valid != (status >= 400) { + t.Fatalf("%s audit: %+v", operation, e) + } + if status >= 400 && (e.Before != nil || e.After != nil) { + t.Fatalf("%s failure has snapshots: %+v", operation, e) + } + return e +} + +type itCommitGateKey struct{} + +type itCommitGate struct { + reached chan struct{} + release chan struct{} +} + +type itCommitGateStore struct{ webStore } + +func (s itCommitGateStore) InTx(ctx context.Context, fn func(webTx) error) error { + return s.webStore.InTx(ctx, itGateCommit(ctx, fn)) +} + +func (s itCommitGateStore) InZoneTx(ctx context.Context, zone string, log *slog.Logger, fn func(webTx) error) error { + return s.webStore.InZoneTx(ctx, zone, log, itGateCommit(ctx, fn)) +} + +func itGateCommit(ctx context.Context, fn func(webTx) error) func(webTx) error { + gate, ok := ctx.Value(itCommitGateKey{}).(*itCommitGate) + if !ok { + return fn + } + return func(tx webTx) error { + if err := fn(tx); err != nil { + return err + } + close(gate.reached) + select { + case <-gate.release: + return nil + case <-ctx.Done(): + return ctx.Err() + } + } +} + +func (it itHTTP) race(t *testing.T, first, second webRequest, firstStatus, secondStatus int) (*httptest.ResponseRecorder, *httptest.ResponseRecorder) { + t.Helper() + ctx, cancel := context.WithTimeout(t.Context(), 8*time.Second) + defer cancel() + gate := &itCommitGate{make(chan struct{}), make(chan struct{})} + a := make(chan *httptest.ResponseRecorder, 1) + b := make(chan *httptest.ResponseRecorder, 1) + go func() { a <- it.do(context.WithValue(ctx, itCommitGateKey{}, gate), first) }() + select { + case <-gate.reached: + case w := <-a: + t.Fatalf("first request stopped before commit: %d %s", w.Code, w.Body) + case <-ctx.Done(): + t.Fatal("first request did not reach its commit") + } + go func() { b <- it.do(ctx, second) }() + tick := time.NewTicker(20 * time.Millisecond) + defer tick.Stop() + for { + var waiting bool + err := it.database.root.QueryRowContext(ctx, "SELECT EXISTS (SELECT 1 FROM performance_schema.data_lock_waits w "+ + "JOIN performance_schema.data_locks l ON l.ENGINE = w.ENGINE AND l.ENGINE_LOCK_ID = w.REQUESTING_ENGINE_LOCK_ID "+ + "WHERE l.OBJECT_SCHEMA = ? AND l.OBJECT_NAME = ?)", + it.database.name, it.database.prefix+"webui_users").Scan(&waiting) + if err != nil { + t.Fatalf("observe user lock: %v", err) + } + if waiting { + break + } + select { + case w := <-b: + t.Fatalf("second request did not wait on the users table: %d %s", w.Code, w.Body) + case <-ctx.Done(): + t.Fatal("second request did not reach a user row lock") + case <-tick.C: + } + } + close(gate.release) + receive := func(ch <-chan *httptest.ResponseRecorder, status int) *httptest.ResponseRecorder { + select { + case w := <-ch: + if w.Code != status { + t.Fatalf("request status = %d, want %d, body %s", w.Code, status, w.Body) + } + return w + case <-ctx.Done(): + t.Fatal("request did not finish") + return nil + } + } + return receive(a, firstStatus), receive(b, secondStatus) +} + +func TestIntegrationPasswordRaces(t *testing.T) { + const resetPassword = "admin-reset-password" + for _, scenario := range []string{"login_reset", "login_delete", "own_change_reset"} { + for _, accountFirst := range []bool{true, false} { + t.Run(fmt.Sprintf("%s/account_first_%t", scenario, accountFirst), func(t *testing.T) { + it := newITHTTP(t) + admin := it.createUser(t, "admin", roleAdmin) + user := it.createUser(t, "alice", roleUser) + token := it.token(t, user) + it.token(t, user) + adminToken := it.token(t, admin) + account := webRequest{method: "POST", path: "/login", ctype: "application/x-www-form-urlencoded", body: loginForm(user.Username, testPassword, "")} + accountOp, accountStatus, rejected := opLogin, http.StatusSeeOther, http.StatusUnauthorized + mutation := webRequest{method: "PUT", path: apiPrefix + "/users/alice/password", token: adminToken, body: `{"password":"admin-reset-password"}`} + mutationOp, finalPassword := opUserPassword, resetPassword + deleteUser := scenario == "login_delete" + if deleteUser { + mutation = webRequest{method: "DELETE", path: apiPrefix + "/users/alice", token: adminToken, body: `{"confirm":"alice"}`} + mutationOp, finalPassword = opUserDelete, testPassword + } + if scenario == "own_change_reset" { + account = webRequest{method: "PUT", path: apiPrefix + "/account/password", token: token, body: `{"current":"secret-password","password":"own-new-password"}`} + accountOp, accountStatus, rejected = opPasswordChange, http.StatusNoContent, http.StatusConflict + } + var response *httptest.ResponseRecorder + if accountFirst { + response, _ = it.race(t, account, mutation, accountStatus, http.StatusNoContent) + } else { + _, response = it.race(t, mutation, account, http.StatusNoContent, rejected) + accountStatus = rejected + } + ctx := t.Context() + stored, err := newUserStore(it.server.db, it.server.tables).UserByID(ctx, user.ID) + if err != nil || stored.PasswordHash != fakeHash(finalPassword) || stored.DeletedAt.Valid != deleteUser || + stored.LastLoginAt.Valid != (accountOp == opLogin && accountFirst) { + t.Fatalf("unexpected winning account state: hash match %t, deleted %t, login %t, error %v", + stored.PasswordHash == fakeHash(finalPassword), stored.DeletedAt.Valid, stored.LastLoginAt.Valid, err) + } + if n := it.database.count(t, it.server.tables.sql("SELECT COUNT(*) FROM {sessions} WHERE user_id = ?"), user.ID); n != 0 { + t.Fatalf("the revoked user has %d surviving sessions", n) + } + cookies := response.Header().Values("Set-Cookie") + if (len(cookies) == 1) != (accountOp == opLogin && accountFirst) { + t.Fatalf("unexpected number of cookies: %d", len(cookies)) + } + a := it.audit(t, accountOp, accountStatus, user) + m := it.audit(t, mutationOp, http.StatusNoContent, admin) + if (a.ID < m.ID) != accountFirst || m.TargetUserID != (sql.NullInt64{Int64: user.ID, Valid: true}) { + t.Fatalf("unexpected audit sequence or mutation target: %+v %+v", a, m) + } + if !accountFirst { + want := msgInvalidLogin + if accountOp == opPasswordChange { + want = msgPasswordChanged + } + if a.Error.String != want { + t.Fatalf("unexpected rejection audit: %+v", a) + } + } + }) + } + } +} + +func TestIntegrationAdminMutationAuthorizationRaces(t *testing.T) { + for _, operation := range []string{opDelegationGrant, opDelegationRevoke, opUserPassword} { + for _, actorOp := range []string{opUserRole, opUserDelete} { + for _, writeFirst := range []bool{true, false} { + t.Run(fmt.Sprintf("%s/%s/write_first_%t", operation, actorOp, writeFirst), func(t *testing.T) { + it := newITHTTP(t) + keeper := it.createUser(t, "keeper", roleAdmin) + actor := it.createUser(t, "actor", roleAdmin) + target := it.createUser(t, "target", roleUser) + targetToken := it.token(t, target) + write := webRequest{method: "PUT", path: apiPrefix + "/zones/" + testZone + "/users/target", token: it.token(t, actor)} + delegations := newDelegationStore(it.server.db, it.server.tables) + ctx := t.Context() + if operation == opUserPassword { + write.path = apiPrefix + "/users/target/password" + write.body = `{"password":"target-new-password"}` + } else { + records := newRecordStore(it.server.db, it.server.tables) + _, err := records.InsertRecord(ctx, recordRow{Zone: testZone, Name: "www", TTL: sql.NullInt64{Int64: 3600, Valid: true}, + Content: sql.NullString{String: `{"ip":"192.0.2.1"}`, Valid: true}, RecordType: "A"}) + if err != nil { + t.Fatal(err) + } + if operation == opDelegationRevoke { + write.method = "DELETE" + if created, err := delegations.GrantDelegation(ctx, testZone, target.ID, keeper.ID, webNow); !created || err != nil { + t.Fatalf("seed delegation: %t, %v", created, err) + } + } + } + changeActor := webRequest{method: "PUT", path: apiPrefix + "/users/actor/role", token: it.token(t, keeper), body: `{"role":"user"}`} + if actorOp == opUserDelete { + changeActor.method, changeActor.path, changeActor.body = "DELETE", apiPrefix+"/users/actor", `{"confirm":"actor"}` + } + writeStatus := http.StatusNoContent + if writeFirst { + it.race(t, write, changeActor, writeStatus, http.StatusNoContent) + } else { + writeStatus = http.StatusForbidden + _, response := it.race(t, changeActor, write, http.StatusNoContent, writeStatus) + if response.Body.String() != `{"error":"admin role required"}` { + t.Fatalf("refusal body: %s", response.Body) + } + } + guard := it.audit(t, actorOp, http.StatusNoContent, keeper) + entry := it.audit(t, operation, writeStatus, actor) + if (entry.ID < guard.ID) != writeFirst || entry.TargetUserID != (sql.NullInt64{Int64: target.ID, Valid: true}) || + guard.TargetUserID != (sql.NullInt64{Int64: actor.ID, Valid: true}) { + t.Fatalf("unexpected audit order or target: %+v %+v", entry, guard) + } + users := newUserStore(it.server.db, it.server.tables) + storedActor, err := users.UserByID(ctx, actor.ID) + deleted := actorOp == opUserDelete + if err != nil || storedActor.DeletedAt.Valid != deleted || (storedActor.Role == roleAdmin) != deleted { + t.Fatalf("actor status: role %s, deleted %t, error %v", storedActor.Role, storedActor.DeletedAt.Valid, err) + } + if operation == opUserPassword { + stored, err := users.UserByID(ctx, target.ID) + wantPassword, wantSessions := testPassword, 1 + if writeFirst { + wantPassword, wantSessions = "target-new-password", 0 + } + if err != nil || stored.PasswordHash != fakeHash(wantPassword) { + t.Fatalf("target password has wrong state, error %v", err) + } + if n := it.database.count(t, it.server.tables.sql("SELECT COUNT(*) FROM {sessions} WHERE user_id = ?"), target.ID); n != wantSessions { + t.Fatalf("target session count %d, want %d", n, wantSessions) + } + if !writeFirst && it.do(ctx, webRequest{method: "GET", path: apiPrefix + "/account", token: targetToken}).Code != http.StatusOK { + t.Fatal("target session was revoked by refused password reset") + } + } else { + exists, err := delegations.HasDelegation(ctx, testZone, target.ID) + if err != nil || exists != (writeFirst == (operation == opDelegationGrant)) || entry.Zone.String != testZone { + t.Fatalf("delegation state %t, audit zone %v, error %v", exists, entry.Zone, err) + } + } + }) + } + } + } +} + +func TestIntegrationUserCreateAuditRollback(t *testing.T) { + it := newITHTTP(t) + admin := it.createUser(t, "admin", roleAdmin) + tn := it.server.tables + it.database.rootExec(t, tn.sql("CREATE TRIGGER fail_create_audit BEFORE INSERT ON {audit} FOR EACH ROW "+ + "BEGIN IF NEW.operation = 'user_create' AND NEW.status = 201 THEN "+ + "SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'forced success audit failure'; END IF; END")) + response := it.do(t.Context(), webRequest{method: "POST", path: apiPrefix + "/users", token: it.token(t, admin), + body: `{"username":"newbie","role":"user","password":"long-enough-password"}`}) + if response.Code != http.StatusInternalServerError || response.Body.String() != `{"error":"internal error"}` { + t.Fatalf("user creation: %d %s", response.Code, response.Body) + } + if n := it.database.count(t, tn.sql("SELECT COUNT(*) FROM {users} WHERE username = 'newbie'")); n != 0 { + t.Fatal("user creation survived a failed audit insert") + } + entry := it.audit(t, opUserCreate, http.StatusInternalServerError, admin) + if entry.TargetUserID.Valid || entry.Error.String != msgInternalError { + t.Fatalf("failure audit retained rolled-back data: %+v", entry) + } +} diff --git a/integration_stores_test.go b/integration_stores_test.go index 215ac48..a62ea98 100644 --- a/integration_stores_test.go +++ b/integration_stores_test.go @@ -9,6 +9,8 @@ import ( "context" "database/sql" "errors" + "slices" + "sync" "testing" "time" ) @@ -274,6 +276,46 @@ func TestIntegrationSessionStore(t *testing.T) { if !got.Session.LastSeenAt.Equal(base.Add(time.Minute)) { t.Fatal(got.Session.LastSeenAt) } + for _, stale := range []time.Time{base.Add(90 * time.Second), base.Add(time.Minute - time.Microsecond), base} { + if err := s.TouchSession(ctx, hash(1), stale); err != nil { + t.Fatal(err) + } + if got, _ = s.SessionByTokenHash(ctx, hash(1)); !got.Session.LastSeenAt.Equal(base.Add(time.Minute)) { + t.Fatalf("touch at %v moved last_seen_at to %v", stale, got.Session.LastSeenAt) + } + } + touches := make([]time.Time, 16) + for i := range touches { + touches[i] = base.Add(2*time.Minute + time.Duration(i)*time.Second) + } + var wg sync.WaitGroup + for _, at := range touches { + wg.Go(func() { + if err := s.TouchSession(ctx, hash(1), at); err != nil { + t.Error(err) + } + }) + } + wg.Wait() + got, _ = s.SessionByTokenHash(ctx, hash(1)) + first := got.Session.LastSeenAt + if !slices.ContainsFunc(touches, first.Equal) { + t.Fatalf("concurrent touches left %v", first) + } + for _, at := range touches { + if err := s.TouchSession(ctx, hash(1), at); err != nil { + t.Fatal(err) + } + } + if got, _ = s.SessionByTokenHash(ctx, hash(1)); !got.Session.LastSeenAt.Equal(first) { + t.Fatalf("an older concurrent touch moved last_seen_at from %v to %v", first, got.Session.LastSeenAt) + } + if err := s.TouchSession(ctx, hash(1), first.Add(time.Minute)); err != nil { + t.Fatal(err) + } + if got, _ = s.SessionByTokenHash(ctx, hash(1)); !got.Session.LastSeenAt.Equal(first.Add(time.Minute)) { + t.Fatal("due touch not written") + } if ok, err := s.DeleteSession(ctx, hash(2)); !ok || err != nil { t.Fatal(ok, err) } diff --git a/integration_zone_api_test.go b/integration_zone_api_test.go index 112b43d..06a2088 100644 --- a/integration_zone_api_test.go +++ b/integration_zone_api_test.go @@ -8,6 +8,7 @@ package main import ( "context" "database/sql" + "encoding/json" "errors" "fmt" "net/http" @@ -101,8 +102,19 @@ func TestIntegrationZoneAPIHandlers(t *testing.T) { } it.call(t, admin, "zone_create", "", "", zoneAPITestCreate, 409) it.call(t, user, "zone_create", "", "", zoneAPITestCreate, 403) - if !strings.Contains(string(it.audit(t, "zone_create", 1)[0].After), `"username": "bob"`) { - t.Fatal("zone creation audit omitted the stale delegation") + createdZone := it.audit(t, "zone_create", 1)[0] + var before []zoneAPIAuditDelegation + var after []zoneAPIAuditRecord + if err := json.Unmarshal(createdZone.Before, &before); err != nil || len(before) != 1 || before[0].Zone != zoneAPITestName || before[0].Username != "bob" { + t.Fatalf("zone creation before snapshot: %s (%v)", createdZone.Before, err) + } + if err := json.Unmarshal(createdZone.After, &after); err != nil || len(after) != 3 { + t.Fatalf("zone creation after snapshot: %s (%v)", createdZone.After, err) + } + for _, record := range after { + if record.ID <= 0 || record.Zone != zoneAPITestName || (record.Type != "SOA" && record.Type != "NS") { + t.Fatalf("unexpected zone creation after snapshot: %+v", record) + } } if allowed, err := it.delegations.HasDelegation(t.Context(), zoneAPITestName, user.ID); allowed || err != nil { t.Fatalf("stale delegation retained: %v, %v", allowed, err) diff --git a/logger.go b/logger.go index 12ccf84..4f50f5c 100644 --- a/logger.go +++ b/logger.go @@ -95,6 +95,22 @@ func traceFunc(ctx context.Context, log *slog.Logger, fn string) func() { } } +type traceLoggerKey struct{} + +func withTraceLogger(ctx context.Context, log *slog.Logger) context.Context { + if log.Enabled(ctx, LevelTrace) { + return context.WithValue(ctx, traceLoggerKey{}, log) + } + return ctx +} + +func traceStore(ctx context.Context, operation string) func() { + if log, ok := ctx.Value(traceLoggerKey{}).(*slog.Logger); ok { + return traceFunc(ctx, log, operation) + } + return func() {} +} + func discardLogger() *slog.Logger { return slog.New(slog.DiscardHandler) } diff --git a/middleware.go b/middleware.go index 16d9914..f0024bc 100644 --- a/middleware.go +++ b/middleware.go @@ -19,10 +19,12 @@ import ( "net" "net/http" "net/netip" + "path" "reflect" "slices" "strings" "time" + "unicode/utf8" "github.com/go-sql-driver/mysql" "github.com/gorilla/mux" @@ -61,6 +63,8 @@ type apiContext struct { Server *WebServer auditDone bool bodyLimit int64 + bodyRead bool + body []byte } type apiResponse struct { @@ -76,6 +80,7 @@ type apiError struct { Message string Fields map[string]string Extra map[string]any + Header http.Header } func (e *apiError) Error() string { return e.Message } @@ -181,13 +186,33 @@ func (c *apiContext) writeChangeAudit(ctx context.Context, tx *sql.Tx, status in 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 { + if err := insertAuditRow(ctx, ins, *c.Entry); err != nil { return err } c.auditDone = true return nil } +type auditWriteError struct { + err error +} + +func (e *auditWriteError) Error() string { return "audit write failed: " + e.err.Error() } + +func (e *auditWriteError) Unwrap() error { return e.err } + +func isAuditWriteError(err error) bool { + var auditErr *auditWriteError + return errors.As(err, &auditErr) +} + +func insertAuditRow(ctx context.Context, ins auditInserter, e auditEntry) error { + if _, err := ins.InsertAudit(ctx, e); err != nil { + return &auditWriteError{err: err} + } + return nil +} + func isJSONContentType(ct string) bool { mt, _, err := mime.ParseMediaType(ct) return err == nil && mt == "application/json" @@ -218,29 +243,55 @@ func jsonTypeMessage(e *json.UnmarshalTypeError) string { return "has the wrong type" } -func (c *apiContext) decodeJSON(dst any) error { +func requestHasBody(r *http.Request) bool { + return r.ContentLength != 0 || len(r.TransferEncoding) > 0 +} + +func (c *apiContext) readBody() error { + if c.bodyRead { + return nil + } + c.bodyRead = true + r := c.Request + if !requestHasBody(r) { + return nil + } limit := c.bodyLimit if limit <= 0 { limit = defaultBodyLimit } - body, err := io.ReadAll(io.LimitReader(c.Request.Body, limit+1)) + 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"} + } + body, err := io.ReadAll(io.LimitReader(r.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 !utf8.Valid(body) { + return &apiError{Status: http.StatusBadRequest, Message: "request body must be valid UTF-8"} + } + c.body = body + return nil +} + +func (c *apiContext) decodeJSON(dst any) error { + if err := c.readBody(); err != nil { + return err + } + trimmed := bytes.TrimLeft(c.body, " \t\r\n") + if len(trimmed) == 0 { + return &apiError{Status: http.StatusBadRequest, Message: "request body is required"} + } if trimmed[0] != '{' { return &apiError{Status: http.StatusBadRequest, Message: "request body must be a JSON object"} } - dec := json.NewDecoder(bytes.NewReader(body)) + dec := json.NewDecoder(bytes.NewReader(c.body)) dec.DisallowUnknownFields() if err := dec.Decode(dst); err != nil { var te *json.UnmarshalTypeError @@ -258,19 +309,6 @@ func (c *apiContext) decodeJSON(dst any) error { 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 { @@ -353,7 +391,8 @@ 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)) + ctx := withTraceLogger(r.Context(), s.log) + r = r.WithContext(context.WithValue(ctx, requestInfoKey{}, info)) rec := &statusRecorder{ResponseWriter: w, status: http.StatusOK} next.ServeHTTP(rec, r) level := slog.LevelInfo @@ -447,6 +486,9 @@ func (s *WebServer) authenticate(r *http.Request) (principal, error) { } func failureStatus(err error) (int, string) { + if isAuditWriteError(err) { + return http.StatusInternalServerError, msgInternalError + } if isDatabaseUnavailable(err) { return http.StatusServiceUnavailable, msgDatabaseDown } @@ -509,9 +551,8 @@ func (s *WebServer) apiRouter(handlers map[string]apiHandler) http.Handler { 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) - }) + r.SkipClean(true) + r.NotFoundHandler = s.serveUnknownAPI(http.StatusNotFound, "") byPath := map[string]map[string]apiRoute{} var paths []string for _, route := range apiRoutes { @@ -533,21 +574,32 @@ func (s *WebServer) apiRouter(handlers map[string]apiHandler) http.Handler { } served[method] = s.serveAPI(route, h) } + notAllowed := s.serveUnknownAPI(http.StatusMethodNotAllowed, allow) 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) + notAllowed(w, req) }) } return r } +func (s *WebServer) serveUnknownAPI(status int, allow string) http.HandlerFunc { + route := apiRoute{Operation: opAPIUnknown, Access: accessSession} + return s.serveAPI(route, func(ctx context.Context, c *apiContext) (apiResponse, error) { + if status == http.StatusMethodNotAllowed { + return apiResponse{}, &apiError{Status: status, Message: msgMethodNotAllowed, Header: http.Header{"Allow": {allow}}} + } + return apiResponse{}, &apiError{Status: http.StatusNotFound, Message: msgNotFound} + }) +} + func (s *WebServer) serveAPI(route apiRoute, h apiHandler) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { ctx := r.Context() + defer traceFunc(ctx, s.log, "api."+route.Operation)() p, err := s.authenticate(r) if err != nil { if errors.Is(err, errNoSession) { @@ -563,12 +615,16 @@ func (s *WebServer) serveAPI(route apiRoute, h apiHandler) http.HandlerFunc { 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 && route.BodyLimit > 0 { + err = c.readBody() } if err == nil { resp, err = h(ctx, c) } + var refusal *apiError + if route.Access == accessAdmin && errors.As(err, &refusal) && refusal.Status == http.StatusForbidden { + s.recordAddressedObjects(ctx, c, route) + } s.finishAPI(ctx, w, c, resp, err) } } @@ -601,6 +657,32 @@ func (s *WebServer) authorizeAPI(ctx context.Context, c *apiContext, route apiRo return apiResponse{}, nil } +func (s *WebServer) recordAddressedObjects(ctx context.Context, c *apiContext, route apiRoute) { + rawZone := c.Vars["zone"] + if route.Operation == opZoneCreate && c.readBody() == nil { + var request struct { + Name string `json:"name"` + } + if json.Unmarshal(c.body, &request) == nil { + rawZone = request.Name + } + } + if zone, err := normalizeZone(rawZone); err == nil { + c.Entry.Zone = sql.NullString{String: zone, Valid: true} + } + username, ok := c.Vars["username"] + if c.Entry.TargetUserID.Valid || !ok || !validUsernameSyntax(username) { + return + } + u, err := s.store.UserByUsername(ctx, username) + switch { + case err == nil: + c.Entry.TargetUserID = sql.NullInt64{Int64: u.ID, Valid: true} + case !errors.Is(err, errRowNotFound): + s.log.ErrorContext(ctx, "target user lookup failed", "operation", c.Entry.Operation, "error", err) + } +} + func (s *WebServer) errorResponse(ctx context.Context, c *apiContext, err error) (apiResponse, string) { var ae *apiError switch { @@ -619,7 +701,7 @@ func (s *WebServer) errorResponse(ctx context.Context, c *apiContext, err error) 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 + return apiResponse{Status: ae.Status, Body: body, Header: ae.Header}, 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 @@ -666,6 +748,24 @@ func (s *WebServer) insertAudit(ctx context.Context, e auditEntry) error { return err } +func (s *WebServer) recordAudit(ctx context.Context, e auditEntry) bool { + err := s.insertAudit(ctx, e) + if err == nil { + return true + } + s.log.ErrorContext(ctx, "audit insert failed", "operation", e.Operation, "status", e.Status.Int64, "error", err) + s.recordInternalAudit(ctx, e) + return false +} + +func (s *WebServer) recordInternalAudit(ctx context.Context, e auditEntry) { + e.Before, e.After = nil, nil + finishAuditEntry(&e, http.StatusInternalServerError, msgInternalError) + if err := s.insertAudit(ctx, e); err != nil { + s.log.ErrorContext(ctx, "audit insert of the internal error failed", "operation", e.Operation, "error", err) + } +} + func (s *WebServer) finishAPI(ctx context.Context, w http.ResponseWriter, c *apiContext, resp apiResponse, err error) { message := "" if err != nil { @@ -680,11 +780,13 @@ func (s *WebServer) finishAPI(ctx context.Context, w http.ResponseWriter, c *api 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 if isAuditWriteError(err) { + s.recordInternalAudit(ctx, *c.Entry) + out = internalErrorResponse() } 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) + if !s.recordAudit(ctx, *c.Entry) { out = internalErrorResponse() } } @@ -702,6 +804,35 @@ func (s *WebServer) finishAPI(ctx context.Context, w http.ResponseWriter, c *api } } +func cleanPagePath(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if !isAPIPath(r.URL.Path) { + if p := cleanURLPath(r.URL.Path); p != r.URL.Path { + u := *r.URL + u.Path = p + w.Header().Set("Location", u.String()) + w.WriteHeader(http.StatusMovedPermanently) + return + } + } + next.ServeHTTP(w, r) + }) +} + +func cleanURLPath(p string) string { + if p == "" { + return "/" + } + if p[0] != '/' { + p = "/" + p + } + np := path.Clean(p) + if p[len(p)-1] == '/' && np != "/" { + np += "/" + } + return np +} + 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 index ec6eca4..4527afe 100644 --- a/middleware_test.go +++ b/middleware_test.go @@ -4,12 +4,15 @@ package main import ( + "bytes" "context" "database/sql" "database/sql/driver" "encoding/json" "errors" "fmt" + "io" + "log/slog" "net" "net/http" "net/http/httptest" @@ -51,7 +54,10 @@ func TestDecodeJSON(t *testing.T) { {`{"name":"a"}`, "application/json; charset=utf-8", 0, 0, "", ""}, {" \n{} \n", "application/json", 0, 0, "", ""}, {"", "application/json", 0, 400, "request body is required", ""}, - {" ", "", 0, 400, "request body is required", ""}, + {" ", "", 0, 415, "content type must be application/json", ""}, + {" ", "application/json", 0, 400, "request body is required", ""}, + {strings.Repeat(" ", 70000), "application/json", 0, 413, "request body too large", ""}, + {"{\"name\":\"\xff\"}", "application/json", 0, 400, "request body must be valid UTF-8", ""}, {`{"name":"a"}`, "text/plain", 0, 415, "content type must be application/json", ""}, {`{"name":"a"}`, "", 0, 415, "content type must be application/json", ""}, {`{"name":"a"}`, "application/jsonx", 0, 415, "content type must be application/json", ""}, @@ -267,11 +273,20 @@ func TestCrossOriginProtection(t *testing.T) { func TestAPIRouterNotFoundAndMethods(t *testing.T) { h := newWebHarness(t) token := h.login(h.user("admin", roleAdmin)) - for _, p := range []string{"/api/v1/nothing", "/api/v1/", "/api/v2/account", "/api/v1/zones/a/b/c/d/e", "/api/v1/account/password/x"} { + for _, p := range []string{"/api/v1/nothing", "/api/v1/", "/api/v2/account", "/api/v1/zones/a/b/c/d/e", "/api/v1/account/password/x", + "/api/v1//account", "/api/v1/account/../users", "/api/v1/./account"} { res := h.do(webRequest{method: "GET", path: p, token: token}) - if res.status != 404 || res.body != `{"error":"not found"}` || res.header.Get("Content-Type") != "application/json" || len(res.audit) != 0 { + if res.status != 404 || res.body != `{"error":"not found"}` || res.header.Get("Content-Type") != "application/json" { t.Errorf("%s: %d %s", p, res.status, res.body) } + e := expectOneAudit(t, res, opAPIUnknown, 404) + if e.Error.String != msgNotFound || e.Actor != "admin" || e.UserID.Int64 != 1 || e.Zone.Valid || e.TargetUserID.Valid || e.Before != nil || e.After != nil { + t.Errorf("%s: audit %+v", p, e) + } + res = h.do(webRequest{method: "GET", path: p}) + if res.status != 401 || res.body != `{"error":"authentication required"}` || len(res.audit) != 0 { + t.Errorf("%s without session: %d %s %d", p, res.status, res.body, len(res.audit)) + } } cases := map[string]string{ "PATCH /api/v1/account": "GET", @@ -287,12 +302,19 @@ func TestAPIRouterNotFoundAndMethods(t *testing.T) { for req, allow := range cases { method, path, _ := strings.Cut(req, " ") res := h.do(webRequest{method: method, path: path, token: token}) - if res.status != 405 || res.header.Get("Allow") != allow || len(res.audit) != 0 { + if res.status != 405 || res.header.Get("Allow") != allow { t.Errorf("%s: %d %q", req, res.status, res.header.Get("Allow")) } + if e := expectOneAudit(t, res, opAPIUnknown, 405); e.Error.String != msgMethodNotAllowed { + t.Errorf("%s: audit %+v", req, e) + } if method != "HEAD" && res.body != `{"error":"method not allowed"}` { t.Errorf("%s: %s", req, res.body) } + res = h.do(webRequest{method: method, path: path}) + if res.status != 401 || len(res.audit) != 0 { + t.Errorf("%s without session: %d %d", req, res.status, len(res.audit)) + } } } @@ -558,20 +580,44 @@ func TestAdminRouteRefusedBeforeZone(t *testing.T) { alice := h.user("alice", roleUser) h.store.delegate(testZone, alice) token := h.login(alice) - for _, r := range []struct{ method, path, op string }{ - {"GET", "/zones/example.org./users", opDelegationList}, - {"DELETE", "/zones/bad!/users/x", opDelegationRevoke}, - {"POST", "/zones", opZoneCreate}, - {"GET", "/users", opUserList}, + bob := h.user("bob", roleUser) + for _, r := range []struct { + method, path, op, zone string + target int64 + }{ + {"GET", "/zones/Example.ORG/users", opDelegationList, testZone, 0}, + {"DELETE", "/zones/bad!/users/x", opDelegationRevoke, "", 0}, + {"PUT", "/zones/example.org./users/bob", opDelegationGrant, testZone, bob.ID}, + {"PUT", "/zones/missing.example/users/nobody", opDelegationGrant, "missing.example.", 0}, + {"POST", "/zones", opZoneCreate, "", 0}, + {"GET", "/users", opUserList, "", 0}, + {"GET", "/users/bob", opUserRead, "", bob.ID}, + {"GET", "/users/nobody", opUserRead, "", 0}, + {"GET", "/users/Bad!", opUserRead, "", 0}, } { res := h.api(r.method, r.path, token, "") if res.status != 403 || res.body != `{"error":"admin role required"}` { t.Fatalf("%s: %d %s", r.path, res.status, res.body) } - if e := expectOneAudit(t, res, r.op, 403); e.Zone.Valid { - t.Fatal("zone recorded for a refused admin route") + e := expectOneAudit(t, res, r.op, 403) + if e.Zone.Valid != (r.zone != "") || e.Zone.String != r.zone || e.TargetUserID.Valid != (r.target != 0) || e.TargetUserID.Int64 != r.target { + t.Fatalf("%s: audit zone %+v target %+v", r.path, e.Zone, e.TargetUserID) } } + res := h.api("POST", "/zones", token, `{"name":"Unlisted.EXAMPLE","ns":"ns.example.com."}`) + expectError(t, res, 403, `{"error":"admin role required"}`) + if e := expectOneAudit(t, res, opZoneCreate, 403); !e.Zone.Valid || e.Zone.String != "unlisted.example." { + t.Fatalf("refused create zone: %+v", e.Zone) + } + missing := h.api("GET", "/users/nobody", token, "") + existing := h.api("GET", "/users/bob", token, "") + if missing.status != existing.status || missing.body != existing.body { + t.Fatal("refusal reveals whether the user exists") + } + h.store.failOn["UserByUsername"] = errDatabase + if res := h.api("GET", "/users/bob", token, ""); res.status != 403 || !expectOneAudit(t, res, opUserRead, 403).UserID.Valid { + t.Fatal("target lookup failure changed the refusal") + } } func TestBodyPrecheck(t *testing.T) { @@ -719,3 +765,155 @@ func TestIsAPIPath(t *testing.T) { t.Fatal("isDatabaseUnavailable") } } + +func TestAPIBodyFraming(t *testing.T) { + h := newWebHarness(t) + alice := h.user("alice", roleUser) + token := h.login(alice) + for _, chunked := range []bool{false, true} { + for _, c := range []struct { + method, path, body, ctype, op, want string + status int + }{ + {"GET", "/account", `{"x":1}`, "text/plain", opAccountRead, `{"error":"content type must be application/json"}`, 415}, + {"GET", "/account", strings.Repeat(" ", 70000), "application/json", opAccountRead, `{"error":"request body too large"}`, 413}, + {"GET", "/account", "{\"x\":\"\xff\"}", "application/json", opAccountRead, `{"error":"request body must be valid UTF-8"}`, 400}, + {"PUT", "/account/password", strings.Repeat(" ", 70000), "application/json", opPasswordChange, `{"error":"request body too large"}`, 413}, + {"PUT", "/account/password", " \n\t ", "application/json", opPasswordChange, `{"error":"request body is required"}`, 400}, + {"PUT", "/account/password", "{\"current\":\"secret-password\",\"password\":\"\xffvalid-looking-pw\"}", "application/json", opPasswordChange, `{"error":"request body must be valid UTF-8"}`, 400}, + } { + res := h.do(webRequest{method: c.method, path: apiPrefix + c.path, token: token, body: c.body, ctype: c.ctype, chunked: chunked}) + if res.status != c.status || res.body != c.want { + t.Errorf("chunked %v %s %s: %d %s", chunked, c.method, c.path, res.status, res.body) + continue + } + expectOneAudit(t, res, c.op, c.status) + } + } + if h.store.user(alice.ID).PasswordHash != fakeHash(testPassword) { + t.Fatal("password changed") + } + srv := httptest.NewServer(h.handler) + defer srv.Close() + for _, c := range []struct { + body io.Reader + status int + }{ + {io.MultiReader(strings.NewReader(`{"x":1}`)), 415}, + {io.MultiReader(strings.NewReader(strings.Repeat(" ", 70000))), 413}, + {strings.NewReader(`{"x":1}`), 415}, + } { + req, err := http.NewRequest("GET", srv.URL+apiPrefix+"/account", c.body) + if err != nil { + t.Fatal(err) + } + req.Header.Set("Content-Type", "text/plain") + if c.status == 413 { + req.Header.Set("Content-Type", "application/json") + } + req.AddCookie(&http.Cookie{Name: sessionCookieName, Value: token}) + resp, err := srv.Client().Do(req) + if err != nil { + t.Fatal(err) + } + resp.Body.Close() + if resp.StatusCode != c.status { + t.Errorf("server: %d, want %d", resp.StatusCode, c.status) + } + } +} + +func TestUnknownAPIPathRefusedCrossOrigin(t *testing.T) { + h := newWebHarness(t) + token := h.login(h.user("admin", roleAdmin)) + res := h.do(webRequest{method: "POST", path: "/api/v1/nothing", token: token, body: `{}`, header: map[string]string{"Sec-Fetch-Site": "cross-site"}}) + if res.status != 403 || res.body != `{"error":"cross-origin request refused"}` || len(res.audit) != 0 { + t.Fatalf("%d %s %d", res.status, res.body, len(res.audit)) + } +} + +func TestPagePathCleaning(t *testing.T) { + h := newWebHarness(t) + res := h.do(webRequest{method: "GET", path: "/zones/../audit?x=1"}) + if res.status != 301 || res.header.Get("Location") != "/audit?x=1" { + t.Fatalf("%d %v", res.status, res.header) + } + for in, want := range map[string]string{"": "/", "a": "/a", "/a/b/": "/a/b/", "/a/../": "/", "//a": "/a"} { + if got := cleanURLPath(in); got != want { + t.Errorf("%q: %q", in, got) + } + } +} + +func TestZoneTxLockReleaseFailureKeepsTheCommittedChange(t *testing.T) { + token, tokenHash, err := newSessionToken(strings.NewReader(strings.Repeat("k", 32))) + if err != nil { + t.Fatal(err) + } + userValues := func(id int64, username, role string) []driver.Value { + return []driver.Value{id, username, role, fakeHash(testPassword), webNow, webNow, nil, nil} + } + session := append(userValues(1, "admin", roleAdmin), tokenHash, int64(1), webNow, webNow, webNow.Add(time.Hour), "192.0.2.1", "test") + db, st := newFakeDB(t, fdbRules( + fdbRule{"SELECT GET_LOCK", fdbResponse{rows: fdbRow(int64(1))}}, + fdbRule{"SELECT RELEASE_LOCK", fdbResponse{err: errors.New("connection lost")}}, + fdbRule{"x.`token_hash` = ?", fdbResponse{rows: [][]driver.Value{session}}}, + fdbRule{"ORDER BY u.`id` FOR UPDATE", fdbResponse{rows: [][]driver.Value{userValues(1, "admin", roleAdmin)}}}, + fdbRule{"SELECT 1 FROM `coredns_records`", fdbResponse{rows: fdbRow(int64(1))}}, + fdbRule{"u.`username` = ? FOR UPDATE", fdbResponse{rows: [][]driver.Value{userValues(2, "bob", roleUser)}}}, + fdbRule{"INSERT INTO `coredns_webui_audit`", fdbResponse{lastInsertID: 1, rowsAffected: 1}}, + )) + var logs bytes.Buffer + s := newWebServer(Config{CookieSecure: true, SessionIdleTimeout: time.Hour, SessionMaxAge: 12 * time.Hour}, newLogger(&logs, slog.LevelDebug), db, fdbTables(t), func() time.Time { return webNow }) + r := httptest.NewRequest("PUT", "/api/v1/zones/example.org./users/bob", nil) + r.RemoteAddr = "192.0.2.1:1234" + r.AddCookie(&http.Cookie{Name: sessionCookieName, Value: token}) + w := httptest.NewRecorder() + s.Handler().ServeHTTP(w, r) + if w.Code != 204 { + t.Fatalf("%d %s", w.Code, w.Body.String()) + } + var audits, grants int + for _, c := range st.Calls() { + switch { + case strings.HasPrefix(c.query, "INSERT INTO `coredns_webui_audit`"): + audits++ + if c.args[4] != opDelegationGrant || c.args[5] != int64(204) || c.args[6] != nil { + t.Fatalf("audit row %v", c.args) + } + case strings.HasPrefix(c.query, "INSERT INTO `coredns_webui_zone_delegations`"): + grants++ + } + } + if audits != 1 || grants != 1 || st.commits != 1 || st.rollbacks != 0 { + t.Fatalf("audits %d grants %d commits %d rollbacks %d", audits, grants, st.commits, st.rollbacks) + } + if !strings.Contains(logs.String(), "named lock release failed, discarding the connection") || !strings.Contains(logs.String(), `msg="change committed" operation=delegation_grant`) { + t.Fatal(logs.String()) + } +} + +func TestHandlerTraceHasNoSecrets(t *testing.T) { + h := newWebHarness(t) + alice := h.user("alice", roleUser) + res := h.postLogin(loginForm("alice", testPassword, ""), "") + token := responseCookie(t, res).Value + h.api("GET", "/account", token, "") + h.api("PUT", "/account/password", token, `{"current":"secret-password","password":"brand-new-password"}`) + h.do(webRequest{method: "GET", path: "/audit", token: token}) + out := h.logs.String() + for _, want := range []string{ + `level=TRACE msg="function entry" func=page.login.post`, `level=TRACE msg="function exit" func=page.login.post`, + `level=TRACE msg="function entry" func=api.account_read`, `level=TRACE msg="function exit" func=api.password_change`, + `level=TRACE msg="function entry" func=page.audit`, + } { + if !strings.Contains(out, want) { + t.Errorf("trace lacks %q", want) + } + } + for _, secret := range []string{testPassword, "brand-new-password", token, fakeHash(testPassword), h.store.user(alice.ID).PasswordHash} { + if strings.Contains(out, secret) { + t.Fatalf("logs contain a secret %q", secret) + } + } +} diff --git a/migrations.go b/migrations.go index 5ccd195..7277553 100644 --- a/migrations.go +++ b/migrations.go @@ -110,10 +110,112 @@ func migrateDatabase(ctx context.Context, db connSource, t tableNames, log *slog return err } return withNamedLock(ctx, db, t.migrateLockName(), migrateLockTimeout, log, func(conn *sql.Conn) error { - return applyMigrations(ctx, conn, t, migrations, log) + if err := applyMigrations(ctx, conn, t, migrations, log); err != nil { + return err + } + return verifyAppSchema(ctx, conn, t, log) }) } +type schemaColumn struct { + table string + column string + columnType string +} + +var appSchema = []schemaColumn{ + {"webui_schema", "id", "tinyint"}, + {"webui_schema", "version", "int"}, + {"webui_users", "id", "int"}, + {"webui_users", "username", "varchar(64)"}, + {"webui_users", "role", "varchar(8)"}, + {"webui_users", "password_hash", "varchar(255)"}, + {"webui_users", "created_at", "datetime(6)"}, + {"webui_users", "updated_at", "datetime(6)"}, + {"webui_users", "last_login_at", "datetime(6)"}, + {"webui_users", "deleted_at", "datetime(6)"}, + {"webui_sessions", "token_hash", "binary(32)"}, + {"webui_sessions", "user_id", "int"}, + {"webui_sessions", "created_at", "datetime(6)"}, + {"webui_sessions", "last_seen_at", "datetime(6)"}, + {"webui_sessions", "expires_at", "datetime(6)"}, + {"webui_sessions", "origin", "varchar(45)"}, + {"webui_sessions", "user_agent", "varchar(255)"}, + {"webui_zone_delegations", "zone", "varchar(255)"}, + {"webui_zone_delegations", "user_id", "int"}, + {"webui_zone_delegations", "created_at", "datetime(6)"}, + {"webui_zone_delegations", "created_by", "int"}, + {"webui_audit", "id", "bigint"}, + {"webui_audit", "time", "datetime(6)"}, + {"webui_audit", "user_id", "int"}, + {"webui_audit", "actor", "varchar(64)"}, + {"webui_audit", "origin", "varchar(45)"}, + {"webui_audit", "operation", "varchar(32)"}, + {"webui_audit", "status", "smallint"}, + {"webui_audit", "error", "varchar(255)"}, + {"webui_audit", "zone", "varchar(255)"}, + {"webui_audit", "record_id", "int"}, + {"webui_audit", "target_user_id", "int"}, + {"webui_audit", "before_value", "json"}, + {"webui_audit", "after_value", "json"}, +} + +var appTables = []string{"webui_schema", "webui_users", "webui_sessions", "webui_zone_delegations", "webui_audit"} + +func verifyAppSchema(ctx context.Context, q dbtx, t tableNames, log *slog.Logger) error { + args := make([]any, len(appTables)) + for i, name := range appTables { + args[i] = t.prefix + name + } + rows, err := q.QueryContext(ctx, "SELECT TABLE_NAME, COLUMN_NAME, COLUMN_TYPE FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME IN (?, ?, ?, ?, ?)", args...) + if err != nil { + return fmt.Errorf("read application schema: %w", err) + } + defer rows.Close() + found := map[string]string{} + for rows.Next() { + var table, column, columnType string + if err := rows.Scan(&table, &column, &columnType); err != nil { + return fmt.Errorf("read application schema: %w", err) + } + found[strings.ToLower(table)+"."+strings.ToLower(column)] = strings.ToLower(columnType) + } + if err := rows.Err(); err != nil { + return fmt.Errorf("read application schema: %w", err) + } + for _, c := range appSchema { + table := t.prefix + c.table + got, ok := found[strings.ToLower(table)+"."+c.column] + if !ok { + return fmt.Errorf("application schema: table %s has no column %s", table, c.column) + } + if got != c.columnType { + return fmt.Errorf("application schema: column %s of table %s has type %s, expected %s", c.column, table, got, c.columnType) + } + } + if err := verifyAppForeignKeys(ctx, q, t); err != nil { + return err + } + log.DebugContext(ctx, "application schema verified") + return nil +} + +func verifyAppForeignKeys(ctx context.Context, q dbtx, t tableNames) error { + var n int + err := q.QueryRowContext(ctx, "SELECT COUNT(DISTINCT TABLE_NAME, COLUMN_NAME) FROM information_schema.KEY_COLUMN_USAGE "+ + "WHERE TABLE_SCHEMA = DATABASE() AND REFERENCED_TABLE_SCHEMA = DATABASE() AND REFERENCED_TABLE_NAME = ? AND REFERENCED_COLUMN_NAME = 'id' "+ + "AND ((TABLE_NAME = ? AND COLUMN_NAME = 'user_id') OR (TABLE_NAME = ? AND COLUMN_NAME IN ('user_id', 'created_by')) "+ + "OR (TABLE_NAME = ? AND COLUMN_NAME IN ('user_id', 'target_user_id')))", + t.prefix+"webui_users", t.prefix+"webui_sessions", t.prefix+"webui_zone_delegations", t.prefix+"webui_audit").Scan(&n) + if err != nil { + return fmt.Errorf("read application foreign keys: %w", err) + } + if n != 5 { + return fmt.Errorf("application schema: expected 5 foreign keys to %swebui_users.id, found %d", t.prefix, n) + } + return nil +} + func schemaVersion(ctx context.Context, q dbtx, t tableNames) (int, error) { var count int if err := q.QueryRowContext(ctx, diff --git a/migrations/001_initial.sql b/migrations/001_initial.sql index 15cb874..c205ae4 100644 --- a/migrations/001_initial.sql +++ b/migrations/001_initial.sql @@ -8,7 +8,7 @@ CREATE TABLE IF NOT EXISTS `{prefix}webui_schema` ( CHECK (`id` = 1) ) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci; -CREATE TABLE `{prefix}webui_users` ( +CREATE TABLE IF NOT EXISTS `{prefix}webui_users` ( `id` INT NOT NULL AUTO_INCREMENT, `username` VARCHAR(64) NOT NULL, `role` VARCHAR(8) NOT NULL, @@ -22,7 +22,7 @@ CREATE TABLE `{prefix}webui_users` ( CHECK (`role` IN ('admin', 'user')) ) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci; -CREATE TABLE `{prefix}webui_sessions` ( +CREATE TABLE IF NOT EXISTS `{prefix}webui_sessions` ( `token_hash` BINARY(32) NOT NULL, `user_id` INT NOT NULL, `created_at` DATETIME(6) NOT NULL, @@ -36,7 +36,7 @@ CREATE TABLE `{prefix}webui_sessions` ( FOREIGN KEY (`user_id`) REFERENCES `{prefix}webui_users` (`id`) ) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci; -CREATE TABLE `{prefix}webui_zone_delegations` ( +CREATE TABLE IF NOT EXISTS `{prefix}webui_zone_delegations` ( `zone` VARCHAR(255) NOT NULL, `user_id` INT NOT NULL, `created_at` DATETIME(6) NOT NULL, @@ -47,7 +47,7 @@ CREATE TABLE `{prefix}webui_zone_delegations` ( FOREIGN KEY (`created_by`) REFERENCES `{prefix}webui_users` (`id`) ) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci; -CREATE TABLE `{prefix}webui_audit` ( +CREATE TABLE IF NOT EXISTS `{prefix}webui_audit` ( `id` BIGINT NOT NULL AUTO_INCREMENT, `time` DATETIME(6) NOT NULL, `user_id` INT NULL, diff --git a/migrations_test.go b/migrations_test.go index c6da6d7..1546213 100644 --- a/migrations_test.go +++ b/migrations_test.go @@ -98,6 +98,18 @@ type migrationDB struct { failErr error executedDDL []string versionWrite []any + schemaChange func(rows [][]driver.Value) [][]driver.Value +} + +func appSchemaRows(prefix string, change func(rows [][]driver.Value) [][]driver.Value) [][]driver.Value { + var rows [][]driver.Value + for _, c := range appSchema { + rows = append(rows, []driver.Value{prefix + c.table, c.column, strings.ToUpper(c.columnType)}) + } + if change != nil { + rows = change(rows) + } + return rows } func (m *migrationDB) handler(q string, args []any) fdbResponse { @@ -125,6 +137,10 @@ func (m *migrationDB) handler(q string, args []any) fdbResponse { case strings.HasPrefix(q, "CREATE TABLE"): m.executedDDL = append(m.executedDDL, q) return fdbResponse{} + case strings.Contains(q, "information_schema.COLUMNS"): + return fdbResponse{rows: appSchemaRows("coredns_", m.schemaChange)} + case strings.Contains(q, "information_schema.KEY_COLUMN_USAGE"): + return fdbResponse{rows: fdbRow(int64(5))} } return fdbResponse{err: errors.New("unexpected query " + q)} } @@ -248,3 +264,57 @@ func TestMigrateDatabase(t *testing.T) { t.Fatal("invalid prefix accepted") } } + +func TestVerifyAppSchema(t *testing.T) { + ctx := context.Background() + m := &migrationDB{tableCount: 0} + db, st := newFakeDB(t, m.handler) + if err := migrateDatabase(ctx, db, fdbTables(t), discardLogger()); err != nil { + t.Fatal(err) + } + var verify fdbCall + for _, c := range st.Calls() { + if strings.Contains(c.query, "information_schema.COLUMNS") { + verify = c + } + } + if len(verify.args) != 5 || verify.args[0] != "coredns_webui_schema" || verify.args[4] != "coredns_webui_audit" { + t.Fatalf("%+v", verify) + } + all, err := loadMigrations(migrationFiles, "coredns_") + if err != nil { + t.Fatal(err) + } + for _, migration := range all { + for _, stmt := range migration.statements { + if !strings.HasPrefix(stmt, "CREATE TABLE IF NOT EXISTS ") { + t.Fatalf("%s: not idempotent: %.60s", migration.name, stmt) + } + } + } + cases := map[string]func(rows [][]driver.Value) [][]driver.Value{ + "table coredns_webui_audit has no column after_value": func(rows [][]driver.Value) [][]driver.Value { return rows[:len(rows)-1] }, + "column id of table coredns_webui_users has type bigint, expected int": func(rows [][]driver.Value) [][]driver.Value { + for _, r := range rows { + if r[0] == "coredns_webui_users" && r[1] == "id" { + r[2] = "bigint" + } + } + return rows + }, + "table coredns_webui_schema has no column id": func([][]driver.Value) [][]driver.Value { return nil }, + } + for want, change := range cases { + m := &migrationDB{tableCount: 1, version: int64(1), schemaChange: change} + db, _ := newFakeDB(t, m.handler) + if err := migrateDatabase(ctx, db, fdbTables(t), discardLogger()); err == nil || !strings.Contains(err.Error(), want) { + t.Fatalf("%s: %v", want, err) + } + } + for _, fail := range []fdbResponse{{err: errors.New("boom")}, {rows: [][]driver.Value{{"t", nil, "int"}}}} { + db, _ := newFakeDB(t, fdbRules(fdbRule{"information_schema.COLUMNS", fail})) + if err := verifyAppSchema(ctx, db, fdbTables(t), discardLogger()); err == nil || !strings.Contains(err.Error(), "read application schema") { + t.Fatal(err) + } + } +} diff --git a/records_store.go b/records_store.go index 7022f54..428b5d4 100644 --- a/records_store.go +++ b/records_store.go @@ -32,10 +32,12 @@ const zoneSummarySelect = "SELECT r.`zone`, COUNT(*), " + "ORDER BY s.`name` <> '', s.`id` LIMIT 1) FROM {records} r " func (s recordStore) ListZones(ctx context.Context) ([]zoneSummary, error) { + defer traceStore(ctx, "recordStore.ListZones")() return s.queryZones(ctx, s.t.sql(zoneSummarySelect+"GROUP BY r.`zone` ORDER BY r.`zone`")) } func (s recordStore) ListZonesOfUser(ctx context.Context, userID int64) ([]zoneSummary, error) { + defer traceStore(ctx, "recordStore.ListZonesOfUser")() return s.queryZones(ctx, s.t.sql(zoneSummarySelect+ "WHERE r.`zone` IN (SELECT d.`zone` FROM {delegations} d WHERE d.`user_id` = ?) GROUP BY r.`zone` ORDER BY r.`zone`"), userID) } @@ -61,6 +63,7 @@ func (s recordStore) queryZones(ctx context.Context, query string, args ...any) } func (s recordStore) ZoneExists(ctx context.Context, zone string) (bool, error) { + defer traceStore(ctx, "recordStore.ZoneExists")() var one int err := s.q.QueryRowContext(ctx, s.t.sql("SELECT 1 FROM {records} WHERE `zone` = ? LIMIT 1"), zone).Scan(&one) if errors.Is(err, sql.ErrNoRows) { @@ -73,10 +76,12 @@ func (s recordStore) ZoneExists(ctx context.Context, zone string) (bool, error) } func (s recordStore) ZoneRows(ctx context.Context, zone string) ([]recordRow, error) { + defer traceStore(ctx, "recordStore.ZoneRows")() return s.queryRecords(ctx, s.t.sql("SELECT "+recordColumns+" FROM {records} WHERE `zone` = ? ORDER BY `id`"), zone) } func (s recordStore) ZoneRowsForUpdate(ctx context.Context, zone string) ([]recordRow, error) { + defer traceStore(ctx, "recordStore.ZoneRowsForUpdate")() return s.queryRecords(ctx, s.t.sql("SELECT "+recordColumns+" FROM {records} WHERE `zone` = ? ORDER BY `id` FOR UPDATE"), zone) } @@ -101,10 +106,12 @@ func (s recordStore) queryRecords(ctx context.Context, query string, args ...any } func (s recordStore) RecordByID(ctx context.Context, id int64) (recordRow, error) { + defer traceStore(ctx, "recordStore.RecordByID")() return s.queryRecord(ctx, s.t.sql("SELECT "+recordColumns+" FROM {records} WHERE `id` = ?"), id) } func (s recordStore) RecordByIDForUpdate(ctx context.Context, id int64) (recordRow, error) { + defer traceStore(ctx, "recordStore.RecordByIDForUpdate")() return s.queryRecord(ctx, s.t.sql("SELECT "+recordColumns+" FROM {records} WHERE `id` = ? FOR UPDATE"), id) } @@ -121,7 +128,8 @@ func (s recordStore) queryRecord(ctx context.Context, query string, id int64) (r } func (s recordStore) InsertRecord(ctx context.Context, r recordRow) (int64, error) { - res, err := s.q.ExecContext(ctx, + defer traceStore(ctx, "recordStore.InsertRecord")() + res, err := s.q.ExecContext(privateSQLArgs(ctx, 4), s.t.sql("INSERT INTO {records} (`zone`, `name`, `ttl`, `content`, `record_type`) VALUES (?, ?, ?, ?, ?)"), r.Zone, r.Name, r.TTL, r.Content, r.RecordType) if err != nil { @@ -135,7 +143,8 @@ func (s recordStore) InsertRecord(ctx context.Context, r recordRow) (int64, erro } func (s recordStore) UpdateRecord(ctx context.Context, r recordRow) error { - _, err := s.q.ExecContext(ctx, + defer traceStore(ctx, "recordStore.UpdateRecord")() + _, err := s.q.ExecContext(privateSQLArgs(ctx, 4), s.t.sql("UPDATE {records} SET `zone` = ?, `name` = ?, `ttl` = ?, `content` = ?, `record_type` = ? WHERE `id` = ?"), r.Zone, r.Name, r.TTL, r.Content, r.RecordType, r.ID) if err != nil { @@ -145,6 +154,7 @@ func (s recordStore) UpdateRecord(ctx context.Context, r recordRow) error { } func (s recordStore) DeleteRecord(ctx context.Context, id int64) (bool, error) { + defer traceStore(ctx, "recordStore.DeleteRecord")() res, err := s.q.ExecContext(ctx, s.t.sql("DELETE FROM {records} WHERE `id` = ?"), id) if err != nil { return false, fmt.Errorf("delete record: %w", err) @@ -157,6 +167,7 @@ func (s recordStore) DeleteRecord(ctx context.Context, id int64) (bool, error) { } func (s recordStore) DeleteZoneRecords(ctx context.Context, zone string) (int64, error) { + defer traceStore(ctx, "recordStore.DeleteZoneRecords")() res, err := s.q.ExecContext(ctx, s.t.sql("DELETE FROM {records} WHERE `zone` = ?"), zone) if err != nil { return 0, fmt.Errorf("delete zone records: %w", err) diff --git a/routes.go b/routes.go index 9ecd5e4..c459a6c 100644 --- a/routes.go +++ b/routes.go @@ -20,8 +20,9 @@ var appMiddlewares = []handlerMiddleware{requestLogMiddleware, securityHeadersMi func (s *WebServer) Handler() http.Handler { r := mux.NewRouter() + r.SkipClean(true) s.Routes(r) - var h http.Handler = r + h := cleanPagePath(r) for i := len(appMiddlewares) - 1; i >= 0; i-- { h = appMiddlewares[i](s, h) } @@ -42,6 +43,7 @@ const ( ) func (s *WebServer) handleHealth(w http.ResponseWriter, r *http.Request) { + defer traceFunc(r.Context(), s.log, "page.health")() status, body := http.StatusOK, healthOK ctx, cancel := context.WithTimeout(r.Context(), healthPingTimeout) defer cancel() diff --git a/scripts/docker-test-lib.sh b/scripts/docker-test-lib.sh new file mode 100644 index 0000000..3fc3d6d --- /dev/null +++ b/scripts/docker-test-lib.sh @@ -0,0 +1,10 @@ +#!/bin/sh +# SPDX-License-Identifier: GPL-2.0-or-later +# Copyright (C) 2026 Bryan Joshua Pedini + +require_free_docker_name() { + if docker "$1" inspect "$2" >/dev/null 2>&1; then + echo "docker $1 already exists: $2" >&2 + exit 1 + fi +} diff --git a/scripts/integration.sh b/scripts/integration.sh index 33fdfd2..c086384 100755 --- a/scripts/integration.sh +++ b/scripts/integration.sh @@ -4,35 +4,72 @@ set -eu cd "$(dirname "$0")/.." +. ./scripts/docker-test-lib.sh IT_ID=${IT_ID:-$$} IT_NAME=${IT_NAME:-cdwu-it-${IT_ID}} MYSQL_IMAGE=${MYSQL_IMAGE:-mysql:8.4} -network="${IT_NAME}" +network="$IT_NAME" mysql="${IT_NAME}-mysql" mysql_data="${IT_NAME}-data" tests="${IT_NAME}-tests" image="${IT_NAME}:integration" -root_password=$(od -An -tx1 -N16 /dev/urandom | tr -d ' \n') + +require_free_docker_name network "$network" +require_free_docker_name container "$mysql" +require_free_docker_name volume "$mysql_data" +require_free_docker_name container "$tests" +require_free_docker_name image "$image" + +network_id= +mysql_id= +tests_id= +volume= +tmp=$(mktemp -d) +owner=${tmp##*/} +owns_volume() { + [ "$(docker volume inspect --format '{{index .Labels "cdwu.test.owner"}}' "$1")" = "$owner" ] +} cleanup() { status=$? - if [ "$status" -ne 0 ]; then - docker logs --tail 80 "$mysql" >&2 2>&1 || true + if [ "$status" -ne 0 ] && [ -n "$mysql_id" ]; then + docker logs --tail 80 "$mysql_id" >&2 2>&1 || true fi - docker rm --force --volumes "$tests" "$mysql" >/dev/null 2>&1 || true - docker volume rm "$mysql_data" >/dev/null 2>&1 || true - docker network rm "$network" >/dev/null 2>&1 || true - docker image rm --force "$image" >/dev/null 2>&1 || true + for container in "$tests_id" "$mysql_id"; do + if [ -n "$container" ]; then + docker rm --force --volumes "$container" >/dev/null 2>&1 || true + fi + done + if [ -n "$volume" ] && owns_volume "$volume" 2>/dev/null; then + docker volume rm "$volume" >/dev/null 2>&1 || true + fi + if [ -n "$network_id" ]; then + docker network rm "$network_id" >/dev/null 2>&1 || true + fi + if [ -s "$tmp/image-id" ] && + [ "$(docker image inspect --format '{{.Id}}' "$image" 2>/dev/null)" = "$(cat "$tmp/image-id")" ]; then + docker image rm "$image" >/dev/null 2>&1 || true + fi + rm -rf "$tmp" exit "$status" } trap cleanup EXIT trap 'exit 130' INT TERM -docker build --target integration --file dockerfile --tag "$image" . -docker network create --internal "$network" >/dev/null -docker run --detach --name "$mysql" --network "$network" --network-alias mysql \ - --volume "$mysql_data:/var/lib/mysql" \ - --env MYSQL_ROOT_PASSWORD="$root_password" "$MYSQL_IMAGE" >/dev/null + +root_password=$(od -An -tx1 -N16 /dev/urandom | tr -d ' \n') +volume=$(docker volume create --label "cdwu.test.owner=$owner" "$mysql_data") +if ! owns_volume "$volume"; then + echo "docker volume already exists: $mysql_data" >&2 + exit 1 +fi +network_id=$(docker network create --internal "$network") +require_free_docker_name image "$image" +docker build --target integration --file dockerfile --tag "$image" --iidfile "$tmp/image-id" . +mysql_id=$(docker create --name "$mysql" --network "$network_id" --network-alias mysql \ + --volume "$volume:/var/lib/mysql" \ + --env MYSQL_ROOT_PASSWORD="$root_password" "$MYSQL_IMAGE") +docker start "$mysql_id" >/dev/null attempt=0 -until docker exec --env MYSQL_PWD="$root_password" "$mysql" mysqladmin ping --host=127.0.0.1 --user=root --silent >/dev/null 2>&1; do +until docker exec --env MYSQL_PWD="$root_password" "$mysql_id" mysql --host=127.0.0.1 --user=root --execute 'SELECT 1' >/dev/null 2>&1; do attempt=$((attempt + 1)) if [ "$attempt" -ge 120 ]; then echo "mysql did not become ready" >&2 @@ -40,6 +77,7 @@ until docker exec --env MYSQL_PWD="$root_password" "$mysql" mysqladmin ping --ho fi sleep 1 done -docker run --name "$tests" --network "$network" \ +tests_id=$(docker create --name "$tests" --network "$network_id" \ --env IT_MYSQL_HOST=mysql --env IT_MYSQL_PORT=3306 --env IT_MYSQL_ROOT_PASSWORD="$root_password" \ - "$image" + "$(cat "$tmp/image-id")") +docker start --attach "$tests_id" diff --git a/scripts/test-image.sh b/scripts/test-image.sh index 52c93d9..15a51ce 100755 --- a/scripts/test-image.sh +++ b/scripts/test-image.sh @@ -8,6 +8,7 @@ if [ "$#" -ne 3 ]; then exit 2 fi cd "$(dirname "$0")/.." +. ./scripts/docker-test-lib.sh image=$1 version=$2 commit=$3 @@ -18,24 +19,43 @@ network="$name" mysql="${name}-mysql" server="${name}-app" exported="${name}-export" +probe_name="${name}-probe" + +require_free_docker_name network "$network" +for container in "$mysql" "$server" "$exported" "$probe_name"; do + require_free_docker_name container "$container" +done + +network_id= +mysql_id= +server_id= +exported_id= +probe_id= tmp=$(mktemp -d) root_password=$(od -An -tx1 -N16 /dev/urandom | tr -d ' \n') db_password=coredns_webui_dev pw_admin="pw$(od -An -tx1 -N12 /dev/urandom | tr -d ' \n')" pw_user="pw$(od -An -tx1 -N12 /dev/urandom | tr -d ' \n')" +pw_reset="pw$(od -An -tx1 -N12 /dev/urandom | tr -d ' \n')" pw_short="pw$(od -An -tx1 -N4 /dev/urandom | tr -d ' \n')" rc=0 cleanup() { status=$? if [ "$status" -ne 0 ]; then - for container in "$server" "$mysql"; do - if docker inspect "$container" >/dev/null 2>&1; then + for container in "$server_id" "$mysql_id"; do + if [ -n "$container" ]; then docker logs --tail 40 "$container" >&2 2>&1 || true fi done fi - docker rm --force --volumes "$server" "$mysql" "$exported" "${name}-probe" >/dev/null 2>&1 || true - docker network rm "$network" >/dev/null 2>&1 || true + for container in "$server_id" "$mysql_id" "$exported_id" "$probe_id"; do + if [ -n "$container" ]; then + docker rm --force --volumes "$container" >/dev/null 2>&1 || true + fi + done + if [ -n "$network_id" ]; then + docker network rm "$network_id" >/dev/null 2>&1 || true + fi rm -rf "$tmp" exit "$status" } @@ -63,8 +83,15 @@ capture() { "$@" >"$tmp/out" 2>"$tmp/err" && rc=0 || rc=$? } +capture_probe() { + probe_id=$(docker create --name "$probe_name" "$@") || fail "could not create probe" + capture docker start --attach "$probe_id" + docker rm --force --volumes "$probe_id" >/dev/null + probe_id= +} + scan() { - if grep -qF -e "$pw_admin" -e "$pw_user" -e "$pw_short" -e "$db_password" -e "$root_password" "$@"; then + if grep -qF -e "$pw_admin" -e "$pw_user" -e "$pw_reset" -e "$pw_short" -e "$db_password" -e "$root_password" "$@"; then fail "a secret appears in the output" fi } @@ -72,12 +99,12 @@ scan() { cli() { input=$1 shift - printf '%s\n' "$input" | docker exec -i "$server" /app "$@" >"$tmp/out" 2>"$tmp/err" && rc=0 || rc=$? + printf '%s\n' "$input" | docker exec -i "$server_id" /app "$@" >"$tmp/out" 2>"$tmp/err" && rc=0 || rc=$? scan "$tmp/out" "$tmp/err" } sql() { - docker exec --env MYSQL_PWD="$root_password" "$mysql" mysql --user=root --batch --skip-column-names --execute "$1" + docker exec --env MYSQL_PWD="$root_password" "$mysql_id" mysql --user=root --batch --skip-column-names --execute "$1" } usage_text() { @@ -113,11 +140,12 @@ ok "OCI labels" [ "$(docker image inspect --format '{{json .Config.Healthcheck.Test}}' "$image")" = '["CMD","/app","healthcheck"]' ] || fail "image healthcheck is not /app healthcheck" ok "image user, entrypoint and healthcheck" -capture docker run --rm --name "${name}-probe" --entrypoint /bin/sh "$image" -c true +capture_probe --entrypoint /bin/sh "$image" -c true [ "$rc" -ne 0 ] || fail "the image runs /bin/sh" -docker create --name "$exported" "$image" >/dev/null -docker export "$exported" | tar -t >"$tmp/files" -docker rm --force "$exported" >/dev/null +exported_id=$(docker create --name "$exported" "$image") +docker export "$exported_id" | tar -t >"$tmp/files" +docker rm --force --volumes "$exported_id" >/dev/null +exported_id= while IFS= read -r entry; do case ${entry%/} in app | etc | etc/ssl | etc/ssl/cert.pem | etc/hostname | etc/hosts | etc/resolv.conf | etc/mtab) ;; @@ -129,41 +157,45 @@ grep -qx 'app' "$tmp/files" || fail "/app missing from the image filesystem" grep -qx 'etc/ssl/cert.pem' "$tmp/files" || fail "CA bundle missing from the image filesystem" ok "image filesystem has no shell" -capture docker run --rm --name "${name}-probe" "$image" +capture_probe "$image" expect_rc "start without configuration" 2 ok "exit 2 without configuration" -capture docker run --rm --name "${name}-probe" "$image" version +capture_probe "$image" version expect_rc "version" 0 [ "$(cat "$tmp/out")" = "coredns-web-ui $version $commit" ] || fail "version output is not 'coredns-web-ui $version $commit'" ok "version output" -capture docker run --rm --name "${name}-probe" "$image" help +capture_probe "$image" help expect_rc "help" 0 cmp -s "$tmp/out" "$tmp/usage" || fail "help output differs from the usage text" [ ! -s "$tmp/err" ] || fail "help wrote to stderr" ok "help output" -for args in "bogus" "help extra"; do - capture docker run --rm --name "${name}-probe" "$image" $args - expect_rc "usage error ($args)" 2 - [ ! -s "$tmp/out" ] || fail "usage error ($args) wrote to stdout" - head -n 1 "$tmp/err" | grep -q '^coredns-web-ui: usage error: ' || fail "usage error ($args) message has no usage error prefix" - tail -n +2 "$tmp/err" | cmp -s - "$tmp/usage" || fail "usage error ($args) does not end with the usage text" +for cmd in bogus help; do + set -- "$cmd" + if [ "$cmd" = help ]; then + set -- "$@" extra + fi + capture_probe "$image" "$@" + expect_rc "usage error ($*)" 2 + [ ! -s "$tmp/out" ] || fail "usage error ($*) wrote to stdout" + head -n 1 "$tmp/err" | grep -q '^coredns-web-ui: usage error: ' || fail "usage error ($*) message has no usage error prefix" + tail -n +2 "$tmp/err" | cmp -s - "$tmp/usage" || fail "usage error ($*) does not end with the usage text" done ok "usage errors exit 2 with the usage text on stderr" -capture docker run --rm --name "${name}-probe" "$image" healthcheck +capture_probe "$image" healthcheck expect_rc "healthcheck without a server" 1 ok "healthcheck fails without a server" -docker network create --internal "$network" >/dev/null -docker create --name "$mysql" --network "$network" --network-alias mysql --tmpfs /var/lib/mysql \ - --env MYSQL_ROOT_PASSWORD="$root_password" "$mysql_image" >/dev/null -docker cp dev/mysql-init.sql "$mysql:/docker-entrypoint-initdb.d/mysql-init.sql" -docker start "$mysql" >/dev/null +network_id=$(docker network create --internal "$network") +mysql_id=$(docker create --name "$mysql" --network "$network_id" --network-alias mysql --tmpfs /var/lib/mysql \ + --env MYSQL_ROOT_PASSWORD="$root_password" "$mysql_image") +docker cp dev/mysql-init.sql "$mysql_id:/docker-entrypoint-initdb.d/mysql-init.sql" +docker start "$mysql_id" >/dev/null attempt=0 -until docker exec --env MYSQL_PWD="$root_password" "$mysql" mysqladmin ping --host=127.0.0.1 --user=root --silent >/dev/null 2>&1; do +until docker exec --env MYSQL_PWD="$root_password" "$mysql_id" mysql --host=127.0.0.1 --user=root --execute 'SELECT 1' >/dev/null 2>&1; do attempt=$((attempt + 1)) [ "$attempt" -lt 120 ] || fail "mysql did not become ready" sleep 1 @@ -171,13 +203,14 @@ done [ "$(sql 'SELECT COUNT(*) FROM coredns.coredns_records')" = 0 ] || fail "records table is not initialized" ok "mysql ready" -docker run --detach --name "$server" --network "$network" --network-alias app \ +server_id=$(docker create --name "$server" --network "$network_id" --network-alias app \ --health-interval 2s --health-timeout 5s --health-start-period 2s --health-retries 5 \ --env DB_HOST=mysql --env DB_USER=coredns_webui --env DB_PASSWORD="$db_password" --env DB_NAME=coredns \ - --env COOKIE_SECURE=false --env LOG_LEVEL=TRACE "$image" >/dev/null + --env COOKIE_SECURE=false --env LOG_LEVEL=TRACE "$image") +docker start "$server_id" >/dev/null attempt=0 while :; do - state=$(docker inspect --format '{{.State.Status}} {{if .State.Health}}{{.State.Health.Status}}{{end}}' "$server") + state=$(docker inspect --format '{{.State.Status}} {{if .State.Health}}{{.State.Health.Status}}{{end}}' "$server_id") [ "$state" != "running healthy" ] || break case $state in running*) ;; @@ -189,25 +222,36 @@ while :; do done ok "container healthy through its HEALTHCHECK" -[ "$(docker inspect --format '{{.Config.User}}' "$server")" = "65532:65532" ] || fail "the container does not run as 65532:65532" +[ "$(docker inspect --format '{{.Config.User}}' "$server_id")" = "65532:65532" ] || fail "the container does not run as 65532:65532" ok "container runs as 65532:65532" -capture docker exec "$server" /bin/sh -c true +capture docker exec "$server_id" /bin/sh -c true [ "$rc" -ne 0 ] || fail "docker exec /bin/sh succeeded" ok "docker exec /bin/sh fails" -capture docker exec "$server" /app healthcheck +capture docker exec "$server_id" /app healthcheck expect_rc "docker exec healthcheck" 0 ok "docker exec healthcheck" -health=$(docker run --rm --name "${name}-probe" --network "$network" "$probe" wget -qO- http://app:8080/health) || fail "GET /health failed" -[ "$health" = '{"status":"ok"}' ] || fail "unexpected /health body: $health" -page=$(docker run --rm --name "${name}-probe" --network "$network" "$probe" wget -qO- http://app:8080/version) || fail "GET /version failed" -printf '%s' "$page" | grep -qF "$version" || fail "/version does not render the version" -printf '%s' "$page" | grep -qF "$commit" || fail "/version does not render the commit" +capture docker exec "$server_id" /app version +expect_rc "docker exec version" 0 +[ "$(cat "$tmp/out")" = "coredns-web-ui $version $commit" ] || fail "docker exec version returned unexpected output" +capture docker exec "$server_id" /app help +expect_rc "docker exec help" 0 +cmp -s "$tmp/out" "$tmp/usage" || fail "docker exec help differs from the usage text" +[ ! -s "$tmp/err" ] || fail "docker exec help wrote to stderr" +ok "docker exec version and help" + +capture_probe --network "$network_id" "$probe" wget -qO- http://app:8080/health +expect_rc "GET /health" 0 +[ "$(cat "$tmp/out")" = '{"status":"ok"}' ] || fail "unexpected /health body" +capture_probe --network "$network_id" "$probe" wget -qO- http://app:8080/version +expect_rc "GET /version" 0 +grep -qF "$version" "$tmp/out" || fail "/version does not render the version" +grep -qF "$commit" "$tmp/out" || fail "/version does not render the commit" ok "/health and /version" -docker logs "$server" >"$tmp/startup.log" 2>&1 +docker logs "$server_id" >"$tmp/startup.log" 2>&1 grep -qF "$commit" "$tmp/startup.log" || fail "commit $commit not in the startup log" grep -qF "$version" "$tmp/startup.log" || fail "version $version not in the startup log" ok "version and commit in the startup log" @@ -225,6 +269,19 @@ expect_rc "user add user" 0 [ "$(sql "SELECT COUNT(*) FROM coredns.coredns_webui_users WHERE password_hash LIKE '\$argon2id\$%' AND deleted_at IS NULL")" = 2 ] || fail "passwords are not stored as argon2id hashes" ok "user add with both roles" +hash_query="SELECT SHA2(password_hash, 256) FROM coredns.coredns_webui_users WHERE username = 'imguser'" +old_hash=$(sql "$hash_query") +sql "INSERT INTO coredns.coredns_webui_sessions (token_hash, user_id, created_at, last_seen_at, expires_at, origin, user_agent) + SELECT UNHEX(REPEAT('11', 32)), id, UTC_TIMESTAMP(6), UTC_TIMESTAMP(6), + UTC_TIMESTAMP(6) + INTERVAL 1 HOUR, '192.0.2.1', 'image test' + FROM coredns.coredns_webui_users WHERE username = 'imguser'" +cli "$pw_reset" user passwd imguser +expect_rc "user passwd" 0 +new_hash=$(sql "$hash_query") +[ -n "$new_hash" ] && [ "$old_hash" != "$new_hash" ] || fail "user passwd did not replace the stored hash" +[ "$(sql 'SELECT COUNT(*) FROM coredns.coredns_webui_sessions')" = 0 ] || fail "user passwd did not revoke the session" +ok "user passwd changes the hash and revokes sessions" + cli "" user list expect_rc "user list" 0 grep -q '^imgadmin ' "$tmp/out" || fail "user list does not show imgadmin" @@ -260,20 +317,20 @@ cli "$pw_user" user add imguser user [ "$(sql "SELECT COUNT(*) FROM coredns.coredns_webui_users WHERE username = 'imguser'")" = 1 ] || fail "user add changed the row of a deleted user" ok "the username of a deleted user cannot be reused" -[ "$(sql "SELECT GROUP_CONCAT(operation ORDER BY id) FROM coredns.coredns_webui_audit")" = "user_create,user_create,user_role,user_role,user_delete" ] || fail "unexpected audit rows for the CLI changes" -[ "$(sql "SELECT COUNT(*) FROM coredns.coredns_webui_audit WHERE actor = 'cli' AND origin = 'local'")" = 5 ] || fail "CLI audit rows do not have actor cli and origin local" +[ "$(sql "SELECT GROUP_CONCAT(operation ORDER BY id) FROM coredns.coredns_webui_audit")" = "user_create,user_create,user_password,user_role,user_role,user_delete" ] || fail "unexpected audit rows for the CLI changes" +[ "$(sql "SELECT COUNT(*) FROM coredns.coredns_webui_audit WHERE actor = 'cli' AND origin = 'local'")" = 6 ] || fail "CLI audit rows do not have actor cli and origin local" ok "CLI changes are audited" -docker logs "$server" >"$tmp/server.log" 2>&1 +docker logs "$server_id" >"$tmp/server.log" 2>&1 scan "$tmp/server.log" ok "no secret in the container logs" started=$(date +%s) -docker stop --time 40 "$server" >/dev/null +docker stop --time 40 "$server_id" >/dev/null elapsed=$(($(date +%s) - started)) -[ "$(docker inspect --format '{{.State.ExitCode}}' "$server")" = 0 ] || fail "SIGTERM did not stop the container with exit code 0" +[ "$(docker inspect --format '{{.State.ExitCode}}' "$server_id")" = 0 ] || fail "SIGTERM did not stop the container with exit code 0" [ "$elapsed" -lt 25 ] || fail "SIGTERM took ${elapsed}s, longer than the 25s grace period" -docker logs "$server" >"$tmp/server.log" 2>&1 +docker logs "$server_id" >"$tmp/server.log" 2>&1 scan "$tmp/server.log" ok "SIGTERM stops the container with exit 0 in ${elapsed}s" diff --git a/session_store.go b/session_store.go index 7a7ed18..c5d8402 100644 --- a/session_store.go +++ b/session_store.go @@ -36,7 +36,8 @@ func newSessionStore(q dbtx, t tableNames) sessionStore { } func (s sessionStore) CreateSession(ctx context.Context, row sessionRow) error { - _, err := s.q.ExecContext(ctx, + defer traceStore(ctx, "sessionStore.CreateSession")() + _, err := s.q.ExecContext(privateSQLArgs(ctx, 7), s.t.sql("INSERT INTO {sessions} (`token_hash`, `user_id`, `created_at`, `last_seen_at`, `expires_at`, `origin`, `user_agent`) VALUES (?, ?, ?, ?, ?, ?, ?)"), row.TokenHash, row.UserID, dbTime(row.CreatedAt), dbTime(row.LastSeenAt), dbTime(row.ExpiresAt), row.Origin, row.UserAgent) if err != nil { @@ -46,6 +47,7 @@ func (s sessionStore) CreateSession(ctx context.Context, row sessionRow) error { } func (s sessionStore) SessionByTokenHash(ctx context.Context, tokenHash []byte) (sessionWithUser, error) { + defer traceStore(ctx, "sessionStore.SessionByTokenHash")() var r sessionWithUser u, err := scanUser(s.q.QueryRowContext(ctx, s.t.sql("SELECT "+userColumns+", x.`token_hash`, x.`user_id`, x.`created_at`, x.`last_seen_at`, x.`expires_at`, x.`origin`, x.`user_agent` "+ @@ -65,7 +67,10 @@ func (s sessionStore) SessionByTokenHash(ctx context.Context, tokenHash []byte) } func (s sessionStore) TouchSession(ctx context.Context, tokenHash []byte, now time.Time) error { - if _, err := s.q.ExecContext(ctx, s.t.sql("UPDATE {sessions} SET `last_seen_at` = ? WHERE `token_hash` = ?"), dbTime(now), tokenHash); err != nil { + defer traceStore(ctx, "sessionStore.TouchSession")() + now = dbTime(now) + if _, err := s.q.ExecContext(ctx, s.t.sql("UPDATE {sessions} SET `last_seen_at` = ? WHERE `token_hash` = ? AND `last_seen_at` <= ?"), + now, tokenHash, now.Add(-sessionTouchInterval)); err != nil { return fmt.Errorf("touch session: %w", err) } return nil @@ -84,20 +89,24 @@ func (s sessionStore) deleted(ctx context.Context, what, query string, args ...a } func (s sessionStore) DeleteSession(ctx context.Context, tokenHash []byte) (bool, error) { + defer traceStore(ctx, "sessionStore.DeleteSession")() n, err := s.deleted(ctx, "delete session", "DELETE FROM {sessions} WHERE `token_hash` = ?", tokenHash) return n > 0, err } func (s sessionStore) DeleteUserSessions(ctx context.Context, userID int64) (int64, error) { + defer traceStore(ctx, "sessionStore.DeleteUserSessions")() return s.deleted(ctx, "delete user sessions", "DELETE FROM {sessions} WHERE `user_id` = ?", userID) } func (s sessionStore) DeleteUserSessionsExcept(ctx context.Context, userID int64, keepTokenHash []byte) (int64, error) { + defer traceStore(ctx, "sessionStore.DeleteUserSessionsExcept")() return s.deleted(ctx, "delete user sessions", "DELETE FROM {sessions} WHERE `user_id` = ? AND `token_hash` <> ?", userID, keepTokenHash) } func (s sessionStore) DeleteExpiredSessions(ctx context.Context, now time.Time, idleTimeout time.Duration) (int64, error) { + defer traceStore(ctx, "sessionStore.DeleteExpiredSessions")() now = dbTime(now) return s.deleted(ctx, "delete expired sessions", "DELETE FROM {sessions} WHERE `expires_at` <= ? OR `last_seen_at` <= ?", now, now.Add(-idleTimeout)) diff --git a/stores_test.go b/stores_test.go index bdc4811..973f90f 100644 --- a/stores_test.go +++ b/stores_test.go @@ -415,7 +415,8 @@ func TestSessionStore(t *testing.T) { if err := s.TouchSession(ctx, []byte("h"), storeTime); err != nil { t.Fatal(err) } - expectArgs(t, st.Calls()[2], ts, []byte("h")) + expectQuery(t, st.Calls()[2], "SET `last_seen_at` = ? WHERE `token_hash` = ? AND `last_seen_at` <= ?") + expectArgs(t, st.Calls()[2], ts, []byte("h"), ts.Add(-time.Minute)) if ok, err := s.DeleteSession(ctx, []byte("h")); !ok || err != nil { t.Fatal(ok, err) } diff --git a/templates/html/pages/audit.html b/templates/html/pages/audit.html index f10f627..ea597ef 100644 --- a/templates/html/pages/audit.html +++ b/templates/html/pages/audit.html @@ -26,7 +26,7 @@ - +
diff --git a/type_webserver.go b/type_webserver.go index 50940f3..952c0fd 100644 --- a/type_webserver.go +++ b/type_webserver.go @@ -211,6 +211,7 @@ func (s *WebServer) runSessionCleanup(ctx context.Context) { } func (s *WebServer) cleanupSessions(ctx context.Context) { + ctx = withTraceLogger(ctx, s.log) n, err := s.sessions.DeleteExpiredSessions(ctx, s.now(), s.cfg.SessionIdleTimeout) if err != nil { if ctx.Err() == nil { diff --git a/type_webserver_test.go b/type_webserver_test.go index 654120f..2950a7f 100644 --- a/type_webserver_test.go +++ b/type_webserver_test.go @@ -307,7 +307,7 @@ func TestLogConfigOmitsSecrets(t *testing.T) { func serverDBHandler(columns [][]driver.Value) fdbHandler { m := &migrationDB{tableCount: 1, version: int64(1)} return func(q string, args []any) fdbResponse { - if strings.Contains(q, "information_schema.COLUMNS") { + if strings.Contains(q, "information_schema.COLUMNS") && args[0] == "coredns_records" { return fdbResponse{rows: columns} } return m.handler(q, args) @@ -315,7 +315,8 @@ func serverDBHandler(columns [][]driver.Value) fdbHandler { } var validContractRows = [][]driver.Value{ - {"id", "int"}, {"zone", "varchar"}, {"name", "varchar"}, {"ttl", "int"}, {"content", "text"}, {"record_type", "varchar"}, + {"id", "int", "int", nil}, {"zone", "varchar", "varchar(255)", int64(255)}, {"name", "varchar", "varchar(255)", int64(255)}, + {"ttl", "int", "int", nil}, {"content", "text", "text", int64(65535)}, {"record_type", "varchar", "varchar(255)", int64(255)}, } func TestRunServer(t *testing.T) { @@ -407,7 +408,7 @@ func TestConnectDatabase(t *testing.T) { t.Fatal(err) } - broken, _ := newFakeDB(t, serverDBHandler([][]driver.Value{{"id", "int"}})) + broken, _ := newFakeDB(t, serverDBHandler([][]driver.Value{{"id", "int", "int", nil}})) h.a.openDB = func(Config, *slog.Logger) (*sql.DB, error) { return broken, nil } if _, _, err := h.a.connectDatabase(ctx, cfg, discardLogger()); !errors.Is(err, errContract) { t.Fatal(err) @@ -427,7 +428,7 @@ func TestConnectDatabase(t *testing.T) { } newer, _ := newFakeDB(t, func(q string, args []any) fdbResponse { - if strings.Contains(q, "information_schema.COLUMNS") { + if strings.Contains(q, "information_schema.COLUMNS") && args[0] == "coredns_records" { return fdbResponse{rows: validContractRows} } m := &migrationDB{tableCount: 1, version: int64(99)} diff --git a/user_store.go b/user_store.go index ade31b9..806fa3a 100644 --- a/user_store.go +++ b/user_store.go @@ -56,8 +56,9 @@ func scanUser(sc rowScanner, extra ...any) (userRow, error) { } func (s userStore) CreateUser(ctx context.Context, username, role, passwordHash string, now time.Time) (userRow, error) { + defer traceStore(ctx, "userStore.CreateUser")() now = dbTime(now) - res, err := s.q.ExecContext(ctx, + res, err := s.q.ExecContext(privateSQLArgs(ctx, 3), s.t.sql("INSERT INTO {users} (`username`, `role`, `password_hash`, `created_at`, `updated_at`) VALUES (?, ?, ?, ?, ?)"), username, role, passwordHash, now, now) if isDuplicateKey(err) { @@ -85,26 +86,32 @@ func (s userStore) queryUser(ctx context.Context, query string, args ...any) (us } func (s userStore) UserByUsername(ctx context.Context, username string) (userRow, error) { + defer traceStore(ctx, "userStore.UserByUsername")() return s.queryUser(ctx, "SELECT "+userColumns+" FROM {users} u WHERE u.`username` = ?", username) } func (s userStore) UserByUsernameForUpdate(ctx context.Context, username string) (userRow, error) { + defer traceStore(ctx, "userStore.UserByUsernameForUpdate")() return s.queryUser(ctx, "SELECT "+userColumns+" FROM {users} u WHERE u.`username` = ? FOR UPDATE", username) } func (s userStore) UserByID(ctx context.Context, id int64) (userRow, error) { + defer traceStore(ctx, "userStore.UserByID")() return s.queryUser(ctx, "SELECT "+userColumns+" FROM {users} u WHERE u.`id` = ?", id) } func (s userStore) UserByIDForShare(ctx context.Context, id int64) (userRow, error) { + defer traceStore(ctx, "userStore.UserByIDForShare")() return s.queryUser(ctx, "SELECT "+userColumns+" FROM {users} u WHERE u.`id` = ? FOR SHARE", id) } func (s userStore) UserByIDForUpdate(ctx context.Context, id int64) (userRow, error) { + defer traceStore(ctx, "userStore.UserByIDForUpdate")() return s.queryUser(ctx, "SELECT "+userColumns+" FROM {users} u WHERE u.`id` = ? FOR UPDATE", id) } func (s userStore) ListUsers(ctx context.Context, includeDeleted bool) ([]userSummary, error) { + defer traceStore(ctx, "userStore.ListUsers")() query := "SELECT " + userColumns + ", (SELECT COUNT(*) FROM {delegations} d WHERE d.`user_id` = u.`id`) FROM {users} u " if !includeDeleted { query += "WHERE u.`deleted_at` IS NULL " @@ -131,6 +138,7 @@ func (s userStore) ListUsers(ctx context.Context, includeDeleted bool) ([]userSu } func (s userStore) ActiveUsersWithRole(ctx context.Context, role string) ([]userRow, error) { + defer traceStore(ctx, "userStore.ActiveUsersWithRole")() rows, err := s.q.QueryContext(ctx, s.t.sql("SELECT "+userColumns+" FROM {users} u WHERE u.`role` = ? AND u.`deleted_at` IS NULL ORDER BY u.`username`"), role) if err != nil { @@ -156,6 +164,7 @@ func collectUsers(rows *sql.Rows) ([]userRow, error) { } func (s userStore) LockActiveAdmins(ctx context.Context) ([]userRow, error) { + defer traceStore(ctx, "userStore.LockActiveAdmins")() rows, err := s.q.QueryContext(ctx, s.t.sql("SELECT "+userColumns+" FROM {users} u WHERE u.`role` = 'admin' AND u.`deleted_at` IS NULL ORDER BY u.`id` FOR UPDATE")) if err != nil { @@ -165,6 +174,7 @@ func (s userStore) LockActiveAdmins(ctx context.Context) ([]userRow, error) { } func (s userStore) HasActiveAdmin(ctx context.Context) (bool, error) { + defer traceStore(ctx, "userStore.HasActiveAdmin")() var one int err := s.q.QueryRowContext(ctx, s.t.sql("SELECT 1 FROM {users} WHERE `role` = 'admin' AND `deleted_at` IS NULL LIMIT 1")).Scan(&one) @@ -185,22 +195,26 @@ func (s userStore) exec(ctx context.Context, what, query string, args ...any) er } func (s userStore) SetRole(ctx context.Context, id int64, role string, now time.Time) error { + defer traceStore(ctx, "userStore.SetRole")() return s.exec(ctx, "set role", "UPDATE {users} SET `role` = ?, `updated_at` = ? WHERE `id` = ? AND `deleted_at` IS NULL", role, dbTime(now), id) } func (s userStore) SetPassword(ctx context.Context, id int64, passwordHash string, now time.Time) error { - return s.exec(ctx, "set password", + defer traceStore(ctx, "userStore.SetPassword")() + return s.exec(privateSQLArgs(ctx, 1), "set password", "UPDATE {users} SET `password_hash` = ?, `updated_at` = ? WHERE `id` = ? AND `deleted_at` IS NULL", passwordHash, dbTime(now), id) } func (s userStore) MarkDeleted(ctx context.Context, id int64, now time.Time) error { + defer traceStore(ctx, "userStore.MarkDeleted")() now = dbTime(now) return s.exec(ctx, "delete user", "UPDATE {users} SET `deleted_at` = ?, `updated_at` = ? WHERE `id` = ? AND `deleted_at` IS NULL", now, now, id) } func (s userStore) TouchLastLogin(ctx context.Context, id int64, now time.Time) error { + defer traceStore(ctx, "userStore.TouchLastLogin")() return s.exec(ctx, "touch last login", "UPDATE {users} SET `last_login_at` = ? WHERE `id` = ?", dbTime(now), id) } diff --git a/version.go b/version.go index e0b8a9e..daa49f6 100644 --- a/version.go +++ b/version.go @@ -34,6 +34,7 @@ func renderVersionPage(w io.Writer, name string) error { } func (s *WebServer) handleVersion(w http.ResponseWriter, r *http.Request) { + defer traceFunc(r.Context(), s.log, "page.version")() var buf bytes.Buffer if err := renderVersionPage(&buf, s.cfg.AppName); err != nil { s.log.ErrorContext(r.Context(), "render version page failed", "error", err) diff --git a/webfake_test.go b/webfake_test.go index 0868a75..4ff6c5f 100644 --- a/webfake_test.go +++ b/webfake_test.go @@ -61,7 +61,9 @@ type fakeWebStore struct { mu sync.Mutex state fakeWebState failOn map[string]error + failTimes map[string]int onLock func(state *fakeWebState) + onTx func(state *fakeWebState) calls []string zoneLocks []string commits int @@ -75,7 +77,8 @@ func newFakeWebStore() *fakeWebStore { delegations: map[delegationKey]delegationRow{}, zones: map[string]bool{}, }, - failOn: map[string]error{}, + failOn: map[string]error{}, + failTimes: map[string]int{}, } } @@ -91,6 +94,12 @@ func (f *fakeWebStore) view() *fakeWebView { func (v *fakeWebView) call(name string) error { v.store.calls = append(v.store.calls, name) + if n, limited := v.store.failTimes[name]; limited { + if n <= 0 { + return nil + } + v.store.failTimes[name] = n - 1 + } return v.store.failOn[name] } @@ -220,7 +229,7 @@ func (v *fakeWebView) TouchSession(ctx context.Context, tokenHash []byte, now ti if err := v.call("TouchSession"); err != nil { return err } - if s, ok := v.state.sessions[string(tokenHash)]; ok { + if s, ok := v.state.sessions[string(tokenHash)]; ok && !s.LastSeenAt.After(now.Add(-sessionTouchInterval)) { s.LastSeenAt = now v.state.sessions[string(tokenHash)] = s } @@ -341,6 +350,10 @@ func (f *fakeWebStore) InTx(ctx context.Context, fn func(tx webTx) error) error if err := f.failOn["InTx"]; err != nil { return err } + if hook := f.onTx; hook != nil { + f.onTx = nil + hook(&f.state) + } working := f.state.clone() if err := fn(&fakeWebView{store: f, state: &working, inTx: true}); err != nil { f.rollbacks++ @@ -699,6 +712,7 @@ type webRequest struct { header map[string]string remote string rawBody io.Reader + chunked bool } type webResult struct { @@ -718,6 +732,10 @@ func (h *webHarness) do(req webRequest) webResult { if req.body == "" && req.rawBody == nil { r = httptest.NewRequest(req.method, req.path, nil) } + if req.chunked { + r = httptest.NewRequest(req.method, req.path, io.MultiReader(body)) + r.TransferEncoding = []string{"chunked"} + } r.RemoteAddr = "192.0.2.10:40000" if req.remote != "" { r.RemoteAddr = req.remote