- 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
221 lines
7.2 KiB
Go
221 lines
7.2 KiB
Go
// SPDX-License-Identifier: GPL-2.0-or-later
|
|
// Copyright (C) 2026 Bryan Joshua Pedini
|
|
|
|
package main
|
|
|
|
import (
|
|
"context"
|
|
"database/sql"
|
|
"errors"
|
|
"fmt"
|
|
"time"
|
|
)
|
|
|
|
type userRow struct {
|
|
ID int64
|
|
Username string
|
|
Role string
|
|
PasswordHash string
|
|
CreatedAt time.Time
|
|
UpdatedAt time.Time
|
|
LastLoginAt sql.NullTime
|
|
DeletedAt sql.NullTime
|
|
}
|
|
|
|
type userSummary struct {
|
|
userRow
|
|
Zones int64
|
|
}
|
|
|
|
type userStore struct {
|
|
q dbtx
|
|
t tableNames
|
|
}
|
|
|
|
func newUserStore(q dbtx, t tableNames) userStore {
|
|
return userStore{q: q, t: t}
|
|
}
|
|
|
|
const userColumns = "u.`id`, u.`username`, u.`role`, u.`password_hash`, u.`created_at`, u.`updated_at`, u.`last_login_at`, u.`deleted_at`"
|
|
|
|
type rowScanner interface {
|
|
Scan(dest ...any) error
|
|
}
|
|
|
|
func scanUser(sc rowScanner, extra ...any) (userRow, error) {
|
|
var u userRow
|
|
dest := append([]any{&u.ID, &u.Username, &u.Role, &u.PasswordHash, &u.CreatedAt, &u.UpdatedAt, &u.LastLoginAt, &u.DeletedAt}, extra...)
|
|
if err := sc.Scan(dest...); err != nil {
|
|
return userRow{}, err
|
|
}
|
|
scanUTC(&u.CreatedAt)
|
|
scanUTC(&u.UpdatedAt)
|
|
scanNullUTC(&u.LastLoginAt)
|
|
scanNullUTC(&u.DeletedAt)
|
|
return u, nil
|
|
}
|
|
|
|
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(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) {
|
|
return userRow{}, errUsernameTaken
|
|
}
|
|
if err != nil {
|
|
return userRow{}, fmt.Errorf("create user: %w", err)
|
|
}
|
|
id, err := res.LastInsertId()
|
|
if err != nil {
|
|
return userRow{}, fmt.Errorf("create user: %w", err)
|
|
}
|
|
return userRow{ID: id, Username: username, Role: role, PasswordHash: passwordHash, CreatedAt: now, UpdatedAt: now}, nil
|
|
}
|
|
|
|
func (s userStore) queryUser(ctx context.Context, query string, args ...any) (userRow, error) {
|
|
u, err := scanUser(s.q.QueryRowContext(ctx, s.t.sql(query), args...))
|
|
if errors.Is(err, sql.ErrNoRows) {
|
|
return userRow{}, errRowNotFound
|
|
}
|
|
if err != nil {
|
|
return userRow{}, fmt.Errorf("read user: %w", err)
|
|
}
|
|
return u, nil
|
|
}
|
|
|
|
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 "
|
|
}
|
|
query += "ORDER BY u.`username`"
|
|
rows, err := s.q.QueryContext(ctx, s.t.sql(query))
|
|
if err != nil {
|
|
return nil, fmt.Errorf("list users: %w", err)
|
|
}
|
|
defer rows.Close()
|
|
var users []userSummary
|
|
for rows.Next() {
|
|
var zones int64
|
|
u, err := scanUser(rows, &zones)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("list users: %w", err)
|
|
}
|
|
users = append(users, userSummary{userRow: u, Zones: zones})
|
|
}
|
|
if err := rows.Err(); err != nil {
|
|
return nil, fmt.Errorf("list users: %w", err)
|
|
}
|
|
return users, nil
|
|
}
|
|
|
|
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 {
|
|
return nil, fmt.Errorf("list users: %w", err)
|
|
}
|
|
return collectUsers(rows)
|
|
}
|
|
|
|
func collectUsers(rows *sql.Rows) ([]userRow, error) {
|
|
defer rows.Close()
|
|
var users []userRow
|
|
for rows.Next() {
|
|
u, err := scanUser(rows)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("list users: %w", err)
|
|
}
|
|
users = append(users, u)
|
|
}
|
|
if err := rows.Err(); err != nil {
|
|
return nil, fmt.Errorf("list users: %w", err)
|
|
}
|
|
return users, nil
|
|
}
|
|
|
|
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 {
|
|
return nil, fmt.Errorf("lock active admins: %w", err)
|
|
}
|
|
return collectUsers(rows)
|
|
}
|
|
|
|
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)
|
|
if errors.Is(err, sql.ErrNoRows) {
|
|
return false, nil
|
|
}
|
|
if err != nil {
|
|
return false, fmt.Errorf("active admin: %w", err)
|
|
}
|
|
return true, nil
|
|
}
|
|
|
|
func (s userStore) exec(ctx context.Context, what, query string, args ...any) error {
|
|
if _, err := s.q.ExecContext(ctx, s.t.sql(query), args...); err != nil {
|
|
return fmt.Errorf("%s: %w", what, err)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
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 {
|
|
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)
|
|
}
|