- 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
203 lines
5.5 KiB
Go
203 lines
5.5 KiB
Go
// SPDX-License-Identifier: GPL-2.0-or-later
|
|
// Copyright (C) 2026 Bryan Joshua Pedini
|
|
|
|
package main
|
|
|
|
import (
|
|
"context"
|
|
"database/sql"
|
|
"errors"
|
|
"fmt"
|
|
"strings"
|
|
)
|
|
|
|
const (
|
|
auditKindRead = "read"
|
|
auditKindChange = "change"
|
|
auditOutcomeSuccess = "success"
|
|
auditOutcomeError = "error"
|
|
auditMaxActorRunes = 64
|
|
auditMaxOriginRunes = 45
|
|
auditMaxErrorRunes = 255
|
|
auditMaxOperationLen = 32
|
|
auditMaxListLimit = 1000
|
|
)
|
|
|
|
type auditFilter struct {
|
|
Zone string
|
|
Actor string
|
|
Operation string
|
|
Kind string
|
|
Outcome string
|
|
BeforeID int64
|
|
Limit int
|
|
RestrictToUserID sql.NullInt64
|
|
}
|
|
|
|
type auditRow struct {
|
|
auditEntry
|
|
TargetUsername sql.NullString
|
|
}
|
|
|
|
type auditStore struct {
|
|
q dbtx
|
|
t tableNames
|
|
}
|
|
|
|
func newAuditStore(q dbtx, t tableNames) auditStore {
|
|
return auditStore{q: q, t: t}
|
|
}
|
|
|
|
func cropRunes(s string, max int) string {
|
|
if len(s) <= max {
|
|
return s
|
|
}
|
|
n := 0
|
|
for i := range s {
|
|
if n == max {
|
|
return s[:i]
|
|
}
|
|
n++
|
|
}
|
|
return s
|
|
}
|
|
|
|
func nullJSON(b []byte) any {
|
|
if b == nil {
|
|
return nil
|
|
}
|
|
return string(b)
|
|
}
|
|
|
|
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")
|
|
}
|
|
errMsg := e.Error
|
|
if errMsg.Valid {
|
|
errMsg.String = cropRunes(errMsg.String, auditMaxErrorRunes)
|
|
}
|
|
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,
|
|
e.Status, errMsg, e.Zone, e.RecordID, e.TargetUserID, nullJSON(e.Before), nullJSON(e.After))
|
|
if err != nil {
|
|
return 0, fmt.Errorf("insert audit: %w", err)
|
|
}
|
|
id, err := res.LastInsertId()
|
|
if err != nil {
|
|
return 0, fmt.Errorf("insert audit: %w", err)
|
|
}
|
|
return id, nil
|
|
}
|
|
|
|
const auditSelect = "SELECT a.`id`, a.`time`, a.`user_id`, a.`actor`, a.`origin`, a.`operation`, a.`status`, a.`error`, a.`zone`, " +
|
|
"a.`record_id`, a.`target_user_id`, a.`before_value`, a.`after_value`, tu.`username` FROM {audit} a " +
|
|
"LEFT JOIN {users} tu ON tu.`id` = a.`target_user_id` "
|
|
|
|
func auditFilterSQL(f auditFilter) (string, []any, error) {
|
|
var conds []string
|
|
var args []any
|
|
if f.Zone != "" {
|
|
conds = append(conds, "a.`zone` = ?")
|
|
args = append(args, f.Zone)
|
|
}
|
|
if f.Actor != "" {
|
|
conds = append(conds, "a.`actor` = ?")
|
|
args = append(args, f.Actor)
|
|
}
|
|
if f.Operation != "" {
|
|
conds = append(conds, "a.`operation` = ?")
|
|
args = append(args, f.Operation)
|
|
}
|
|
switch f.Kind {
|
|
case "":
|
|
case auditKindRead, auditKindChange:
|
|
op := "IN"
|
|
if f.Kind == auditKindRead {
|
|
op = "NOT IN"
|
|
}
|
|
marks := strings.TrimSuffix(strings.Repeat("?, ", len(auditChangeOperations)), ", ")
|
|
conds = append(conds, "a.`operation` "+op+" ("+marks+")")
|
|
for _, o := range auditChangeOperations {
|
|
args = append(args, o)
|
|
}
|
|
default:
|
|
return "", nil, errors.New("invalid audit kind")
|
|
}
|
|
switch f.Outcome {
|
|
case "":
|
|
case auditOutcomeSuccess:
|
|
conds = append(conds, "(a.`status` IS NULL OR a.`status` < 400)")
|
|
case auditOutcomeError:
|
|
conds = append(conds, "a.`status` >= 400")
|
|
default:
|
|
return "", nil, errors.New("invalid audit outcome")
|
|
}
|
|
if f.BeforeID > 0 {
|
|
conds = append(conds, "a.`id` < ?")
|
|
args = append(args, f.BeforeID)
|
|
}
|
|
if f.RestrictToUserID.Valid {
|
|
conds = append(conds, "(a.`user_id` = ? OR a.`zone` IN (SELECT d.`zone` FROM {delegations} d WHERE d.`user_id` = ?))")
|
|
args = append(args, f.RestrictToUserID.Int64, f.RestrictToUserID.Int64)
|
|
}
|
|
if len(conds) == 0 {
|
|
return "", args, nil
|
|
}
|
|
return "WHERE " + strings.Join(conds, " AND ") + " ", args, nil
|
|
}
|
|
|
|
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")
|
|
}
|
|
where, args, err := auditFilterSQL(f)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("list audit: %w", err)
|
|
}
|
|
args = append(args, f.Limit)
|
|
return s.queryAudit(ctx, s.t.sql(auditSelect+where+"ORDER BY a.`id` DESC LIMIT ?"), args...)
|
|
}
|
|
|
|
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")
|
|
}
|
|
rows, err := s.queryAudit(ctx, s.t.sql(auditSelect+"ORDER BY a.`id` DESC LIMIT ?"), n)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
for i, j := 0, len(rows)-1; i < j; i, j = i+1, j-1 {
|
|
rows[i], rows[j] = rows[j], rows[i]
|
|
}
|
|
return rows, nil
|
|
}
|
|
|
|
func (s auditStore) queryAudit(ctx context.Context, query string, args ...any) ([]auditRow, error) {
|
|
rows, err := s.q.QueryContext(ctx, query, args...)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("read audit: %w", err)
|
|
}
|
|
defer rows.Close()
|
|
var out []auditRow
|
|
for rows.Next() {
|
|
var r auditRow
|
|
e := &r.auditEntry
|
|
if err := rows.Scan(&e.ID, &e.Time, &e.UserID, &e.Actor, &e.Origin, &e.Operation, &e.Status, &e.Error, &e.Zone,
|
|
&e.RecordID, &e.TargetUserID, &e.Before, &e.After, &r.TargetUsername); err != nil {
|
|
return nil, fmt.Errorf("read audit: %w", err)
|
|
}
|
|
scanUTC(&e.Time)
|
|
out = append(out, r)
|
|
}
|
|
if err := rows.Err(); err != nil {
|
|
return nil, fmt.Errorf("read audit: %w", err)
|
|
}
|
|
return out, nil
|
|
}
|