test(ui): avoid a literal em dash in the em dash check

- test(ui): avoid a literal em dash in the em dash check
- fix(cli): accept any positive int64 audit count and share the last active admin rule
- fix(api): limit audit before_id to 2^53-1
- fix(api): audit unmatched api requests, bound every request body and record audit write failures
- fix(ui): recheck the account in the login transaction and require existing zones on zone pages
- fix(api): recheck the acting admin and the stored password hash in change transactions
- fix(db): keep committed outcomes on lock release failure, narrow the records contract and trace sql statements
- fix(db): make the initial migration restartable and verify the application schema
- fix(auth): never move last_seen_at backwards on concurrent session touches
- test(api): cover lock release failure after commit and handler tracing without secrets
- fix(test): redact credentials from mysql setup errors
- fix(audit): retain addressed objects on admin refusals
- test(db): cover migration restarts and records contract ranges in mysql
- test(api): verify account races and audit rollback in mysql
- fix(auth): reject password changes after account deletion
- docs: document unknown api audit entries
- fix(audit): bound failure retries and redact sensitive sql parameters
- fix(test): isolate docker resources and cover image cli commands
- test(auth): expect unauthorized after an account deletion race
- fix(db): verify application column widths and foreign keys
This commit is contained in:
bryanpedini committed 2026-11-19 15:46:12 +01:00
1 parent 5f17aab6ca
commit 53444bec7a
40 files changed
+2332 -254

No files matched your search

+208 -34
View File
@@ -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<<a.Ordinal) != 0 && a.Value != nil {
values[i] = redactedLogValue
} else {
values[i] = traceValue(a.Value)
}
}
log.Log(ctx, LevelTrace, "sql statement", "caller", sqlCaller(), "statement", strings.Join(strings.Fields(query), " "), "args", values)
}