- 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
789 lines
20 KiB
Go
789 lines
20 KiB
Go
// SPDX-License-Identifier: GPL-2.0-or-later
|
|
// Copyright (C) 2026 Bryan Joshua Pedini
|
|
|
|
package main
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"crypto/rand"
|
|
"database/sql"
|
|
"encoding/json"
|
|
"io"
|
|
"log/slog"
|
|
"maps"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"slices"
|
|
"strings"
|
|
"sync"
|
|
"testing"
|
|
"time"
|
|
)
|
|
|
|
var webNow = time.Date(2026, 11, 18, 12, 0, 0, 0, time.UTC)
|
|
|
|
const (
|
|
testPassword = "secret-password"
|
|
testZone = "example.org."
|
|
otherZone = "other.org."
|
|
)
|
|
|
|
type delegationKey struct {
|
|
zone string
|
|
userID int64
|
|
}
|
|
|
|
type fakeAuditInsert struct {
|
|
entry auditEntry
|
|
inTx bool
|
|
}
|
|
|
|
type fakeWebState struct {
|
|
users []userRow
|
|
sessions map[string]sessionRow
|
|
delegations map[delegationKey]delegationRow
|
|
zones map[string]bool
|
|
audit []fakeAuditInsert
|
|
}
|
|
|
|
func (s fakeWebState) clone() fakeWebState {
|
|
return fakeWebState{
|
|
users: slices.Clone(s.users),
|
|
sessions: maps.Clone(s.sessions),
|
|
delegations: maps.Clone(s.delegations),
|
|
zones: maps.Clone(s.zones),
|
|
audit: slices.Clone(s.audit),
|
|
}
|
|
}
|
|
|
|
type fakeWebStore struct {
|
|
mu sync.Mutex
|
|
state fakeWebState
|
|
failOn map[string]error
|
|
failTimes map[string]int
|
|
onLock func(state *fakeWebState)
|
|
onTx func(state *fakeWebState)
|
|
calls []string
|
|
zoneLocks []string
|
|
commits int
|
|
rollbacks int
|
|
}
|
|
|
|
func newFakeWebStore() *fakeWebStore {
|
|
return &fakeWebStore{
|
|
state: fakeWebState{
|
|
sessions: map[string]sessionRow{},
|
|
delegations: map[delegationKey]delegationRow{},
|
|
zones: map[string]bool{},
|
|
},
|
|
failOn: map[string]error{},
|
|
failTimes: map[string]int{},
|
|
}
|
|
}
|
|
|
|
type fakeWebView struct {
|
|
store *fakeWebStore
|
|
state *fakeWebState
|
|
inTx bool
|
|
}
|
|
|
|
func (f *fakeWebStore) view() *fakeWebView {
|
|
return &fakeWebView{store: f, state: &f.state}
|
|
}
|
|
|
|
func (v *fakeWebView) call(name string) error {
|
|
v.store.calls = append(v.store.calls, name)
|
|
if n, limited := v.store.failTimes[name]; limited {
|
|
if n <= 0 {
|
|
return nil
|
|
}
|
|
v.store.failTimes[name] = n - 1
|
|
}
|
|
return v.store.failOn[name]
|
|
}
|
|
|
|
func (f *fakeWebStore) called(name string) int {
|
|
f.mu.Lock()
|
|
defer f.mu.Unlock()
|
|
n := 0
|
|
for _, c := range f.calls {
|
|
if c == name {
|
|
n++
|
|
}
|
|
}
|
|
return n
|
|
}
|
|
|
|
func (f *fakeWebStore) addUser(username, role string) userRow {
|
|
f.mu.Lock()
|
|
defer f.mu.Unlock()
|
|
u := userRow{
|
|
ID: int64(len(f.state.users) + 1),
|
|
Username: username,
|
|
Role: role,
|
|
PasswordHash: fakeHash(testPassword),
|
|
CreatedAt: webNow.Add(-48 * time.Hour),
|
|
UpdatedAt: webNow.Add(-48 * time.Hour),
|
|
}
|
|
f.state.users = append(f.state.users, u)
|
|
return u
|
|
}
|
|
|
|
func (f *fakeWebStore) user(id int64) userRow {
|
|
f.mu.Lock()
|
|
defer f.mu.Unlock()
|
|
return f.state.users[id-1]
|
|
}
|
|
|
|
func (f *fakeWebStore) setUser(u userRow) {
|
|
f.mu.Lock()
|
|
defer f.mu.Unlock()
|
|
f.state.users[u.ID-1] = u
|
|
}
|
|
|
|
func (f *fakeWebStore) addZone(zone string) {
|
|
f.mu.Lock()
|
|
defer f.mu.Unlock()
|
|
f.state.zones[zone] = true
|
|
}
|
|
|
|
func (f *fakeWebStore) delegate(zone string, u userRow) {
|
|
f.mu.Lock()
|
|
defer f.mu.Unlock()
|
|
f.state.delegations[delegationKey{zone, u.ID}] = delegationRow{Zone: zone, UserID: u.ID, Username: u.Username, CreatedAt: webNow.Add(-time.Hour), CreatedBy: 1}
|
|
}
|
|
|
|
func (f *fakeWebStore) hasDelegation(zone string, userID int64) bool {
|
|
f.mu.Lock()
|
|
defer f.mu.Unlock()
|
|
_, ok := f.state.delegations[delegationKey{zone, userID}]
|
|
return ok
|
|
}
|
|
|
|
func (f *fakeWebStore) addSession(u userRow, created, lastSeen time.Time) string {
|
|
token, hash, err := newSessionToken(rand.Reader)
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
f.mu.Lock()
|
|
defer f.mu.Unlock()
|
|
f.state.sessions[string(hash)] = sessionRow{TokenHash: hash, UserID: u.ID, CreatedAt: created, LastSeenAt: lastSeen, ExpiresAt: created.Add(12 * time.Hour), Origin: "192.0.2.1", UserAgent: "test"}
|
|
return token
|
|
}
|
|
|
|
func (f *fakeWebStore) sessionCount(userID int64) int {
|
|
f.mu.Lock()
|
|
defer f.mu.Unlock()
|
|
n := 0
|
|
for _, s := range f.state.sessions {
|
|
if s.UserID == userID {
|
|
n++
|
|
}
|
|
}
|
|
return n
|
|
}
|
|
|
|
func (f *fakeWebStore) auditRows() []fakeAuditInsert {
|
|
f.mu.Lock()
|
|
defer f.mu.Unlock()
|
|
return slices.Clone(f.state.audit)
|
|
}
|
|
|
|
func (f *fakeWebStore) auditCount() int {
|
|
f.mu.Lock()
|
|
defer f.mu.Unlock()
|
|
return len(f.state.audit)
|
|
}
|
|
|
|
func (v *fakeWebView) InsertAudit(ctx context.Context, e auditEntry) (int64, error) {
|
|
if err := v.call("InsertAudit"); err != nil {
|
|
return 0, err
|
|
}
|
|
e.ID = int64(len(v.state.audit) + 1)
|
|
v.state.audit = append(v.state.audit, fakeAuditInsert{entry: e, inTx: v.inTx})
|
|
return e.ID, nil
|
|
}
|
|
|
|
func (v *fakeWebView) userByUsername(username string) (userRow, error) {
|
|
for _, u := range v.state.users {
|
|
if u.Username == username {
|
|
return u, nil
|
|
}
|
|
}
|
|
return userRow{}, errRowNotFound
|
|
}
|
|
|
|
func (v *fakeWebView) SessionByTokenHash(ctx context.Context, tokenHash []byte) (sessionWithUser, error) {
|
|
if err := v.call("SessionByTokenHash"); err != nil {
|
|
return sessionWithUser{}, err
|
|
}
|
|
s, ok := v.state.sessions[string(tokenHash)]
|
|
if !ok {
|
|
return sessionWithUser{}, errRowNotFound
|
|
}
|
|
return sessionWithUser{Session: s, User: v.state.users[s.UserID-1]}, nil
|
|
}
|
|
|
|
func (v *fakeWebView) TouchSession(ctx context.Context, tokenHash []byte, now time.Time) error {
|
|
if err := v.call("TouchSession"); err != nil {
|
|
return err
|
|
}
|
|
if s, ok := v.state.sessions[string(tokenHash)]; ok && !s.LastSeenAt.After(now.Add(-sessionTouchInterval)) {
|
|
s.LastSeenAt = now
|
|
v.state.sessions[string(tokenHash)] = s
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (v *fakeWebView) UserByUsername(ctx context.Context, username string) (userRow, error) {
|
|
if err := v.call("UserByUsername"); err != nil {
|
|
return userRow{}, err
|
|
}
|
|
return v.userByUsername(username)
|
|
}
|
|
|
|
func (v *fakeWebView) HasActiveAdmin(ctx context.Context) (bool, error) {
|
|
if err := v.call("HasActiveAdmin"); err != nil {
|
|
return false, err
|
|
}
|
|
return slices.ContainsFunc(v.state.users, func(u userRow) bool { return u.Role == roleAdmin && !u.DeletedAt.Valid }), nil
|
|
}
|
|
|
|
func (v *fakeWebView) HasDelegation(ctx context.Context, zone string, userID int64) (bool, error) {
|
|
if err := v.call("HasDelegation"); err != nil {
|
|
return false, err
|
|
}
|
|
_, ok := v.state.delegations[delegationKey{zone, userID}]
|
|
return ok, nil
|
|
}
|
|
|
|
func (v *fakeWebView) ListUsers(ctx context.Context, includeDeleted bool) ([]userSummary, error) {
|
|
if err := v.call("ListUsers"); err != nil {
|
|
return nil, err
|
|
}
|
|
var out []userSummary
|
|
for _, u := range v.state.users {
|
|
if u.DeletedAt.Valid && !includeDeleted {
|
|
continue
|
|
}
|
|
var n int64
|
|
for k := range v.state.delegations {
|
|
if k.userID == u.ID {
|
|
n++
|
|
}
|
|
}
|
|
out = append(out, userSummary{userRow: u, Zones: n})
|
|
}
|
|
slices.SortFunc(out, func(a, b userSummary) int { return strings.Compare(a.Username, b.Username) })
|
|
return out, nil
|
|
}
|
|
|
|
func (v *fakeWebView) UserZones(ctx context.Context, userID int64) ([]userZone, error) {
|
|
if err := v.call("UserZones"); err != nil {
|
|
return nil, err
|
|
}
|
|
var out []userZone
|
|
for k, d := range v.state.delegations {
|
|
if k.userID == userID {
|
|
out = append(out, userZone{Zone: k.zone, CreatedAt: d.CreatedAt, ZoneExists: v.state.zones[k.zone]})
|
|
}
|
|
}
|
|
slices.SortFunc(out, func(a, b userZone) int { return strings.Compare(a.Zone, b.Zone) })
|
|
return out, nil
|
|
}
|
|
|
|
func (v *fakeWebView) ZoneUsers(ctx context.Context, zone string) ([]userRow, error) {
|
|
if err := v.call("ZoneUsers"); err != nil {
|
|
return nil, err
|
|
}
|
|
var out []userRow
|
|
for k := range v.state.delegations {
|
|
u := v.state.users[k.userID-1]
|
|
if k.zone == zone && u.Role == roleUser && !u.DeletedAt.Valid {
|
|
out = append(out, u)
|
|
}
|
|
}
|
|
slices.SortFunc(out, func(a, b userRow) int { return strings.Compare(a.Username, b.Username) })
|
|
return out, nil
|
|
}
|
|
|
|
func (v *fakeWebView) ZoneExists(ctx context.Context, zone string) (bool, error) {
|
|
if err := v.call("ZoneExists"); err != nil {
|
|
return false, err
|
|
}
|
|
return v.state.zones[zone], nil
|
|
}
|
|
|
|
func (v *fakeWebView) ListAudit(ctx context.Context, f auditFilter) ([]auditRow, error) {
|
|
if err := v.call("ListAudit"); err != nil {
|
|
return nil, err
|
|
}
|
|
var out []auditRow
|
|
for i := len(v.state.audit) - 1; i >= 0 && len(out) < f.Limit; i-- {
|
|
e := v.state.audit[i].entry
|
|
if f.BeforeID > 0 && e.ID >= f.BeforeID {
|
|
continue
|
|
}
|
|
if f.Operation != "" && e.Operation != f.Operation {
|
|
continue
|
|
}
|
|
if f.RestrictToUserID.Valid {
|
|
_, delegated := v.state.delegations[delegationKey{e.Zone.String, f.RestrictToUserID.Int64}]
|
|
if !(e.UserID.Valid && e.UserID.Int64 == f.RestrictToUserID.Int64) && !(e.Zone.Valid && delegated) {
|
|
continue
|
|
}
|
|
}
|
|
r := auditRow{auditEntry: e}
|
|
if e.TargetUserID.Valid {
|
|
r.TargetUsername = sql.NullString{String: v.state.users[e.TargetUserID.Int64-1].Username, Valid: true}
|
|
}
|
|
out = append(out, r)
|
|
}
|
|
return out, nil
|
|
}
|
|
|
|
func (f *fakeWebStore) InTx(ctx context.Context, fn func(tx webTx) error) error {
|
|
f.mu.Lock()
|
|
defer f.mu.Unlock()
|
|
f.calls = append(f.calls, "InTx")
|
|
if err := f.failOn["InTx"]; err != nil {
|
|
return err
|
|
}
|
|
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++
|
|
return err
|
|
}
|
|
if err := f.failOn["Commit"]; err != nil {
|
|
f.rollbacks++
|
|
return err
|
|
}
|
|
f.state = working
|
|
f.commits++
|
|
return nil
|
|
}
|
|
|
|
func (f *fakeWebStore) InZoneTx(ctx context.Context, zone string, log *slog.Logger, fn func(tx webTx) error) error {
|
|
f.mu.Lock()
|
|
f.zoneLocks = append(f.zoneLocks, zone)
|
|
f.mu.Unlock()
|
|
return f.InTx(ctx, fn)
|
|
}
|
|
|
|
func (f *fakeWebStore) InsertAudit(ctx context.Context, e auditEntry) (int64, error) {
|
|
f.mu.Lock()
|
|
defer f.mu.Unlock()
|
|
return f.view().InsertAudit(ctx, e)
|
|
}
|
|
|
|
func (f *fakeWebStore) SessionByTokenHash(ctx context.Context, h []byte) (sessionWithUser, error) {
|
|
f.mu.Lock()
|
|
defer f.mu.Unlock()
|
|
return f.view().SessionByTokenHash(ctx, h)
|
|
}
|
|
|
|
func (f *fakeWebStore) TouchSession(ctx context.Context, h []byte, now time.Time) error {
|
|
f.mu.Lock()
|
|
defer f.mu.Unlock()
|
|
return f.view().TouchSession(ctx, h, now)
|
|
}
|
|
|
|
func (f *fakeWebStore) UserByUsername(ctx context.Context, username string) (userRow, error) {
|
|
f.mu.Lock()
|
|
defer f.mu.Unlock()
|
|
return f.view().UserByUsername(ctx, username)
|
|
}
|
|
|
|
func (f *fakeWebStore) HasActiveAdmin(ctx context.Context) (bool, error) {
|
|
f.mu.Lock()
|
|
defer f.mu.Unlock()
|
|
return f.view().HasActiveAdmin(ctx)
|
|
}
|
|
|
|
func (f *fakeWebStore) HasDelegation(ctx context.Context, zone string, userID int64) (bool, error) {
|
|
f.mu.Lock()
|
|
defer f.mu.Unlock()
|
|
return f.view().HasDelegation(ctx, zone, userID)
|
|
}
|
|
|
|
func (f *fakeWebStore) ListUsers(ctx context.Context, includeDeleted bool) ([]userSummary, error) {
|
|
f.mu.Lock()
|
|
defer f.mu.Unlock()
|
|
return f.view().ListUsers(ctx, includeDeleted)
|
|
}
|
|
|
|
func (f *fakeWebStore) UserZones(ctx context.Context, userID int64) ([]userZone, error) {
|
|
f.mu.Lock()
|
|
defer f.mu.Unlock()
|
|
return f.view().UserZones(ctx, userID)
|
|
}
|
|
|
|
func (f *fakeWebStore) ZoneUsers(ctx context.Context, zone string) ([]userRow, error) {
|
|
f.mu.Lock()
|
|
defer f.mu.Unlock()
|
|
return f.view().ZoneUsers(ctx, zone)
|
|
}
|
|
|
|
func (f *fakeWebStore) ZoneExists(ctx context.Context, zone string) (bool, error) {
|
|
f.mu.Lock()
|
|
defer f.mu.Unlock()
|
|
return f.view().ZoneExists(ctx, zone)
|
|
}
|
|
|
|
func (f *fakeWebStore) ListAudit(ctx context.Context, filter auditFilter) ([]auditRow, error) {
|
|
f.mu.Lock()
|
|
defer f.mu.Unlock()
|
|
return f.view().ListAudit(ctx, filter)
|
|
}
|
|
|
|
func (v *fakeWebView) CreateSession(ctx context.Context, row sessionRow) error {
|
|
if err := v.call("CreateSession"); err != nil {
|
|
return err
|
|
}
|
|
v.state.sessions[string(row.TokenHash)] = row
|
|
return nil
|
|
}
|
|
|
|
func (v *fakeWebView) DeleteSession(ctx context.Context, tokenHash []byte) (bool, error) {
|
|
if err := v.call("DeleteSession"); err != nil {
|
|
return false, err
|
|
}
|
|
_, ok := v.state.sessions[string(tokenHash)]
|
|
delete(v.state.sessions, string(tokenHash))
|
|
return ok, nil
|
|
}
|
|
|
|
func (v *fakeWebView) deleteSessions(userID int64, keep []byte) int64 {
|
|
var n int64
|
|
for k, s := range v.state.sessions {
|
|
if s.UserID == userID && k != string(keep) {
|
|
delete(v.state.sessions, k)
|
|
n++
|
|
}
|
|
}
|
|
return n
|
|
}
|
|
|
|
func (v *fakeWebView) DeleteUserSessions(ctx context.Context, userID int64) (int64, error) {
|
|
if err := v.call("DeleteUserSessions"); err != nil {
|
|
return 0, err
|
|
}
|
|
return v.deleteSessions(userID, nil), nil
|
|
}
|
|
|
|
func (v *fakeWebView) DeleteUserSessionsExcept(ctx context.Context, userID int64, keep []byte) (int64, error) {
|
|
if err := v.call("DeleteUserSessionsExcept"); err != nil {
|
|
return 0, err
|
|
}
|
|
return v.deleteSessions(userID, keep), nil
|
|
}
|
|
|
|
func (v *fakeWebView) TouchLastLogin(ctx context.Context, id int64, now time.Time) error {
|
|
if err := v.call("TouchLastLogin"); err != nil {
|
|
return err
|
|
}
|
|
v.state.users[id-1].LastLoginAt = sql.NullTime{Time: now, Valid: true}
|
|
return nil
|
|
}
|
|
|
|
func (v *fakeWebView) CreateUser(ctx context.Context, username, role, passwordHash string, now time.Time) (userRow, error) {
|
|
if err := v.call("CreateUser"); err != nil {
|
|
return userRow{}, err
|
|
}
|
|
if _, err := v.userByUsername(username); err == nil {
|
|
return userRow{}, errUsernameTaken
|
|
}
|
|
u := userRow{ID: int64(len(v.state.users) + 1), Username: username, Role: role, PasswordHash: passwordHash, CreatedAt: dbTime(now), UpdatedAt: dbTime(now)}
|
|
v.state.users = append(v.state.users, u)
|
|
return u, nil
|
|
}
|
|
|
|
func (v *fakeWebView) UserByIDForUpdate(ctx context.Context, id int64) (userRow, error) {
|
|
if err := v.call("UserByIDForUpdate"); err != nil {
|
|
return userRow{}, err
|
|
}
|
|
if id < 1 || int(id) > len(v.state.users) {
|
|
return userRow{}, errRowNotFound
|
|
}
|
|
return v.state.users[id-1], nil
|
|
}
|
|
|
|
func (v *fakeWebView) UserByUsernameForUpdate(ctx context.Context, username string) (userRow, error) {
|
|
if err := v.call("UserByUsernameForUpdate"); err != nil {
|
|
return userRow{}, err
|
|
}
|
|
return v.userByUsername(username)
|
|
}
|
|
|
|
func (v *fakeWebView) LockActiveAdmins(ctx context.Context) ([]userRow, error) {
|
|
if err := v.call("LockActiveAdmins"); err != nil {
|
|
return nil, err
|
|
}
|
|
if v.store.onLock != nil {
|
|
v.store.onLock(v.state)
|
|
}
|
|
var out []userRow
|
|
for _, u := range v.state.users {
|
|
if u.Role == roleAdmin && !u.DeletedAt.Valid {
|
|
out = append(out, u)
|
|
}
|
|
}
|
|
return out, nil
|
|
}
|
|
|
|
func (v *fakeWebView) SetRole(ctx context.Context, id int64, role string, now time.Time) error {
|
|
if err := v.call("SetRole"); err != nil {
|
|
return err
|
|
}
|
|
v.state.users[id-1].Role = role
|
|
v.state.users[id-1].UpdatedAt = now
|
|
return nil
|
|
}
|
|
|
|
func (v *fakeWebView) SetPassword(ctx context.Context, id int64, hash string, now time.Time) error {
|
|
if err := v.call("SetPassword"); err != nil {
|
|
return err
|
|
}
|
|
v.state.users[id-1].PasswordHash = hash
|
|
v.state.users[id-1].UpdatedAt = now
|
|
return nil
|
|
}
|
|
|
|
func (v *fakeWebView) MarkDeleted(ctx context.Context, id int64, now time.Time) error {
|
|
if err := v.call("MarkDeleted"); err != nil {
|
|
return err
|
|
}
|
|
v.state.users[id-1].DeletedAt = sql.NullTime{Time: now, Valid: true}
|
|
return nil
|
|
}
|
|
|
|
func (v *fakeWebView) GrantDelegation(ctx context.Context, zone string, userID, createdBy int64, now time.Time) (bool, error) {
|
|
if err := v.call("GrantDelegation"); err != nil {
|
|
return false, err
|
|
}
|
|
k := delegationKey{zone, userID}
|
|
if _, ok := v.state.delegations[k]; ok {
|
|
return false, nil
|
|
}
|
|
v.state.delegations[k] = delegationRow{Zone: zone, UserID: userID, Username: v.state.users[userID-1].Username, CreatedAt: now, CreatedBy: createdBy}
|
|
return true, nil
|
|
}
|
|
|
|
func (v *fakeWebView) RevokeDelegation(ctx context.Context, zone string, userID int64) (bool, error) {
|
|
if err := v.call("RevokeDelegation"); err != nil {
|
|
return false, err
|
|
}
|
|
k := delegationKey{zone, userID}
|
|
_, ok := v.state.delegations[k]
|
|
delete(v.state.delegations, k)
|
|
return ok, nil
|
|
}
|
|
|
|
func fakeHash(password string) string {
|
|
return "$fake$" + password
|
|
}
|
|
|
|
func fakeVerify(password, encoded string) bool {
|
|
return encoded == fakeHash(password)
|
|
}
|
|
|
|
type testClock struct {
|
|
mu sync.Mutex
|
|
now time.Time
|
|
}
|
|
|
|
func (c *testClock) Now() time.Time {
|
|
c.mu.Lock()
|
|
defer c.mu.Unlock()
|
|
return c.now
|
|
}
|
|
|
|
func (c *testClock) advance(d time.Duration) {
|
|
c.mu.Lock()
|
|
defer c.mu.Unlock()
|
|
c.now = c.now.Add(d)
|
|
}
|
|
|
|
type lockedBuffer struct {
|
|
mu sync.Mutex
|
|
buf bytes.Buffer
|
|
}
|
|
|
|
func (b *lockedBuffer) Write(p []byte) (int, error) {
|
|
b.mu.Lock()
|
|
defer b.mu.Unlock()
|
|
return b.buf.Write(p)
|
|
}
|
|
|
|
func (b *lockedBuffer) String() string {
|
|
b.mu.Lock()
|
|
defer b.mu.Unlock()
|
|
return b.buf.String()
|
|
}
|
|
|
|
type webHarness struct {
|
|
t *testing.T
|
|
s *WebServer
|
|
store *fakeWebStore
|
|
clock *testClock
|
|
logs *lockedBuffer
|
|
handler http.Handler
|
|
users map[string]userRow
|
|
}
|
|
|
|
type webOption func(cfg *Config)
|
|
|
|
func newWebHarness(t *testing.T, opts ...webOption) *webHarness {
|
|
t.Helper()
|
|
cfg := Config{AppName: "Test DNS", CookieSecure: true, SessionIdleTimeout: time.Hour, SessionMaxAge: 12 * time.Hour, LogLevel: LevelTrace}
|
|
for _, o := range opts {
|
|
o(&cfg)
|
|
}
|
|
h := &webHarness{t: t, store: newFakeWebStore(), clock: &testClock{now: webNow}, logs: &lockedBuffer{}, users: map[string]userRow{}}
|
|
h.s = newWebServer(cfg, newLogger(h.logs, LevelTrace), nil, tableNames{}, h.clock.Now)
|
|
h.s.store = h.store
|
|
h.s.hashPassword = func(p string) (string, error) { return fakeHash(p), nil }
|
|
h.s.verifyPassword = fakeVerify
|
|
h.handler = h.s.Handler()
|
|
return h
|
|
}
|
|
|
|
func (h *webHarness) withHandlers(handlers map[string]apiHandler) {
|
|
h.s.apiHandlerSet = handlers
|
|
h.handler = h.s.Handler()
|
|
}
|
|
|
|
func (h *webHarness) withFakeZoneHandlers() {
|
|
handlers := frameworkAPIHandlers(h.s)
|
|
maps.Copy(handlers, fakeZoneHandlers())
|
|
h.withHandlers(handlers)
|
|
}
|
|
|
|
func fakeZoneHandlers() map[string]apiHandler {
|
|
out := map[string]apiHandler{}
|
|
for _, op := range zoneOperations {
|
|
kind := ""
|
|
for _, o := range auditOperations {
|
|
if o.Name == op {
|
|
kind = o.Kind
|
|
}
|
|
}
|
|
if kind == auditKindRead {
|
|
out[op] = func(ctx context.Context, c *apiContext) (apiResponse, error) {
|
|
return okJSON(map[string]string{"operation": op, "zone": c.Zone}), nil
|
|
}
|
|
continue
|
|
}
|
|
out[op] = func(ctx context.Context, c *apiContext) (apiResponse, error) {
|
|
err := c.Server.store.InTx(ctx, func(tx webTx) error {
|
|
c.Entry.After = []byte(`{"fake":true}`)
|
|
return c.writeChangeAuditWith(ctx, tx, http.StatusOK)
|
|
})
|
|
if err != nil {
|
|
return apiResponse{}, err
|
|
}
|
|
return okJSON(map[string]string{"operation": op}), nil
|
|
}
|
|
}
|
|
return out
|
|
}
|
|
|
|
func (h *webHarness) user(username, role string) userRow {
|
|
u := h.store.addUser(username, role)
|
|
h.users[username] = u
|
|
return u
|
|
}
|
|
|
|
func (h *webHarness) login(u userRow) string {
|
|
return h.store.addSession(u, h.clock.Now(), h.clock.Now())
|
|
}
|
|
|
|
type webRequest struct {
|
|
method string
|
|
path string
|
|
token string
|
|
body string
|
|
ctype string
|
|
header map[string]string
|
|
remote string
|
|
rawBody io.Reader
|
|
chunked bool
|
|
}
|
|
|
|
type webResult struct {
|
|
status int
|
|
header http.Header
|
|
body string
|
|
audit []fakeAuditInsert
|
|
}
|
|
|
|
func (h *webHarness) do(req webRequest) webResult {
|
|
h.t.Helper()
|
|
var body io.Reader = strings.NewReader(req.body)
|
|
if req.rawBody != nil {
|
|
body = req.rawBody
|
|
}
|
|
r := httptest.NewRequest(req.method, req.path, body)
|
|
if req.body == "" && req.rawBody == nil {
|
|
r = httptest.NewRequest(req.method, req.path, nil)
|
|
}
|
|
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
|
|
}
|
|
if req.body != "" {
|
|
ct := req.ctype
|
|
if ct == "" {
|
|
ct = "application/json"
|
|
}
|
|
r.Header.Set("Content-Type", ct)
|
|
}
|
|
if req.token != "" {
|
|
r.AddCookie(&http.Cookie{Name: sessionCookieName, Value: req.token})
|
|
}
|
|
for k, v := range req.header {
|
|
r.Header.Set(k, v)
|
|
}
|
|
before := h.store.auditCount()
|
|
w := httptest.NewRecorder()
|
|
h.handler.ServeHTTP(w, r)
|
|
rows := h.store.auditRows()
|
|
return webResult{status: w.Code, header: w.Header(), body: w.Body.String(), audit: rows[before:]}
|
|
}
|
|
|
|
func (h *webHarness) api(method, path, token, body string) webResult {
|
|
h.t.Helper()
|
|
return h.do(webRequest{method: method, path: apiPrefix + path, token: token, body: body})
|
|
}
|
|
|
|
func expectOneAudit(t *testing.T, res webResult, operation string, status int) auditEntry {
|
|
t.Helper()
|
|
if len(res.audit) != 1 {
|
|
t.Fatalf("%s: %d audit rows, want 1 (status %d body %s)", operation, len(res.audit), res.status, res.body)
|
|
}
|
|
e := res.audit[0].entry
|
|
if e.Operation != operation || !e.Status.Valid || e.Status.Int64 != int64(status) {
|
|
t.Fatalf("audit row %+v, want operation %s status %d", e, operation, status)
|
|
}
|
|
if status >= 400 {
|
|
var body map[string]any
|
|
_ = json.Unmarshal([]byte(res.body), &body)
|
|
msg, _ := body["error"].(string)
|
|
if !e.Error.Valid || (strings.HasPrefix(res.body, "{") && res.status == status && e.Error.String != msg) {
|
|
t.Fatalf("audit error %v, body %s", e.Error, res.body)
|
|
}
|
|
} else if e.Error.Valid {
|
|
t.Fatalf("audit error set on success: %v", e.Error)
|
|
}
|
|
return e
|
|
}
|